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