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
pub trait Reducer: Sized {
type State;
type Item;
fn reduce(&mut self, state: Self::State, item: &Self::Item) -> Self::State;
fn chain<R: Reducer<State=Self::State, Item=Self::Item>>(self, other: R) -> ChainedReducer<Self, R> {
ChainedReducer::new(self, other)
}
}
#[cfg(feature = "duktape-reducers")]
pub mod duktape;
pub struct ChainedReducer<R1: Reducer, R2: Reducer>(R1, R2);
impl<R1: Reducer, R2: Reducer> ChainedReducer<R1, R2> {
pub fn new(r1: R1, r2: R2) -> Self {
ChainedReducer(r1, r2)
}
}
impl<T, I, R1: Reducer<State=T, Item=I>, R2: Reducer<State=T, Item=I>> Reducer for ChainedReducer<R1, R2> {
type State = R1::State;
type Item = R1::Item;
fn reduce(&mut self, state: Self::State, item: &Self::Item) -> Self::State {
self.1.reduce(self.0.reduce(state, item), item)
}
}
#[cfg(test)]
mod tests {
use super::Reducer;
struct R<T>(T);
impl<T: Clone> Reducer for R<T> {
type State = T;
type Item = T;
fn reduce(&mut self, _state: Self::State, _item: &Self::Item) -> Self::State {
self.0.clone()
}
}
#[test]
fn chained_reducer() {
assert_eq!(R(1).chain(R(2)).reduce(0, &0), 2);
}
}