Skip to main content

gpu_async_reactor/host/
tokio.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! tokio: a [`Clock`] + [`Timer`] over `tokio::time`, so [`wait`](crate::wait) runs as a tokio
4//! task (its predicted sleep is a tokio timer; tokio's timer wheel has 1 ms resolution, so this
5//! host suits consumers that are not latency-critical). Pair it with
6//! [`Watcher`](crate::host::std_host::Watcher) to await completion lines from tokio tasks.
7
8use tokio::time::Instant;
9
10use crate::core::time::{Clock, MonoNs, Timer};
11
12/// tokio's clock from an origin (paused time in tests moves it too).
13#[derive(Clone, Copy, Debug)]
14pub struct TokioClock {
15    origin: Instant,
16}
17
18impl TokioClock {
19    /// A clock whose 0 is now.
20    #[must_use]
21    pub fn new() -> Self {
22        Self {
23            origin: Instant::now(),
24        }
25    }
26}
27
28impl Default for TokioClock {
29    fn default() -> Self {
30        Self::new()
31    }
32}
33
34impl Clock for TokioClock {
35    fn monotonic_ns(&self) -> MonoNs {
36        MonoNs(u64::try_from(self.origin.elapsed().as_nanos()).unwrap_or(u64::MAX))
37    }
38}
39
40impl Timer for TokioClock {
41    async fn sleep_until(&self, at: MonoNs) {
42        tokio::time::sleep_until(self.origin + core::time::Duration::from_nanos(at.0)).await;
43    }
44}