-
Notifications
You must be signed in to change notification settings - Fork 72
/
queue.rs
107 lines (81 loc) · 2.04 KB
/
queue.rs
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
use std::collections::VecDeque;
pub struct Queue<T> {
vec: VecDeque<T>,
}
impl<T> Queue<T> {
pub fn new() -> Self {
Queue {
vec: VecDeque::new(),
}
}
pub fn enqueue(&mut self, item: T) {
self.vec.push_back(item);
}
pub fn len(&self) -> usize {
self.vec.len()
}
pub fn is_empty(&self) -> bool {
self.vec.is_empty()
}
pub fn peek(&self) -> Option<&T> {
self.vec.front()
}
pub fn dequeue(&mut self) -> Option<T> {
self.vec.pop_front()
}
}
#[cfg(test)]
mod tests {
use super::Queue;
#[test]
fn starts_empty() {
let mut q: Queue<String> = Queue::new();
assert!(q.is_empty());
assert_eq!(q.dequeue(), None);
assert_eq!(q.len(), 0);
assert_eq!(q.peek(), None);
}
#[test]
fn fills_and_empties() {
let mut q = Queue::new();
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
assert!(!q.is_empty());
assert_eq!(q.len(), 3);
assert_eq!(q.peek(), Some(&1));
q.dequeue();
q.dequeue();
q.dequeue();
assert!(q.is_empty());
assert_eq!(q.dequeue(), None);
assert_eq!(q.len(), 0);
assert_eq!(q.peek(), None);
}
#[test]
fn alternate_mutations() {
let mut q = Queue::new();
q.enqueue("A");
assert!(!q.is_empty());
assert_eq!(q.len(), 1);
assert_eq!(q.peek(), Some(&"A"));
q.enqueue("B");
assert!(!q.is_empty());
assert_eq!(q.len(), 2);
assert_eq!(q.peek(), Some(&"A"));
q.dequeue();
assert!(!q.is_empty());
assert_eq!(q.len(), 1);
assert_eq!(q.peek(), Some(&"B"));
q.enqueue("C");
q.enqueue("D");
assert!(!q.is_empty());
assert_eq!(q.len(), 3);
assert_eq!(q.peek(), Some(&"B"));
q.dequeue();
q.dequeue();
assert!(!q.is_empty());
assert_eq!(q.len(), 1);
assert_eq!(q.peek(), Some(&"D"));
}
}