algorithms_edu/data_structures/
queue.rs1pub trait Queue<T> {
2 fn with_capacity(capacity: usize) -> Self;
3 fn len(&self) -> usize;
4 fn is_empty(&self) -> bool {
5 self.len() == 0
6 }
7 fn push_back(&mut self, val: T);
8 fn pop_front(&mut self) -> Option<T>;
9}
10
11pub struct FixedCapacityQueue<T: Clone> {
16 ar: Box<[Option<T>]>,
17 front: usize,
18 back: usize,
19 capacity: usize,
20}
21
22impl<T: Clone> FixedCapacityQueue<T> {
23 pub fn with_capacity(capacity: usize) -> Self {
26 Self {
27 front: 0,
28 back: 0,
29 capacity,
30 ar: vec![None; capacity].into_boxed_slice(),
31 }
32 }
33
34 pub fn peek(&self) -> Option<&T> {
35 self.ar.get(self.front).and_then(|x| x.as_ref())
36 }
37}
38
39impl<T: Clone> Queue<T> for FixedCapacityQueue<T> {
40 fn len(&self) -> usize {
41 self.back - self.front
42 }
43 fn with_capacity(capacity: usize) -> Self {
44 Self::with_capacity(capacity)
45 }
46 fn push_back(&mut self, val: T) {
47 assert!(self.back < self.capacity, "Queue too small!");
48 self.ar[self.back] = Some(val);
49 self.back += 1;
50 }
51 fn pop_front(&mut self) -> Option<T> {
52 if self.is_empty() {
53 None
54 } else {
55 let res = self.ar[self.front].take();
56 self.front += 1;
57 res
58 }
59 }
60}
61
62impl<T: Clone> Queue<T> for std::collections::VecDeque<T> {
63 fn len(&self) -> usize {
64 self.len()
65 }
66 fn with_capacity(capacity: usize) -> Self {
67 Self::with_capacity(capacity)
68 }
69 fn push_back(&mut self, val: T) {
70 self.push_back(val);
71 }
72 fn pop_front(&mut self) -> Option<T> {
73 self.pop_front()
74 }
75}