1use crate::error;
2use crate::lang::Error;
3
4type Result<T> = std::result::Result<T, Error>;
5
6#[derive(Clone)]
9pub struct Stack<T> {
10 overflow_message: &'static str,
11 vec: Vec<T>,
12}
13
14impl<T: std::fmt::Debug> std::fmt::Debug for Stack<T> {
15 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16 write!(f, "{:?}", self.vec)
17 }
18}
19
20impl<T> Stack<T> {
21 pub fn new(overflow_message: &'static str) -> Stack<T> {
22 Stack {
23 overflow_message,
24 vec: vec![],
25 }
26 }
27 fn max_len(&self) -> usize {
28 u16::max_value() as usize
29 }
30 fn overflow_check(&self) -> Result<()> {
31 if self.vec.len() > self.max_len() {
32 Err(error!(OutOfMemory; self.overflow_message))
33 } else {
34 Ok(())
35 }
36 }
37 fn underflow_error(&self) -> Error {
38 error!(InternalError; "UNDERFLOW")
39 }
40 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
41 self.vec.get_mut(index)
42 }
43 pub fn clear(&mut self) {
44 self.vec.clear()
45 }
46 pub fn drain<R>(&mut self, range: R) -> std::vec::Drain<'_, T>
47 where
48 R: std::ops::RangeBounds<usize>,
49 {
50 debug_assert!(range.end_bound() == std::ops::Bound::Unbounded);
51 self.vec.drain(range)
52 }
53 pub fn len(&self) -> usize {
54 self.vec.len()
55 }
56 pub fn is_empty(&self) -> bool {
57 self.vec.is_empty()
58 }
59 pub fn is_full(&self) -> bool {
60 self.vec.len() > self.max_len() - 32
61 }
62 pub fn last(&self) -> Option<&T> {
63 self.vec.last()
64 }
65 pub fn get(&self, index: usize) -> Option<&T> {
66 self.vec.get(index)
67 }
68 pub fn append(&mut self, other: &mut Stack<T>) -> Result<()> {
69 self.vec.append(&mut other.vec);
70 self.overflow_check()
71 }
72 pub fn push(&mut self, val: T) -> Result<()> {
73 self.vec.push(val);
74 self.overflow_check()
75 }
76 pub fn pop(&mut self) -> Result<T> {
77 match self.vec.pop() {
78 Some(v) => Ok(v),
79 None => Err(self.underflow_error()),
80 }
81 }
82 pub fn pop_2(&mut self) -> Result<(T, T)> {
83 let two = self.pop()?;
84 let one = self.pop()?;
85 Ok((one, two))
86 }
87 pub fn pop_n(&mut self, len: usize) -> Result<Stack<T>> {
88 if len > self.vec.len() {
89 Err(self.underflow_error())
90 } else {
91 let range = (self.vec.len() - len as usize)..;
92 let mut st: Stack<T> = Stack::new(self.overflow_message);
93 for item in self.drain(range) {
94 st.push(item)?;
95 }
96 Ok(st)
97 }
98 }
99}
100
101impl<T> IntoIterator for Stack<T> {
102 type Item = T;
103 type IntoIter = std::vec::IntoIter<Self::Item>;
104
105 fn into_iter(self) -> Self::IntoIter {
106 self.vec.into_iter()
107 }
108}