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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use futures::prelude::*;

use std::fmt;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};

/// A future representing the notification that an elapsed duration has occurred.
#[must_use = "futures do nothing unless awaited"]
pub struct Delay {
    inner: Pin<Box<dyn runtime_raw::Delay>>,
}

impl Delay {
    /// Continue execution after the duration has passed.
    ///
    /// ## Examples
    /// ```
    /// # #![feature(async_await)]
    /// use runtime::time::Delay;
    /// use std::time::{Duration, Instant};
    ///
    /// # #[runtime::main]
    /// # async fn main () -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
    /// let start = Instant::now();
    /// let now = Delay::new(Duration::from_millis(40)).await;
    ///
    /// assert!(now - start >= Duration::from_millis(40));
    /// # Ok(())}
    /// ```
    #[inline]
    pub fn new(dur: Duration) -> Self {
        let inner = runtime_raw::current_runtime().new_delay(dur);
        Self { inner }
    }

    /// Continue execution after the given instant.
    ///
    /// ## Examples
    /// ```
    /// # #![feature(async_await)]
    /// use runtime::time::Delay;
    /// use std::time::{Duration, Instant};
    ///
    /// # #[runtime::main]
    /// # async fn main () -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
    /// let start = Instant::now();
    /// let now = Delay::new_at(start + Duration::from_millis(40)).await;
    ///
    /// assert!(now - start >= Duration::from_millis(40));
    /// # Ok(())}
    /// ```
    #[inline]
    pub fn new_at(at: Instant) -> Self {
        let inner = runtime_raw::current_runtime().new_delay_at(at);
        Self { inner }
    }
}

impl fmt::Debug for Delay {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        fmt::Debug::fmt(&self.inner, f)
    }
}

impl Future for Delay {
    type Output = Instant;

    #[inline]
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.inner.poll_unpin(cx)
    }
}