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
use signalo_traits::Source;
#[derive(Clone, Debug)]
pub struct State<T, U> {
pub inner: T,
#[cfg_attr(feature = "cargo-clippy", allow(clippy::option_option))]
pub peeked: Option<Option<U>>,
}
#[derive(Clone, Debug)]
pub struct Peek<T, U> {
state: State<T, U>,
}
impl<T, U> Peek<T, U>
where
T: Source<Output = U>,
{
pub fn peek(&mut self) -> Option<&U> {
if self.state.peeked.is_none() {
self.state.peeked = Some(self.state.inner.source());
}
match self.state.peeked {
Some(Some(ref value)) => Some(value),
Some(None) => None,
_ => unreachable!(),
}
}
}
impl<T, U> From<T> for Peek<T, U> {
fn from(inner: T) -> Self {
let peeked = None;
let state = State { inner, peeked };
Self { state }
}
}
impl<T, U> Default for Peek<T, U>
where
T: Default,
{
fn default() -> Self {
Self::from(T::default())
}
}
impl<T, U> Source for Peek<T, U>
where
T: Source<Output = U>,
U: Clone,
{
type Output = U;
fn source(&mut self) -> Option<Self::Output> {
match self.state.peeked.take() {
Some(output) => output,
None => self.state.inner.source(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Default)]
struct Dummy {
value: f32,
}
impl Source for Dummy {
type Output = f32;
fn source(&mut self) -> Option<Self::Output> {
let value = self.value;
self.value += 1.0;
Some(value)
}
}
#[test]
fn test() {
let mut peek = Peek::from(Dummy::default());
assert_nearly_eq!(peek.peek(), Some(0.0));
assert_nearly_eq!(peek.peek(), Some(0.0));
assert_nearly_eq!(peek.source(), Some(0.0));
assert_nearly_eq!(peek.source(), Some(1.0));
assert_nearly_eq!(peek.source(), Some(2.0));
}
}