Skip to main content

async_deferred/
spawner.rs

1use core::future::Future;
2
3use crate::SpawnError;
4
5/// Runs a task in the background on an async runtime.
6///
7/// Implement this to use [`Deferred`](crate::Deferred) with any runtime. Implementations
8/// for Tokio and smol are available behind the `tokio` (default) and `smol` features.
9///
10/// The runtime must keep polling `task` until it finishes. If the runtime stops first,
11/// it must drop `task`, so the `Deferred` reports [`State::Cancelled`](crate::State::Cancelled)
12/// instead of staying pending. If the runtime can't take the task, for example because its
13/// task pool is full, return a [`SpawnError`].
14///
15/// # Examples
16///
17/// ```rust
18/// use std::future::Future;
19/// use async_deferred::{Deferred, SpawnError, Spawner};
20///
21/// struct ThreadSpawner;
22///
23/// impl Spawner for ThreadSpawner {
24///     fn spawn<F>(&self, task: F) -> Result<(), SpawnError>
25///     where
26///         F: Future<Output = ()> + Send + 'static,
27///     {
28///         std::thread::spawn(move || futures_executor::block_on(task));
29///         Ok(())
30///     }
31/// }
32///
33/// let mut deferred = Deferred::start_on(&ThreadSpawner, async { 42 }).unwrap();
34/// assert_eq!(futures_executor::block_on(deferred.join()), Ok(&42));
35/// ```
36pub trait Spawner {
37    /// Runs `task` in the background.
38    fn spawn<F>(&self, task: F) -> Result<(), SpawnError>
39    where
40        F: Future<Output = ()> + Send + 'static;
41}
42
43/// Runs a task that is not `Send` in the background, on a single-threaded executor.
44///
45/// Use it with the `*_local_on` methods of [`Deferred`](crate::Deferred). The same
46/// requirements as [`Spawner`] apply.
47///
48/// # Embassy
49///
50/// Use [`embassy_spawner!`](crate::embassy_spawner) to declare a `LocalSpawner` for embassy.
51pub trait LocalSpawner {
52    /// Runs `task` in the background.
53    fn spawn_local<F>(&self, task: F) -> Result<(), SpawnError>
54    where
55        F: Future<Output = ()> + 'static;
56}
57
58/// Implements `Spawner` for pointers to a spawner. Attributes before a pointer, such as a
59/// `cfg`, are put on its impl, so docs.rs shows which feature it needs.
60macro_rules! forward_spawner {
61    ($($(#[$attr:meta])* $pointer:ty),* $(,)?) => {$(
62        $(#[$attr])*
63        impl<S: Spawner + ?Sized> Spawner for $pointer {
64            fn spawn<F>(&self, task: F) -> Result<(), SpawnError>
65            where
66                F: Future<Output = ()> + Send + 'static,
67            {
68                (**self).spawn(task)
69            }
70        }
71    )*};
72}
73
74/// Same as `forward_spawner`, for `LocalSpawner`.
75macro_rules! forward_local_spawner {
76    ($($(#[$attr:meta])* $pointer:ty),* $(,)?) => {$(
77        $(#[$attr])*
78        impl<S: LocalSpawner + ?Sized> LocalSpawner for $pointer {
79            fn spawn_local<F>(&self, task: F) -> Result<(), SpawnError>
80            where
81                F: Future<Output = ()> + 'static,
82            {
83                (**self).spawn_local(task)
84            }
85        }
86    )*};
87}
88
89forward_spawner!(
90    &S,
91    &mut S,
92    #[cfg(feature = "alloc")]
93    alloc::boxed::Box<S>,
94    #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
95    alloc::sync::Arc<S>,
96);
97forward_local_spawner!(
98    &S,
99    &mut S,
100    #[cfg(feature = "alloc")]
101    alloc::boxed::Box<S>,
102    #[cfg(feature = "alloc")]
103    alloc::rc::Rc<S>,
104    #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
105    alloc::sync::Arc<S>,
106);
107
108/// Spawns on the current Tokio runtime.
109///
110/// Spawning outside a Tokio runtime returns a [`SpawnError`]. Use a
111/// [`tokio::runtime::Handle`] to spawn from outside one.
112#[cfg(feature = "tokio")]
113#[derive(Debug, Clone, Copy, Default)]
114pub struct Tokio;
115
116#[cfg(feature = "tokio")]
117impl Spawner for Tokio {
118    fn spawn<F>(&self, task: F) -> Result<(), SpawnError>
119    where
120        F: Future<Output = ()> + Send + 'static,
121    {
122        let handle = tokio::runtime::Handle::try_current()
123            .map_err(|_| SpawnError::new("not inside a Tokio runtime"))?;
124        handle.spawn(task);
125        Ok(())
126    }
127}
128
129/// Spawns on this Tokio runtime. Works from outside the runtime.
130#[cfg(feature = "tokio")]
131impl Spawner for tokio::runtime::Handle {
132    fn spawn<F>(&self, task: F) -> Result<(), SpawnError>
133    where
134        F: Future<Output = ()> + Send + 'static,
135    {
136        tokio::runtime::Handle::spawn(self, task);
137        Ok(())
138    }
139}
140
141/// Spawns on this `LocalSet`. The task only makes progress while the `LocalSet` is run.
142#[cfg(feature = "tokio")]
143impl LocalSpawner for tokio::task::LocalSet {
144    fn spawn_local<F>(&self, task: F) -> Result<(), SpawnError>
145    where
146        F: Future<Output = ()> + 'static,
147    {
148        tokio::task::LocalSet::spawn_local(self, task);
149        Ok(())
150    }
151}
152
153/// Spawns on smol's global executor.
154#[cfg(feature = "smol")]
155#[derive(Debug, Clone, Copy, Default)]
156pub struct Smol;
157
158#[cfg(feature = "smol")]
159impl Spawner for Smol {
160    fn spawn<F>(&self, task: F) -> Result<(), SpawnError>
161    where
162        F: Future<Output = ()> + Send + 'static,
163    {
164        smol::spawn(task).detach();
165        Ok(())
166    }
167}
168
169/// Spawns on this smol executor. The task only makes progress while the executor is run.
170#[cfg(feature = "smol")]
171impl<'a> Spawner for smol::Executor<'a> {
172    fn spawn<F>(&self, task: F) -> Result<(), SpawnError>
173    where
174        F: Future<Output = ()> + Send + 'static,
175    {
176        smol::Executor::spawn(self, task).detach();
177        Ok(())
178    }
179}
180
181/// Spawns on this smol local executor. The task only makes progress while the executor
182/// is run.
183#[cfg(feature = "smol")]
184impl<'a> LocalSpawner for smol::LocalExecutor<'a> {
185    fn spawn_local<F>(&self, task: F) -> Result<(), SpawnError>
186    where
187        F: Future<Output = ()> + 'static,
188    {
189        smol::LocalExecutor::spawn(self, task).detach();
190        Ok(())
191    }
192}