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
use pin_project_lite::pin_project;
use futures_core::stream::Stream;
use std::pin::Pin;
use std::task::{Context, Poll};
pin_project! {
#[derive(Debug)]
#[must_use = "streams do nothing unless polled or .awaited"]
pub struct Sample<S: Stream, I> {
#[pin]
stream: S,
#[pin]
interval: I,
state: State,
slot: Option<S::Item>,
}
}
impl<S: Stream, I> Sample<S, I> {
pub(crate) fn new(stream: S, interval: I) -> Self {
Self {
state: State::Streaming,
stream,
interval,
slot: None,
}
}
}
#[derive(Debug)]
enum State {
Streaming,
StreamDone,
AllDone,
}
impl<S: Stream, I: Stream> Stream for Sample<S, I> {
type Item = S::Item;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
match this.state {
State::Streaming => {
loop {
match this.stream.as_mut().poll_next(cx) {
Poll::Ready(Some(value)) => {
let _ = this.slot.insert(value);
}
Poll::Ready(None) => {
*this.state = State::StreamDone;
break;
}
Poll::Pending => break,
}
}
match this.interval.as_mut().poll_next(cx) {
Poll::Ready(_) => {
if let State::StreamDone = this.state {
cx.waker().wake_by_ref();
}
match this.slot.take() {
Some(item) => Poll::Ready(Some(item)),
None => Poll::Pending,
}
}
Poll::Pending => Poll::Pending,
}
}
State::StreamDone => {
*this.state = State::AllDone;
Poll::Ready(None)
}
State::AllDone => panic!("stream polled after completion"),
}
}
}
#[cfg(test)]
mod test {
use crate::prelude::*;
use crate::time::Duration;
use futures_lite::prelude::*;
#[test]
fn smoke() {
async_io::block_on(async {
let interval = Duration::from_millis(100);
let throttle = Duration::from_millis(200);
let take = 4;
let expected = 2;
let mut counter = 0;
crate::stream::interval(interval)
.take(take)
.sample(throttle)
.for_each(|_| counter += 1)
.await;
assert_eq!(counter, expected);
})
}
}