-
Notifications
You must be signed in to change notification settings - Fork 7
/
rust_queue.rs
70 lines (59 loc) · 1.26 KB
/
rust_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
struct Queue<T> {
queue: Vec<T>
}
impl<T> Queue<T> {
fn new() -> Self {
Queue { queue: Vec::new() }
}
fn enqueue(&mut self, item: T) {
self.queue.push(item);
}
fn dequeue(&mut self) -> Option<T> {
if self.is_empty() {
return None
}
return Some(self.queue.remove(0))
}
fn len(&self) -> usize {
self.queue.len()
}
fn is_empty(&self) -> bool {
self.queue.is_empty()
}
fn peek(&self) -> Option<&T> {
self.queue.first()
}
}
#[test]
fn test_enqueue() {
let mut q: Queue<i32> = Queue::new();
assert!(q.is_empty());
assert_eq!(q.len(), 0);
q.enqueue(3);
assert!(!q.is_empty());
assert_eq!(q.len(), 1);
}
#[test]
fn test_dequeue() {
let mut q: Queue<i32> = Queue::new();
q.enqueue(3);
assert!(!q.is_empty());
assert_eq!(q.len(), 1);
let item = q.dequeue();
assert_eq!(item.unwrap(), 3);
}
#[test]
fn test_empty_dequeue() {
let mut q: Queue<i32> = Queue::new();
assert!(q.is_empty());
let item = q.dequeue();
assert!(item.is_none());
}
#[test]
fn test_peek() {
let mut q: Queue<i32> = Queue::new();
q.enqueue(3);
q.enqueue(5);
let item = q.peek();
assert_eq!(*item.unwrap(), 3);
}