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
use crate::{Sleep, SleepTrait, ZERO_DURATION};
use futures::{
future::Future,
ready,
stream::{FusedStream, Stream},
};
use pin_project::pin_project;
use std::{
pin::Pin,
task::{Context, Poll},
time::Duration,
};
#[pin_project]
#[must_use = "streams do nothing unless you `.await` or poll them"]
#[derive(Debug)]
pub struct Interval {
#[pin]
delay: Sleep,
period: Duration,
}
impl Interval {
pub fn new(delay: Sleep, period: Duration) -> Self {
assert!(period > ZERO_DURATION, "`period` must be non-zero.");
Self { delay, period }
}
}
impl Stream for Interval {
type Item = ();
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
ready!(this.delay.as_mut().poll(cx));
this.delay.reset(*this.period);
Poll::Ready(Some(()))
}
}
impl FusedStream for Interval {
fn is_terminated(&self) -> bool {
false
}
}