async_deferred/embassy.rs
1/// Declares a [`LocalSpawner`](crate::LocalSpawner) for the embassy executor.
2///
3/// Embassy only runs tasks declared with `#[embassy_executor::task]`, so this macro declares
4/// one with room for `pool_size` tasks at once, and a spawner type that runs every
5/// [`Deferred`](crate::Deferred) task through it. Starting more tasks than `pool_size` at
6/// the same time panics.
7///
8/// Needs `embassy-executor` 0.10 and a heap allocator, such as `esp-alloc` or
9/// `embedded-alloc`.
10///
11/// # Examples
12///
13/// ```rust,ignore
14/// use async_deferred::{embassy_spawner, Deferred};
15///
16/// embassy_spawner!(DeferredSpawner, pool_size = 4);
17///
18/// #[embassy_executor::main]
19/// async fn main(spawner: embassy_executor::Spawner) {
20/// let spawner = DeferredSpawner(spawner);
21/// let mut reading = Deferred::start_local_on(&spawner, read_sensor());
22/// // ... do other work ...
23/// let value = reading.join().await;
24/// }
25/// ```
26#[macro_export]
27macro_rules! embassy_spawner {
28 ($vis:vis $name:ident, pool_size = $pool_size:expr) => {
29 /// Runs `Deferred` tasks on the embassy executor.
30 #[derive(Clone, Copy)]
31 $vis struct $name(pub ::embassy_executor::Spawner);
32
33 impl $crate::LocalSpawner for $name {
34 fn spawn_local<F>(&self, task: F)
35 where
36 F: ::core::future::Future<Output = ()> + 'static,
37 {
38 #[::embassy_executor::task(pool_size = $pool_size)]
39 async fn run(
40 task: ::core::pin::Pin<
41 $crate::__private::Box<dyn ::core::future::Future<Output = ()>>,
42 >,
43 ) {
44 task.await
45 }
46
47 self.0.spawn(run($crate::__private::Box::pin(task)).expect(concat!(
48 stringify!($name),
49 ": too many tasks running at once, increase `pool_size`"
50 )));
51 }
52 }
53 };
54}