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
pub struct Queue<T> {
items: Vec<T>,
}
impl<T> Queue<T> {
pub fn new() -> Self {
Self { items: Vec::new() }
}
pub fn enqueue(&mut self, item: T) {
self.items.push(item);
}
pub fn dequeue(&mut self) -> Option<T> {
match self.items.is_empty() {
false => Some(self.items.remove(0)),
true => None,
}
}
pub fn peek(&self) -> Option<&T> {
self.items.first()
}
pub fn size(&self) -> usize {
self.items.len()
}
}
#[cfg(test)]
mod impl_by_vec {
use super::*;
#[test]
fn new() {
let queue = Queue::<()>::new();
assert!(queue.items.is_empty());
}
#[test]
fn enqueue() {
let mut queue = Queue::new();
queue.enqueue(32);
assert_eq!(Some(&32), queue.peek());
assert_eq!(1, queue.size());
}
#[test]
fn dequeue() {
let mut queue = Queue::new();
queue.enqueue(32);
assert_eq!(Some(32), queue.dequeue());
assert_eq!(None, queue.dequeue());
}
#[test]
fn size() {
let mut queue = Queue::new();
queue.enqueue(-20);
assert_eq!(1, queue.size());
assert_eq!(Some(&-20), queue.peek());
}
#[test]
fn integration() {
let mut queue = Queue::new();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
assert_eq!(3, queue.size());
assert_eq!(Some(1), queue.dequeue());
assert_eq!(Some(&2), queue.peek());
assert_eq!(Some(2), queue.dequeue());
assert_eq!(Some(3), queue.dequeue());
assert_eq!(0, queue.size());
}
}