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
//!Interval module

use core::future::Future;
use core::{task, time};
use core::pin::Pin;

use crate::oneshot::Oneshot;
use crate::oneshot::Timer as PlatformTimer;

///Periodic Timer
#[must_use = "Interval does nothing unless polled"]
pub struct Interval<T=PlatformTimer> {
    inner: Option<(T, time::Duration)>,
}

impl Interval {
    #[inline(always)]
    ///Creates new instance using platform timer
    pub fn platform_new(interval: time::Duration) -> Self {
        Interval::<PlatformTimer>::new(interval)
    }
}

impl<T: Oneshot> Interval<T> {
    ///Creates new instance with specified timer type.
    pub fn new(interval: time::Duration) -> Self {
        Self {
            inner: Some((T::new(interval), interval)),
        }
    }

    fn inner(&mut self) -> &mut (T, time::Duration) {
        match self.inner {
            Some(ref mut inner) => inner,
            None => unreach!()
        }
    }
}

impl<T: Oneshot> Future for Interval<T> {
    type Output = Self;

    fn poll(self: Pin<&mut Self>, ctx: &mut task::Context) -> task::Poll<Self::Output> {
        let this = self.get_mut();

        match Future::poll(Pin::new(&mut this.inner().0), ctx) {
            task::Poll::Ready(()) => {
                let (mut timer, interval) = match this.inner.take() {
                    Some(res) => res,
                    None => unreach!(),
                };
                timer.restart(&interval, ctx.waker());
                task::Poll::Ready(Self {
                    inner: Some((timer, interval)),
                })
            },
            task::Poll::Pending => task::Poll::Pending,
        }
    }
}