use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use async_io::Timer;
use futures_core::stream::Stream;
use crate::time::{Duration, Instant};
pub fn interval(dur: Duration) -> Interval {
Interval {
timer: Timer::after(dur.into()),
interval: dur,
}
}
#[must_use = "streams do nothing unless polled or .awaited"]
#[derive(Debug)]
pub struct Interval {
timer: Timer,
interval: Duration,
}
impl Stream for Interval {
type Item = Instant;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let instant = match Pin::new(&mut self.timer).poll(cx) {
Poll::Ready(instant) => instant,
Poll::Pending => return Poll::Pending,
};
let interval = self.interval;
drop(std::mem::replace(
&mut self.timer,
Timer::after(interval.into()),
));
Poll::Ready(Some(instant.into()))
}
}