use core::future::Future;
use crate::SpawnError;
pub trait Spawner {
fn spawn<F>(&self, task: F) -> Result<(), SpawnError>
where
F: Future<Output = ()> + Send + 'static;
}
pub trait LocalSpawner {
fn spawn_local<F>(&self, task: F) -> Result<(), SpawnError>
where
F: Future<Output = ()> + 'static;
}
macro_rules! forward_spawner {
($($(#[$attr:meta])* $pointer:ty),* $(,)?) => {$(
$(#[$attr])*
impl<S: Spawner + ?Sized> Spawner for $pointer {
fn spawn<F>(&self, task: F) -> Result<(), SpawnError>
where
F: Future<Output = ()> + Send + 'static,
{
(**self).spawn(task)
}
}
)*};
}
macro_rules! forward_local_spawner {
($($(#[$attr:meta])* $pointer:ty),* $(,)?) => {$(
$(#[$attr])*
impl<S: LocalSpawner + ?Sized> LocalSpawner for $pointer {
fn spawn_local<F>(&self, task: F) -> Result<(), SpawnError>
where
F: Future<Output = ()> + 'static,
{
(**self).spawn_local(task)
}
}
)*};
}
forward_spawner!(
&S,
&mut S,
#[cfg(feature = "alloc")]
alloc::boxed::Box<S>,
#[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
alloc::sync::Arc<S>,
);
forward_local_spawner!(
&S,
&mut S,
#[cfg(feature = "alloc")]
alloc::boxed::Box<S>,
#[cfg(feature = "alloc")]
alloc::rc::Rc<S>,
#[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
alloc::sync::Arc<S>,
);
#[cfg(feature = "tokio")]
#[derive(Debug, Clone, Copy, Default)]
pub struct Tokio;
#[cfg(feature = "tokio")]
impl Spawner for Tokio {
fn spawn<F>(&self, task: F) -> Result<(), SpawnError>
where
F: Future<Output = ()> + Send + 'static,
{
let handle = tokio::runtime::Handle::try_current()
.map_err(|_| SpawnError::new("not inside a Tokio runtime"))?;
handle.spawn(task);
Ok(())
}
}
#[cfg(feature = "tokio")]
impl Spawner for tokio::runtime::Handle {
fn spawn<F>(&self, task: F) -> Result<(), SpawnError>
where
F: Future<Output = ()> + Send + 'static,
{
tokio::runtime::Handle::spawn(self, task);
Ok(())
}
}
#[cfg(feature = "tokio")]
impl LocalSpawner for tokio::task::LocalSet {
fn spawn_local<F>(&self, task: F) -> Result<(), SpawnError>
where
F: Future<Output = ()> + 'static,
{
tokio::task::LocalSet::spawn_local(self, task);
Ok(())
}
}
#[cfg(feature = "smol")]
#[derive(Debug, Clone, Copy, Default)]
pub struct Smol;
#[cfg(feature = "smol")]
impl Spawner for Smol {
fn spawn<F>(&self, task: F) -> Result<(), SpawnError>
where
F: Future<Output = ()> + Send + 'static,
{
smol::spawn(task).detach();
Ok(())
}
}
#[cfg(feature = "smol")]
impl<'a> Spawner for smol::Executor<'a> {
fn spawn<F>(&self, task: F) -> Result<(), SpawnError>
where
F: Future<Output = ()> + Send + 'static,
{
smol::Executor::spawn(self, task).detach();
Ok(())
}
}
#[cfg(feature = "smol")]
impl<'a> LocalSpawner for smol::LocalExecutor<'a> {
fn spawn_local<F>(&self, task: F) -> Result<(), SpawnError>
where
F: Future<Output = ()> + 'static,
{
smol::LocalExecutor::spawn(self, task).detach();
Ok(())
}
}