1 module nxt.appender_stack; 2 3 /** Stack using `std.array.Appender`. 4 * 5 * See_Also: http://forum.dlang.org/thread/wswbtzakdvpgaebuhbom@forum.dlang.org 6 */ 7 struct Stack(T) { 8 import std.array : Appender; 9 10 ref inout(T) top() inout @property => _app.data[$ - 1]; 11 bool empty() const @property => _app.data.length == 0; 12 13 /// Pop back value. 14 void pop() => _app.shrinkTo(_app.data.length - 1); 15 16 /// Pop back value and return it. 17 T takeBack() { 18 T value = top; 19 _app.shrinkTo(_app.data.length - 1); 20 return value; 21 } 22 23 void push(T t) => _app.put(t); 24 25 private Appender!(T[]) _app; 26 } 27 28 pure @safe unittest { 29 alias T = uint; 30 31 Stack!T s; 32 assert(s.empty); 33 34 // pushBack: 35 36 s.push(13); 37 assert(!s.empty); 38 assert(s.top == 13); 39 40 s.push(14); 41 assert(!s.empty); 42 assert(s.top == 14); 43 44 s.push(15); 45 assert(!s.empty); 46 assert(s.top == 15); 47 48 // pop: 49 50 s.pop(); 51 assert(!s.empty); 52 assert(s.top == 14); 53 54 s.pop(); 55 assert(!s.empty); 56 assert(s.top == 13); 57 58 s.pop(); 59 assert(s.empty); 60 61 // push: 62 63 s.push(13); 64 s.push(14); 65 s.push(15); 66 assert(!s.empty); 67 assert(s.top == 15); 68 69 // takeBack: 70 71 assert(s.takeBack() == 15); 72 assert(s.takeBack() == 14); 73 assert(s.takeBack() == 13); 74 75 assert(s.empty); 76 }