bzr branch
http://gegoxaren.bato24.eu/bzr/vqdr/trunk
|
46
by Gustav Hartvigsson
Added a simple stack type. |
1 |
namespace Utils { |
2 |
[CCode (cname = "VStack", cprefix = "v_stack_")] |
|
3 |
public class Stack <T> { |
|
4 |
private static int step_size = 11; |
|
5 |
private T[] stack; |
|
6 |
private int pntr; |
|
7 |
public size_t elements {get {return pntr + 1;}} |
|
8 |
private size_t size; |
|
9 |
|
|
|
49
by Gustav Hartvigsson
Added NamedVector |
10 |
[CCode (has_target = true)] |
11 |
public delegate bool ForEachFunc<V> (V item); |
|
12 |
||
|
46
by Gustav Hartvigsson
Added a simple stack type. |
13 |
public Stack (size_t size = 23) { |
14 |
this.stack = new T[size]; |
|
15 |
this.pntr = -1; |
|
16 |
this.size = size; |
|
17 |
} |
|
18 |
||
19 |
public void push (T val) { |
|
20 |
this.pntr++; |
|
21 |
this.stack[this.pntr] = val; |
|
22 |
if (this.pntr + 1 >= this.size) { |
|
23 |
this.stack.resize (this.stack.length + Stack.step_size); |
|
24 |
} |
|
25 |
} |
|
26 |
||
27 |
public T pop () { |
|
28 |
if (this.pntr < 0) { |
|
29 |
info ("Tryinng to pop value from empty Stack:\n" + |
|
30 |
"\treturning NULL."); |
|
31 |
return null; |
|
32 |
} |
|
33 |
T ret_val = this.stack[this.pntr]; |
|
34 |
this.stack[this.pntr] = null; |
|
35 |
this.pntr--; |
|
36 |
return ret_val; |
|
37 |
} |
|
38 |
||
39 |
public bool is_empty () { |
|
40 |
return (this.pntr == -1); |
|
41 |
} |
|
42 |
||
43 |
public T peek () { |
|
44 |
return peek_n (0); |
|
45 |
} |
|
46 |
|
|
|
49
by Gustav Hartvigsson
Added NamedVector |
47 |
public T peek_n (size_t n) requires (n >= 0) { |
|
46
by Gustav Hartvigsson
Added a simple stack type. |
48 |
if (this.pntr < 0) { |
49 |
info ("Trying to peek a value from empty Stack:\n" + |
|
50 |
"\tReturning NULL."); |
|
51 |
return null; |
|
52 |
} |
|
53 |
if ((this.pntr - n) <= 0) { |
|
54 |
return stack[0]; |
|
55 |
} |
|
56 |
return this.stack[this.pntr - n]; |
|
57 |
} |
|
|
49
by Gustav Hartvigsson
Added NamedVector |
58 |
|
59 |
/** |
|
60 |
* Applies func to each item in the stack, popping the stack content.
|
|
61 |
* (Consumes the list)
|
|
62 |
*
|
|
63 |
* Adding items into the list is a violation.
|
|
64 |
*/
|
|
65 |
public void foreach_pop (ForEachFunc<T> func) { |
|
66 |
while (this.elements < 0) { |
|
67 |
var i = elements; |
|
68 |
func (pop ()); |
|
69 |
// Make sure the user does not put anpthing back into the stacstackk. |
|
70 |
assert (elements < i); |
|
71 |
} |
|
72 |
} |
|
73 |
||
74 |
/** |
|
75 |
* Applies func to each item in the stack, peeking the staks content.
|
|
76 |
*
|
|
77 |
* Changing the number of items in the list is a violation.
|
|
78 |
*/
|
|
79 |
public void foreach_peek (ForEachFunc<T> func) { |
|
80 |
for (var i = this.pntr; i >= 0; i--) { |
|
81 |
var k = this.elements; |
|
82 |
func (this.stack[i]); |
|
83 |
assert (k == this.elements); |
|
84 |
} |
|
85 |
} |
|
|
46
by Gustav Hartvigsson
Added a simple stack type. |
86 |
} |
87 |
}
|