1
2
3
4
5
6 package net.sf.zel.vm;
7
8 import java.util.Arrays;
9 import net.sf.zel.math.ExtendedMathContext;
10 import net.sf.zel.math.MathUtil;
11
12
13
14
15
16 public class ProgramBuilder {
17
18
19 public static final int defaultSize = 32;
20
21 public static final int maxGrowthSize = 512;
22
23 private Object [] instructions;
24
25 private int instrNumber;
26
27 private Program.Type type;
28
29 public static int counter =0;
30
31 public static final synchronized int generateID()
32 {
33 return counter++;
34 }
35
36
37
38
39 public ProgramBuilder()
40 {
41 instructions = new Object[defaultSize];
42 instrNumber=0;
43 type = Program.Type.NONDETERMINISTIC;
44 }
45
46
47
48
49
50 public ProgramBuilder(final int size)
51 {
52 instructions = new Object[MathUtil.closestPowerOf2(size)];
53 instrNumber=0;
54 this.type = Program.Type.NONDETERMINISTIC;
55 }
56
57
58
59
60 public Program.Type getType()
61 {
62 return type;
63 }
64
65
66
67
68 public void setType(Program.Type type)
69 {
70 this.type = type;
71 }
72
73 public void add(Object object)
74 {
75 ensureCapacity(instrNumber + 1);
76 instructions[instrNumber++] = object;
77 }
78
79 public void set(int idx, Object object)
80 {
81 ensureCapacity(idx + 1);
82 instructions[idx] = object;
83 instrNumber = Math.max(idx+1, instrNumber);
84 }
85
86
87
88 public void addAll(Object [] objects)
89 {
90 ensureCapacity(instrNumber + objects.length);
91 System.arraycopy(objects, 0, instructions, instrNumber,objects.length);
92 instrNumber += objects.length;
93 }
94
95
96 public void setAll(int idx, Object [] objects)
97 {
98 ensureCapacity(idx + objects.length);
99 System.arraycopy(objects, 0, instructions, idx,objects.length);
100 instrNumber = Math.max(objects.length + idx, instrNumber);
101 }
102
103
104 public void addAll(ProgramBuilder opb)
105 {
106 ensureCapacity(instrNumber + opb.instrNumber);
107 System.arraycopy(opb.instructions, 0, instructions, instrNumber, opb.instrNumber);
108 instrNumber += opb.instrNumber;
109 }
110
111
112
113
114
115
116
117
118
119
120 public void ensureCapacity(int minCapacity) {
121 int oldCapacity = instructions.length;
122 if (minCapacity > oldCapacity) {
123 int newCapacity = 0;
124 if (oldCapacity > maxGrowthSize)
125 newCapacity = oldCapacity + maxGrowthSize;
126 else
127 newCapacity = oldCapacity << 1;
128
129 if (newCapacity < minCapacity)
130 newCapacity = minCapacity;
131 instructions = Arrays.copyOf(instructions,newCapacity);
132 }
133 }
134
135
136 public int size()
137 {
138 return instrNumber;
139 }
140
141 public Object[] toArray()
142 {
143 return Arrays.copyOf(instructions, instrNumber);
144 }
145
146 public Program toProgram()
147 {
148 return new Program(instructions,0,instrNumber,type,
149 ExtendedMathContext.CURRENT_EXTENDED_MATH_CONTEXT.get());
150 }
151
152 }