1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
use core::mem::size_of;

pub struct Stack<T: Copy> {
    top: *mut T,
    cur: *mut T,
    bot: *mut T,
}

#[derive(Debug, PartialEq)]
pub enum StackError {
    StackEmpty,
    StackFull,
    OverwriteInvalid,
}

impl<T: Copy> Stack<T> {
    pub fn new(bottom: *mut T, items: usize) -> Self {
        let top = bottom.wrapping_add(items);
        debug_assert!(top >= bottom);
        Self {
            top,
            bot: bottom,
            cur: top,
        }
    }

    #[inline]
    pub fn push(&mut self, item: T) -> Result<(), StackError> {
        let next_cur = self.cur.wrapping_sub(1);
        if next_cur < self.bot {
            return Err(StackError::StackFull);
        }
        self.cur = next_cur;
        unsafe {
            self.cur.write(item);
        }
        Ok(())
    }

    #[inline]
    pub fn depth(&self) -> usize {
        ((self.top as usize) - (self.cur as usize)) / size_of::<T>()
    }

    #[inline]
    pub fn try_pop(&mut self) -> Result<T, StackError> {
        match self.pop() {
            Some(v) => Ok(v),
            None => Err(StackError::StackEmpty),
        }
    }

    #[inline]
    pub fn pop(&mut self) -> Option<T> {
        let next_cur = self.cur.wrapping_add(1);
        if next_cur > self.top {
            return None;
        }
        let val = unsafe { self.cur.read() };
        self.cur = next_cur;
        Some(val)
    }

    #[inline]
    pub fn try_peek(&self) -> Result<T, StackError> {
        if self.cur == self.top {
            Err(StackError::StackEmpty)
        } else {
            Ok(unsafe { self.cur.read() })
        }
    }

    #[inline]
    pub fn peek(&self) -> Option<T> {
        if self.cur == self.top {
            None
        } else {
            Some(unsafe { self.cur.read() })
        }
    }

    #[inline]
    pub fn peek_mut(&mut self) -> Option<&mut T> {
        if self.cur == self.top {
            None
        } else {
            Some(unsafe { &mut *self.cur })
        }
    }

    #[inline]
    pub fn peek_back_n(&self, n: usize) -> Option<T> {
        let request = self.cur.wrapping_add(n);
        if request >= self.top {
            None
        } else {
            unsafe { Some(request.read()) }
        }
    }

    #[inline]
    pub fn try_peek_back_n(&self, n: usize) -> Result<T, StackError> {
        let request = self.cur.wrapping_add(n);
        if request >= self.top {
            Err(StackError::StackEmpty)
        } else {
            unsafe { Ok(request.read()) }
        }
    }

    #[inline]
    pub fn peek_back_n_mut(&mut self, n: usize) -> Option<&mut T> {
        let request = self.cur.wrapping_add(n);
        if request >= self.top {
            None
        } else {
            unsafe { Some(&mut *request) }
        }
    }

    #[inline]
    pub fn try_peek_back_n_mut(&mut self, n: usize) -> Result<&mut T, StackError> {
        let request = self.cur.wrapping_add(n);
        if request >= self.top {
            Err(StackError::StackEmpty)
        } else {
            unsafe { Ok(&mut *request) }
        }
    }

    #[inline]
    pub fn overwrite_back_n(&mut self, n: usize, item: T) -> Result<(), StackError> {
        let request = self.cur.wrapping_add(n);
        if request >= self.top {
            Err(StackError::OverwriteInvalid)
        } else {
            unsafe {
                request.write(item);
            }
            Ok(())
        }
    }

    #[inline]
    pub fn clear(&mut self) {
        self.cur = self.top;
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.cur == self.top
    }
}

#[cfg(test)]
pub mod test {
    use super::Stack;
    use crate::leakbox::LeakBox;
    use crate::Word;

    #[test]
    fn stack() {
        const ITEMS: usize = 16;
        let payload: LeakBox<Word> = LeakBox::new(ITEMS);

        let mut stack = Stack::<Word>::new(payload.ptr(), payload.len());

        for _ in 0..3 {
            for i in 0..(ITEMS as i32) {
                assert!(stack.push(Word::data(i)).is_ok());
            }
            assert!(stack.push(Word::data(100)).is_err());
            for i in (0..(ITEMS as i32)).rev() {
                assert_eq!(stack.pop().unwrap().into_data(), i);
            }
            assert!(stack.pop().is_none());
        }
    }
}