1 // Robert Burner Schadek rburners@gmail.com LGPL3
2 module stack;
3 
4 struct Stack(T) {
5 	private T[] stack;
6 	private size_t stptr;
7 
8 	pure void init(size_t size = 128) @safe {
9 		this.stack = new T[size];
10 		this.stptr = 0;
11 	}
12 
13 	pure ref Stack!(T) push(T elem) @safe {
14 		if(stack is null) {
15 			this.init();
16 		}
17 		if(this.stptr+1 == stack.length) {
18 			this.stack.length = this.stack.length*2;
19 		}
20 		this.stack[this.stptr++] = elem;
21 		return this;
22 	}
23 
24 	pure void pop() @safe nothrow {
25 		if(this.stptr > 0) {
26 			--this.stptr;
27 		}
28 	}
29 
30 	pure bool empty() const @safe nothrow {
31 		return this.stptr == 0;
32 	}
33 
34 	pure ref T top() @safe nothrow {
35 		if(this.stptr < 0) {
36 			assert(0, "Stack Empty");
37 		}
38 		return this.stack[this.stptr-1];
39 	}
40 
41 	@property pure size_t length() const @safe nothrow {
42 		return this.stptr;
43 	}
44 
45 	pure size_t getCapazity() const @safe nothrow {
46 		return this.stack.length;
47 	}
48 
49 	pure void clear() @safe nothrow {
50 		this.stptr = 0;
51 	}
52 }
53 
54 unittest {
55 	Stack!(int) i;
56 	i.push(44);
57 	assert(i.top() == 44);
58 	i.push(45);
59 	assert(i.top() == 45);
60 	i.pop();
61 	assert(i.top() == 44);
62 	i.pop();
63 	assert(i.empty());
64 
65 	class Tmp {
66 		uint a = 44;
67 	}
68 
69 	Stack!(Tmp) j;
70 	j.push(new Tmp());
71 	j.top().a = 88;
72 	assert(j.top().a == 88);
73 	j.push(new Tmp());
74 	j.push(new Tmp());
75 	j.push(new Tmp());
76 	assert(j.length() == 4);
77 }