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
use alloc::vec::Vec;
#[derive(Debug)]
pub struct Stack<T> {
data: Vec<T>,
top: usize,
}
impl<T: Clone> Stack<T> {
pub fn new() -> Stack<T> {
Self {
data: Vec::new(),
top: 0,
}
}
pub fn is_empty(&self) -> bool {
if self.top == 0 {
true
} else {
false
}
}
pub fn push(&mut self, element: T) {
self.top += 1;
self.data.push(element);
}
pub fn pop(&mut self) -> anyhow::Result<T> {
if self.is_empty() {
return Err(anyhow::anyhow!("underflow"));
} else {
self.top -= 1;
let element = self.data.remove(self.top);
return Ok(element.clone());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_empty_success() {
let empty_stack = Stack::<i32>::new();
assert_eq!(true, empty_stack.is_empty());
}
#[test]
fn test_is_empty_faild() {
let mut empty_stack = Stack::<i32>::new();
empty_stack.push(1);
assert_eq!(false, empty_stack.is_empty());
}
#[test]
fn test_pop_element_success() {
let mut stack = Stack::<i32>::new();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
let ret = stack.pop().unwrap();
assert_eq!(ret, 4);
assert_eq!(false, stack.is_empty());
}
#[test]
fn test_pop_element_faild() {
let mut stack = Stack::<i32>::new();
let ret = stack.pop();
match ret {
Ok(_) => todo!(),
Err(err) => assert_eq!(err.to_string(), "underflow".to_string()),
}
}
}