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
pub trait Queue<T> {
fn with_capacity(capacity: usize) -> Self;
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn push_back(&mut self, val: T);
fn pop_front(&mut self) -> Option<T>;
}
pub struct FixedCapacityQueue<T: Clone> {
ar: Box<[Option<T>]>,
front: usize,
back: usize,
capacity: usize,
}
impl<T: Clone> FixedCapacityQueue<T> {
pub fn with_capacity(capacity: usize) -> Self {
Self {
front: 0,
back: 0,
capacity,
ar: vec![None; capacity].into_boxed_slice(),
}
}
pub fn peek(&self) -> Option<&T> {
self.ar.get(self.front).and_then(|x| x.as_ref())
}
}
impl<T: Clone> Queue<T> for FixedCapacityQueue<T> {
fn len(&self) -> usize {
self.back - self.front
}
fn with_capacity(capacity: usize) -> Self {
Self::with_capacity(capacity)
}
fn push_back(&mut self, val: T) {
assert!(self.back < self.capacity, "Queue too small!");
self.ar[self.back] = Some(val);
self.back += 1;
}
fn pop_front(&mut self) -> Option<T> {
if self.is_empty() {
None
} else {
let res = self.ar[self.front].take();
self.front += 1;
res
}
}
}
impl<T: Clone> Queue<T> for std::collections::VecDeque<T> {
fn len(&self) -> usize {
self.len()
}
fn with_capacity(capacity: usize) -> Self {
Self::with_capacity(capacity)
}
fn push_back(&mut self, val: T) {
self.push_back(val);
}
fn pop_front(&mut self) -> Option<T> {
self.pop_front()
}
}