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
#[cfg(feature = "array-vec")]
pub mod arrayvec;
use crate::{Tick, TumblingWindow};
pub trait QueueCapAtLeast<const LEN: usize> {
type Item;
fn empty() -> Self;
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn deque(&mut self) -> Option<Self::Item>;
fn enque(&mut self, item: Self::Item);
fn get_latest(&self, n: usize) -> Option<&Self::Item>;
fn is_reach(&self) -> bool {
self.len() >= LEN
}
fn enque_and_deque_overflow(&mut self, item: Self::Item) -> Option<Self::Item> {
if self.is_reach() {
let oldest = self.deque();
if LEN > 0 {
self.enque(item);
}
oldest
} else {
if LEN > 0 {
self.enque(item);
}
None
}
}
}
#[derive(Debug, Clone)]
pub struct TumblingQueue<M: TumblingWindow, Q: QueueCapAtLeast<LEN>, const LEN: usize> {
pub(super) mode: M,
last_tick: Tick,
pub(super) queue: Q,
}
impl<M: TumblingWindow, Q: QueueCapAtLeast<LEN>, const LEN: usize> TumblingQueue<M, Q, LEN> {
pub(crate) fn new(mode: M) -> Self {
Self {
mode,
last_tick: Tick::BIG_BANG,
queue: Q::empty(),
}
}
pub(crate) fn enque_or_ignore(
&mut self,
tick: &Tick,
acc: &mut Option<Q::Item>,
) -> Option<Q::Item> {
if !self.mode.same_window(&self.last_tick, tick) {
self.last_tick = *tick;
if let Some(item) = acc.take() {
self.queue.enque_and_deque_overflow(item)
} else {
None
}
} else {
None
}
}
}