Skip to main content

cross_runtime/
runtime.rs

1use std::future::Future;
2
3#[cfg(not(target_arch = "wasm32"))]
4use std::sync::Arc;
5
6/// An owned task runtime on native targets and the ambient browser runtime on WebAssembly.
7#[cfg(not(target_arch = "wasm32"))]
8#[derive(Clone)]
9pub struct Runtime(Arc<tokio::runtime::Runtime>);
10
11#[cfg(not(target_arch = "wasm32"))]
12impl Default for Runtime {
13    fn default() -> Self {
14        let mut builder = tokio::runtime::Builder::new_multi_thread();
15        builder.enable_all();
16        Self(Arc::new(builder.build().unwrap_or_else(|error| {
17            panic!("failed to create Tokio runtime: {error}")
18        })))
19    }
20}
21
22#[cfg(not(target_arch = "wasm32"))]
23impl Runtime {
24    /// Use an existing Tokio runtime as this runtime's native executor.
25    pub fn from_tokio(runtime: Arc<tokio::runtime::Runtime>) -> Self {
26        Self(runtime)
27    }
28
29    /// Access the native Tokio runtime.
30    pub fn tokio(&self) -> &tokio::runtime::Runtime {
31        &self.0
32    }
33
34    /// Clone the shared native Tokio runtime.
35    pub fn tokio_arc(&self) -> Arc<tokio::runtime::Runtime> {
36        self.0.clone()
37    }
38
39    /// Run a future to completion on the native runtime.
40    pub fn block_on<F: Future>(&self, future: F) -> F::Output {
41        self.0.block_on(future)
42    }
43
44    /// Spawn a `Send` task on the native runtime.
45    pub fn spawn<F>(&self, future: F) -> crate::JoinHandle<F::Output>
46    where
47        F: Future + Send + 'static,
48        F::Output: Send + 'static,
49    {
50        self.0.spawn(future)
51    }
52}
53
54/// The ambient browser task runtime.
55#[cfg(target_arch = "wasm32")]
56#[derive(Clone, Copy, Debug, Default)]
57pub struct Runtime;
58
59#[cfg(target_arch = "wasm32")]
60impl Runtime {
61    /// Spawn a `Send` task which may follow its waker across browser workers.
62    pub fn spawn<F>(&self, future: F) -> crate::JoinHandle<F::Output>
63    where
64        F: Future + Send + 'static,
65        F::Output: Send + 'static,
66    {
67        crate::spawn(future)
68    }
69}