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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
use std::ops::BitOr;
use signalo_traits::filter::Filter;
use signalo_traits::source::Source;
use signalo_traits::sink::Sink;
#[derive(Default, Clone, Debug)]
pub struct Pipe<T, U> {
lhs: T,
rhs: U,
}
impl<T, U> Pipe<T, U> {
#[inline]
pub fn new(lhs: T, rhs: U) -> Self {
Self { lhs, rhs }
}
}
impl<T, U> From<(T, U)> for Pipe<T, U> {
#[inline]
fn from(parts: (T, U)) -> Self {
let (lhs, rhs) = parts;
Self::new(lhs, rhs)
}
}
impl<T, U, Rhs> BitOr<Rhs> for Pipe<T, U> {
type Output = Pipe<Self, Rhs>;
#[inline]
fn bitor(self, rhs: Rhs) -> Self::Output {
Pipe::new(self, rhs)
}
}
impl<T, U, I> Filter<I> for Pipe<T, U>
where
T: Filter<I>,
U: Filter<T::Output>,
{
type Output = U::Output;
#[inline]
fn filter(&mut self, input: I) -> Self::Output {
self.rhs.filter(self.lhs.filter(input))
}
}
impl<T, U> Source for Pipe<T, U>
where
T: Source,
U: Filter<T::Output>,
{
type Output = U::Output;
#[inline]
fn source(&mut self) -> Option<Self::Output> {
self.lhs.source().map(|input| self.rhs.filter(input))
}
}
impl<T, U, I> Sink<I> for Pipe<T, U>
where
T: Filter<I>,
U: Sink<T::Output>,
{
type Output = U::Output;
#[inline]
fn sink(&mut self, input: I) {
self.rhs.sink(self.lhs.filter(input))
}
#[inline]
fn finalize(self) -> Self::Output {
self.rhs.finalize()
}
}
#[cfg(test)]
mod tests {
use super::*;
type Value = usize;
struct DummyFilterAdd;
impl Filter<Value> for DummyFilterAdd {
type Output = Value;
#[inline]
fn filter(&mut self, input: Value) -> Self::Output {
input + 1
}
}
struct DummyFilterMul;
impl Filter<Value> for DummyFilterMul {
type Output = Value;
#[inline]
fn filter(&mut self, input: Value) -> Self::Output {
input * 2
}
}
#[test]
fn test() {
let input = vec![0, 1, 7, 2, 5, 8, 16, 3, 19, 6, 14, 9, 9, 17, 17, 4, 12, 20, 20, 7];
let filter_add = DummyFilterAdd;
let filter_mul = DummyFilterMul;
let pipe = Pipe::new(filter_add, filter_mul);
let subject: Vec<_> = input.iter().scan(pipe, |pipe, &input| {
Some(pipe.filter(input))
}).collect();
let expected = vec![2, 4, 16, 6, 12, 18, 34, 8, 40, 14, 30, 20, 20, 36, 36, 10, 26, 42, 42, 16];
assert_eq!(subject, expected);
}
}