1 /** 2 This module implements Stack 3 4 ──────────────────────────────────────────────────────────────────────────────── 5 6 Copyright (C) 2021 pillager86.rf.gd 7 8 This program is free software: you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation, either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT ANY 14 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 15 PARTICULAR PURPOSE. See the GNU General Public License for more details. 16 17 You should have received a copy of the GNU General Public License along with 18 this program. If not, see <https://www.gnu.org/licenses/>. 19 */ 20 module mildew.util.stack; 21 22 /// Stack data structure wrapper around dynamic D arrays 23 struct Stack(T) 24 { 25 public: 26 /// push an item to the stack and return its position 27 size_t push(T item) 28 { 29 _data ~= item; 30 return _data.length - 1; 31 } 32 /// pushes multiple items to the stack such that the last element is on the top 33 void push(T[] items) 34 { 35 _data ~= items; 36 } 37 /// pops one item from the stack 38 auto pop() 39 { 40 auto item = _data[$-1]; 41 _data = _data[0..$-1]; 42 return item; 43 } 44 /// pops multiple items from the stack 45 auto pop(size_t n) 46 { 47 auto items = _data[$-n..$]; 48 _data = _data[0..$-n]; 49 return items; 50 } 51 /// peek element at the top of array 52 auto peek() 53 { 54 return _data[$-1]; 55 } 56 /// number of stack elements 57 auto size() const 58 { 59 return _data.length; 60 } 61 62 /// set the size directly 63 auto size(size_t sz) 64 { 65 return _data.length = sz; 66 } 67 68 /// direct access to array. TODO: replace with an opIndex and opIndexAssign 69 auto array() { return _data; } 70 71 /// calls reserve on array 72 void reserve(size_t size) 73 { 74 _data.reserve(size); 75 } 76 77 /// the top element by reference 78 ref auto top() { return _data[$-1]; } 79 private: 80 T[] _data; 81 }