use std::future::Future;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone)]
pub struct Runtime(Arc<tokio::runtime::Runtime>);
#[cfg(not(target_arch = "wasm32"))]
impl Default for Runtime {
fn default() -> Self {
let mut builder = tokio::runtime::Builder::new_multi_thread();
builder.enable_all();
Self(Arc::new(builder.build().unwrap_or_else(|error| {
panic!("failed to create Tokio runtime: {error}")
})))
}
}
#[cfg(not(target_arch = "wasm32"))]
impl Runtime {
pub fn from_tokio(runtime: Arc<tokio::runtime::Runtime>) -> Self {
Self(runtime)
}
pub fn tokio(&self) -> &tokio::runtime::Runtime {
&self.0
}
pub fn tokio_arc(&self) -> Arc<tokio::runtime::Runtime> {
self.0.clone()
}
pub fn block_on<F: Future>(&self, future: F) -> F::Output {
self.0.block_on(future)
}
pub fn spawn<F>(&self, future: F) -> crate::JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
self.0.spawn(future)
}
}
#[cfg(target_arch = "wasm32")]
#[derive(Clone, Copy, Debug, Default)]
pub struct Runtime;
#[cfg(target_arch = "wasm32")]
impl Runtime {
pub fn spawn<F>(&self, future: F) -> crate::JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
crate::spawn(future)
}
}