async_interval/
impl_async_io.rs

1use alloc::boxed::Box;
2use core::{future::Future, pin::Pin, time::Duration};
3
4pub use async_io::{Timer, Timer as AsyncIoTimer};
5use futures_util::StreamExt as _;
6
7use crate::Intervalable;
8
9//
10impl Intervalable for Timer {
11    fn interval(dur: Duration) -> Self {
12        Self::interval(dur)
13    }
14
15    fn wait<'a>(&'a mut self) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
16        use futures_util::FutureExt as _;
17
18        Box::pin(self.next().map(|_| ()))
19    }
20
21    #[cfg(feature = "std")]
22    fn wait_for_std<'a>(
23        &'a mut self,
24    ) -> Pin<Box<dyn Future<Output = Option<std::time::Instant>> + Send + 'a>> {
25        Box::pin(self.next())
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    #[allow(unused_imports)]
32    use super::*;
33
34    #[cfg(feature = "std")]
35    #[tokio::test]
36    async fn test_impl() {
37        #[cfg(feature = "std")]
38        let now = std::time::Instant::now();
39
40        let mut interval = <Timer as Intervalable>::interval(Duration::from_millis(100));
41
42        //
43        interval.wait().await;
44
45        #[cfg(feature = "std")]
46        {
47            let elapsed_dur = now.elapsed();
48            assert!(elapsed_dur.as_millis() >= 100 && elapsed_dur.as_millis() <= 105);
49        }
50
51        //
52        interval.wait().await;
53
54        #[cfg(feature = "std")]
55        {
56            let elapsed_dur = now.elapsed();
57            assert!(elapsed_dur.as_millis() >= 200 && elapsed_dur.as_millis() <= 210);
58        }
59
60        #[cfg(feature = "std")]
61        {
62            assert!(interval.wait_for_std().await.is_some());
63
64            let elapsed_dur = now.elapsed();
65            assert!(elapsed_dur.as_millis() >= 300 && elapsed_dur.as_millis() <= 315);
66        }
67    }
68
69    #[cfg(all(feature = "std", feature = "stream"))]
70    #[tokio::test]
71    async fn test_intervalable_iter_stream() {
72        use alloc::{vec, vec::Vec};
73
74        //
75        let st = crate::intervalable_iter_stream(
76            0..=2,
77            <Timer as Intervalable>::interval(Duration::from_millis(100)),
78        );
79
80        #[cfg(feature = "std")]
81        let now = std::time::Instant::now();
82
83        assert_eq!(st.collect::<Vec<_>>().await, vec![0, 1, 2]);
84
85        #[cfg(feature = "std")]
86        {
87            let elapsed_dur = now.elapsed();
88            assert!(elapsed_dur.as_millis() >= 300 && elapsed_dur.as_millis() <= 310);
89        }
90    }
91}