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
}
}
}