use {bevy_ecs::prelude::*, core::future::Future};
#[derive(Debug, Clone, Resource)]
pub struct WebSocketRuntime {
#[cfg(target_family = "wasm")]
_priv: (),
#[cfg(not(target_family = "wasm"))]
handle: tokio::runtime::Handle,
}
#[cfg(target_family = "wasm")]
mod maybe {
pub trait Send {}
impl<T> Send for T {}
}
#[cfg(not(target_family = "wasm"))]
mod maybe {
pub trait Send: core::marker::Send {}
impl<T: core::marker::Send> Send for T {}
}
#[cfg_attr(
target_family = "wasm",
allow(
clippy::derivable_impls,
reason = "constructor has conditional cfg logic"
)
)]
impl Default for WebSocketRuntime {
fn default() -> Self {
#[cfg(target_family = "wasm")]
{
Self { _priv: () }
}
#[cfg(not(target_family = "wasm"))]
{
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("failed to create tokio runtime");
let runtime = Box::leak(Box::new(runtime));
Self {
handle: runtime.handle().clone(),
}
}
}
}
#[cfg(not(target_family = "wasm"))]
impl From<tokio::runtime::Handle> for WebSocketRuntime {
fn from(value: tokio::runtime::Handle) -> Self {
Self { handle: value }
}
}
impl WebSocketRuntime {
pub fn spawn_on_self<F>(&self, future: F)
where
F: Future<Output = ()> + maybe::Send + 'static,
{
#[cfg(target_family = "wasm")]
{
wasm_bindgen_futures::spawn_local(future);
}
#[cfg(not(target_family = "wasm"))]
{
self.handle.spawn(future);
}
}
}