Skip to main content

async_deferred/
embassy.rs

1/// Declares a [`LocalSpawner`](crate::LocalSpawner) for the embassy executor.
2///
3/// The spawner can run up to `pool_size` [`Deferred`](crate::Deferred) tasks at once.
4/// Starting a task while `pool_size` tasks are running returns a
5/// [`SpawnError`](crate::SpawnError).
6///
7/// To stop a task and start a new one right away in a full pool, use
8/// [`cancel_and_wait`](crate::Deferred::cancel_and_wait) rather than
9/// [`cancel`](crate::Deferred::cancel).
10///
11/// Needs `embassy-executor` 0.10 and a heap allocator, such as `esp-alloc` or
12/// `embedded-alloc`.
13///
14/// # Examples
15///
16/// ```rust,ignore
17/// use async_deferred::{embassy_spawner, Deferred};
18///
19/// embassy_spawner!(DeferredSpawner, pool_size = 4);
20///
21/// #[embassy_executor::main]
22/// async fn main(spawner: embassy_executor::Spawner) {
23///     let spawner = DeferredSpawner(spawner);
24///     let mut reading = Deferred::start_local_on(&spawner, read_sensor()).unwrap();
25///     // ... do other work ...
26///     let value = reading.join().await;
27/// }
28/// ```
29#[cfg(feature = "alloc")]
30#[macro_export]
31macro_rules! embassy_spawner {
32    ($vis:vis $name:ident, pool_size = $pool_size:expr) => {
33        /// Runs `Deferred` tasks on the embassy executor.
34        #[derive(Clone, Copy)]
35        $vis struct $name(pub ::embassy_executor::Spawner);
36
37        impl $crate::LocalSpawner for $name {
38            fn spawn_local<F>(&self, task: F) -> ::core::result::Result<(), $crate::SpawnError>
39            where
40                F: ::core::future::Future<Output = ()> + 'static,
41            {
42                #[::embassy_executor::task(pool_size = $pool_size)]
43                async fn run(
44                    task: ::core::pin::Pin<
45                        $crate::__private::Box<dyn ::core::future::Future<Output = ()>>,
46                    >,
47                ) {
48                    task.await
49                }
50
51                let token = run($crate::__private::Box::pin(task)).map_err(|_| {
52                    $crate::SpawnError::new(concat!(
53                        stringify!($name),
54                        ": all `pool_size` tasks are running"
55                    ))
56                })?;
57                self.0.spawn(token);
58                ::core::result::Result::Ok(())
59            }
60        }
61    };
62}
63
64/// Without the `alloc` feature, `embassy_spawner!` only reports what is missing.
65#[cfg(not(feature = "alloc"))]
66#[doc(hidden)]
67#[macro_export]
68macro_rules! embassy_spawner {
69    ($($input:tt)*) => {
70        ::core::compile_error!(
71            "`embassy_spawner!` needs the `alloc` feature of async-deferred, because `Deferred` \
72             keeps its tasks on the heap. Without a heap, use `StaticDeferred` \
73             (the `static-deferred` feature)."
74        );
75    };
76}