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
use core::{future::Future, pin::Pin, time::Duration};

pub use tokio::time::Sleep;

use crate::Sleepble;

//
impl Sleepble for Sleep {
    fn sleep(dur: Duration) -> Self {
        tokio::time::sleep(tokio::time::Duration::from_micros(dur.as_micros() as u64))
    }

    fn wait(self) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>> {
        Box::pin(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::time::Instant;

    use crate::{sleep, sleep_until};

    #[tokio::test]
    async fn test_sleep() {
        let now = std::time::Instant::now();

        sleep::<Sleep>(Duration::from_millis(100)).await;

        let elapsed_dur = now.elapsed();
        assert!(elapsed_dur.as_millis() >= 100 && elapsed_dur.as_millis() <= 105);
    }

    #[tokio::test]
    async fn test_sleep_until() {
        let now = std::time::Instant::now();

        sleep_until::<Sleep>(Instant::now() + Duration::from_millis(100)).await;

        let elapsed_dur = now.elapsed();
        assert!(elapsed_dur.as_millis() >= 100 && elapsed_dur.as_millis() <= 105);
    }
}