Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
90 lines (70 loc) · 1.95 KB
/
Copy pathlib.rs
File metadata and controls
90 lines (70 loc) · 1.95 KB
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
pub struct Queue<T> {
older: Vec<T>,
younger: Vec<T>
}
impl<T> Queue<T> {
pub fn new() -> Queue<T> {
Queue { older: Vec::new(), younger: Vec::new() }
}
pub fn push(&mut self, t: T) {
self.younger.push(t);
}
pub fn is_empty(&self) -> bool {
self.older.is_empty() && self.younger.is_empty()
}
pub fn pop(&mut self) -> Option<T> {
if self.older.is_empty() {
use std::mem::swap;
if self.younger.is_empty() {
return None;
}
// Bring the elements in younger over to older, and put them in
// the promised order.
swap(&mut self.older, &mut self.younger);
self.older.reverse();
}
// Now older is guaranteed to have something. Vec's pop method
// already returns an Option, so we're set.
self.older.pop()
}
pub fn split(self) -> (Vec<T>, Vec<T>) {
(self.older, self.younger)
}
}
#[test]
fn test() {
let mut q = Queue::new();
q.push('*');
assert_eq!(q.pop(), Some('*'));
assert_eq!(q.pop(), None);
q.push('0');
q.push('1');
assert_eq!(q.pop(), Some('0'));
q.push('∞');
assert_eq!(q.pop(), Some('1'));
assert_eq!(q.pop(), Some('∞'));
assert_eq!(q.pop(), None);
assert!(q.is_empty());
q.push('☉');
assert!(!q.is_empty());
q.pop();
assert!(q.is_empty());
let mut q = Queue::new();
q.push('P');
q.push('D');
assert_eq!(q.pop(), Some('P'));
q.push('X');
assert_eq!(q.split(), (vec!['D'], vec!['X']));
}
#[test]
fn test_generic() {
let mut q = Queue::<char>::new();
&mut q;
drop(q);
let mut q = Queue::new();
let mut r = Queue::new();
q.push("CAD"); // apparently a Queue<&'static str>
r.push(0.74); // apparently a Queue<f64>
q.push("BTC"); // Bitcoins per USD, 2017-5
r.push(2737.7); // Rust fails to detect irrational exuberance
}