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
use core::future::Future;
use core::{task, time, mem};
use core::pin::Pin;
use crate::oneshot::Oneshot;
use crate::oneshot::Timer as PlatformTimer;
#[must_use = "Interval does nothing unless polled"]
pub enum Interval<T=PlatformTimer> {
#[doc(hidden)]
Ongoing(T, time::Duration),
#[doc(hidden)]
Stopped,
}
impl Interval {
#[inline(always)]
pub fn platform_new(interval: time::Duration) -> Self {
Interval::<PlatformTimer>::new(interval)
}
}
impl<T: Oneshot> Interval<T> {
pub fn new(interval: time::Duration) -> Self {
Interval::Ongoing(T::new(interval), interval)
}
}
impl<T: Oneshot> Future for Interval<T> {
type Output = Self;
fn poll(mut self: Pin<&mut Self>, ctx: &mut task::Context) -> task::Poll<Self::Output> {
let mut state = Interval::Stopped;
mem::swap(self.as_mut().get_mut(), &mut state);
match state {
Interval::Ongoing(mut timer, interval) => match Future::poll(Pin::new(&mut timer), ctx) {
task::Poll::Ready(()) => {
timer.restart(&interval, ctx.waker());
task::Poll::Ready(Interval::Ongoing(timer, interval))
},
task::Poll::Pending => {
*self = Interval::Ongoing(timer, interval);
task::Poll::Pending
},
},
Interval::Stopped => task::Poll::Pending
}
}
}