async_shared_timeout/runtime/
tokio.rs

1use core::{
2    future::Future,
3    pin::Pin,
4    task::{Context, Poll},
5    time::Duration,
6};
7use tokio::time::{self, Instant, Sleep};
8
9/// Tokio runtime implementation
10#[derive(Copy, Clone, Default)]
11#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
12pub struct Runtime {
13    _private: (),
14}
15
16impl Runtime {
17    /// Create a new Tokio runtime object. Current runtime will be used for sleeping. Launch
18    /// [`Timeout::wait`](`crate::Timeout::wait`) in the correct context if necessary.
19    #[must_use]
20    pub fn new() -> Self {
21        Self::default()
22    }
23}
24
25impl super::Runtime for Runtime {
26    type Sleep = Sleep;
27    type Instant = Instant;
28    fn create_sleep(&self, timeout: Duration) -> Self::Sleep {
29        time::sleep(timeout)
30    }
31    fn now(&self) -> Self::Instant {
32        Instant::now()
33    }
34}
35
36impl super::Instant for Instant {
37    fn duration_since(&self, earlier: &Self) -> Duration {
38        self.duration_since(*earlier)
39    }
40}
41
42impl super::Sleep for Sleep {
43    fn poll_sleep(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
44        self.poll(cx)
45    }
46    fn reset(self: Pin<&mut Self>, timeout: Duration) {
47        self.reset(time::Instant::now() + timeout);
48    }
49}