-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmod.rs
80 lines (75 loc) · 2.1 KB
/
mod.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
71
72
73
74
75
76
77
78
79
80
use std::collections::VecDeque;
use alga::general::AbstractMagma;
use alga::general::Identity;
use crate::FifoWindow;
use crate::ops::AggregateOperator;
use crate::ops::AggregateMonoid;
#[derive(Clone)]
pub struct TwoStacksLite<BinOp>
where
BinOp: AggregateMonoid<BinOp> + AggregateOperator + Clone
{
queue: VecDeque<BinOp::Partial>,
agg_back: BinOp::Partial,
front_len: usize,
}
impl<BinOp> FifoWindow<BinOp> for TwoStacksLite<BinOp>
where
BinOp: AggregateMonoid<BinOp> + AggregateOperator + Clone
{
fn new() -> Self {
Self {
queue: VecDeque::new(),
agg_back: BinOp::Partial::identity(),
front_len: 0,
}
}
fn name() -> &'static str {
"two_stacks_lite"
}
fn push(&mut self, v: BinOp::In) {
let lifted = BinOp::lift(v);
self.queue.push_back(lifted.clone());
self.agg_back = self.agg_back.operate(&lifted);
}
fn pop(&mut self) {
if !self.queue.is_empty() {
let end = self.queue.len() - 1;
if self.front_len == 0 {
let mut accum = BinOp::Partial::identity();
for partial in self.queue.iter_mut().rev() {
accum = partial.operate(&accum);
*partial = accum.clone();
}
self.front_len = end + 1;
self.agg_back = BinOp::Partial::identity();
}
self.front_len -= 1;
self.queue.pop_front();
}
}
fn query(&self) -> BinOp::Out {
let f = &self.agg_front();
let b = &self.agg_back;
BinOp::lower(&f.operate(&b))
}
fn len(&self) -> usize {
self.queue.len()
}
fn is_empty(&self) -> bool {
self.queue.is_empty()
}
}
impl<BinOp> TwoStacksLite<BinOp>
where
BinOp: AggregateMonoid<BinOp> + AggregateOperator + Clone
{
#[inline(always)]
fn agg_front(&self) -> BinOp::Partial {
if self.front_len == 0 || self.queue.is_empty() {
BinOp::Partial::identity()
} else {
self.queue.front().unwrap().clone()
}
}
}