algo_rs/data_structure/stack/
fixed_stack.rs

1use crate::data_structure::stack::Stack;
2
3pub struct FixedStack<T> {
4    inner: Vec<T>,
5    size: usize,
6}
7
8impl<T> FixedStack<T> {
9    pub fn new(size: usize) -> Self {
10        Self {
11            size,
12            inner: Vec::<T>::with_capacity(size),
13        }
14    }
15}
16
17impl<T> Stack<T> for FixedStack<T> {
18    fn push(&mut self, item: T) {
19        if self.inner.len() == self.size {
20            panic!("stack is full")
21        }
22        self.inner.push(item);
23    }
24
25    fn pop(&mut self) -> Option<T> {
26        self.inner.pop()
27    }
28
29    fn top(&self) -> Option<&T> {
30        self.inner.last()
31    }
32
33    fn is_empty(&self) -> bool {
34        self.inner.is_empty()
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use crate::data_structure::stack::fixed_stack::FixedStack;
41    use crate::data_structure::stack::Stack;
42
43    #[test]
44    fn test_push_pop() {
45        let mut stack = FixedStack::<i32>::new(10);
46        stack.push(1);
47        stack.push(2);
48        stack.push(3);
49        assert_eq!(Some(3), stack.pop());
50        assert_eq!(Some(2), stack.pop());
51        assert_eq!(Some(1), stack.pop());
52        assert_eq!(None, stack.pop());
53    }
54
55    #[test]
56    fn test_is_empty() {
57        let mut stack = FixedStack::<i32>::new(10);
58        assert_eq!(true, stack.is_empty());
59        stack.push(1);
60        assert_eq!(false, stack.is_empty());
61        stack.pop();
62        assert_eq!(true, stack.is_empty());
63    }
64
65    #[test]
66    #[should_panic(expected = "stack is full")]
67    fn test_push_full_stack() {
68        let mut stack = FixedStack::new(0);
69        stack.push(1);
70    }
71
72    #[test]
73    fn test_top() {
74        let mut stack = FixedStack::<i32>::new(3);
75        assert_eq!(None, stack.top());
76        stack.push(1);
77        assert_eq!(Some(&1), stack.top());
78        stack.push(2);
79        assert_eq!(Some(&2), stack.top());
80        stack.pop();
81        assert_eq!(Some(&1), stack.top());
82        stack.pop();
83        assert_eq!(None, stack.top());
84    }
85}