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
use crate::clock;
use crate::Delay;
use futures_core::ready;
use futures_util::future::poll_fn;
use std::future::Future;
use std::pin::Pin;
use std::task::{self, Poll};
use std::time::{Duration, Instant};
#[derive(Debug)]
pub struct Interval {
delay: Delay,
duration: Duration,
}
impl Interval {
pub fn new(at: Instant, duration: Duration) -> Interval {
assert!(
duration > Duration::new(0, 0),
"`duration` must be non-zero."
);
Interval::new_with_delay(Delay::new(at), duration)
}
pub fn new_interval(duration: Duration) -> Interval {
Interval::new(clock::now() + duration, duration)
}
pub(crate) fn new_with_delay(delay: Delay, duration: Duration) -> Interval {
Interval { delay, duration }
}
#[doc(hidden)]
pub fn poll_next(&mut self, cx: &mut task::Context<'_>) -> Poll<Option<Instant>> {
ready!(Pin::new(&mut self.delay).poll(cx));
let now = self.delay.deadline();
let next = now + self.duration;
self.delay.reset(next);
Poll::Ready(Some(now))
}
#[allow(clippy::should_implement_trait)]
pub async fn next(&mut self) -> Option<Instant> {
poll_fn(|cx| self.poll_next(cx)).await
}
}
#[cfg(feature = "async-traits")]
impl futures_core::FusedStream for Interval {
fn is_terminated(&self) -> bool {
false
}
}
#[cfg(feature = "async-traits")]
impl futures_core::Stream for Interval {
type Item = Instant;
fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
Interval::poll_next(self.get_mut(), cx)
}
}