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
use super::{now, WAITS, WAITS_NUM};
use async_ach_waker::{WakerEntity, WakerPool, WakerToken};
use core::pin::Pin;
use core::task::{Context, Poll};
use core::time::Duration;
use futures_util::Stream;

pub fn interval(period: Duration) -> Interval<'static, WAITS_NUM> {
    Interval {
        pool: &WAITS,
        last: now(),
        period,
        token: None,
    }
}

pub struct Interval<'a, const N: usize> {
    pool: &'a WakerPool<u64, N>,
    last: u64,
    period: Duration,
    token: Option<WakerToken<'a, u64, N>>,
}
impl<'a, const N: usize> Stream for Interval<'a, N> {
    type Item = ();
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let next_time = self.last + self.period.as_nanos() as u64;
        if next_time < now() {
            self.last = next_time;
            return Poll::Ready(Some(()));
        }
        let waker = cx.waker();
        if let Some(token) = &self.token {
            token.swap(WakerEntity::new(waker.clone(), next_time));
        } else if let Ok(token) = self.pool.register() {
            token.swap(WakerEntity::new(waker.clone(), next_time));
            self.token = Some(token);
        } else {
            waker.wake_by_ref();
        }
        if next_time < now() {
            self.last = next_time;
            Poll::Ready(Some(()))
        } else {
            Poll::Pending
        }
    }
}