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
use super::*;
pub struct SinkMap<'a, TInput, UInput, TResult, TError, TSink: Sized>
where
TSink: ISink<TInput = TInput, TResult = TResult, TError = TError>,
{
target: TSink,
map: Box<Fn(UInput) -> TInput + 'a>,
}
impl<'a, TInput, UInput, TResult, TError, TSink> SinkMap<'a, TInput, UInput, TResult, TError, TSink>
where
TSink: ISink<TInput = TInput, TResult = TResult, TError = TError>,
{
pub fn new<F: 'a>(target: TSink, map: F) -> Self
where
F: Fn(UInput) -> TInput + 'a,
{
SinkMap {
target,
map: Box::new(map),
}
}
}
impl<'a, TInput, UInput, TResult, TError, TSink> ISink
for SinkMap<'a, TInput, UInput, TResult, TError, TSink>
where
TSink: ISink<TInput = TInput, TResult = TResult, TError = TError>,
{
type TInput = UInput;
type TResult = TResult;
type TError = TError;
fn send(
&self,
input: <Self as ISink>::TInput,
) -> Result<<Self as ISink>::TResult, <Self as ISink>::TError> {
self.target.send((self.map)(input))
}
}
pub trait ISinkMap<'a, TInput, TResult, TError, TSink>
where
TSink: ISink<TInput = TInput, TResult = TResult, TError = TError>,
Self: ISink<TInput = TInput, TResult = TResult, TError = TError>,
{
fn map<UInput, F: Fn(UInput) -> TInput + 'a>(
self,
map: F,
) -> SinkMap<'a, TInput, UInput, TResult, TError, TSink>;
}
impl<'a, T, TInput, TResult, TError> ISinkMap<'a, TInput, TResult, TError, T> for T
where
Self: ISink<TInput = TInput, TResult = TResult, TError = TError>,
T: ISink<TInput = TInput, TResult = TResult, TError = TError>,
{
fn map<UInput, F: Fn(UInput) -> TInput + 'a>(
self,
map: F,
) -> SinkMap<'a, TInput, UInput, TResult, TError, T> {
SinkMap::new(self, map)
}
}
#[cfg(test)]
mod sink_map_tests {
use super::*;
use super::sink::*;
#[test]
fn should_explicitly_construct_a_sinkmap() {
let s = Sink::<usize, usize, ()>::new(|item| Ok(item));
let sm = SinkMap::new(s, |item: String| item.len());
assert_eq!(Ok(0), sm.send("".to_owned()));
assert_eq!(Ok(9), sm.send("some text".to_owned()));
}
#[test]
fn should_construct_a_sinkmap_through_the_map_function() {
let s = Sink::<usize, usize, ()>::new(|item| Ok(item)).map(|item: String| item.len());
assert_eq!(Ok(0), s.send("".to_owned()));
assert_eq!(Ok(9), s.send("some text".to_owned()));
}
}