Skip to main content

cross_runtime/
lib.rs

1#![allow(async_fn_in_trait)]
2
3mod runtime;
4mod task;
5
6pub use runtime::Runtime;
7pub use task::{JoinError, JoinHandle, spawn, spawn_local};
8
9/// Timeout expiry error, using the clock native to each runtime.
10#[cfg(not(target_arch = "wasm32"))]
11pub use tokio::time::error::Elapsed;
12#[cfg(target_arch = "wasm32")]
13pub use wasmtimer::tokio::error::Elapsed;
14
15/// Sleep without coupling callers to the active platform runtime.
16pub async fn sleep(duration: std::time::Duration) {
17    #[cfg(not(target_arch = "wasm32"))]
18    tokio::time::sleep(duration).await;
19
20    #[cfg(target_arch = "wasm32")]
21    wasmtimer::tokio::sleep(duration).await;
22}
23
24/// Bound `future` by `duration` using the active platform runtime.
25pub async fn timeout<F: std::future::Future>(
26    duration: std::time::Duration,
27    future: F,
28) -> Result<F::Output, Elapsed> {
29    #[cfg(not(target_arch = "wasm32"))]
30    {
31        tokio::time::timeout(duration, future).await
32    }
33
34    #[cfg(target_arch = "wasm32")]
35    {
36        wasmtimer::tokio::timeout(duration, future).await
37    }
38}