async_deferred/static_deferred.rs
1//! [`StaticDeferred`]: a task's result kept in a `static`, without a heap.
2
3use core::cell::RefCell;
4use core::future::{poll_fn, Future};
5use core::mem::{self, ManuallyDrop};
6use core::pin::pin;
7use core::task::{Poll, Waker};
8
9use critical_section::Mutex;
10
11use crate::{BeginError, Error, State};
12
13/// A task's result, kept in a `static` instead of on the heap.
14///
15/// Use it on targets without a heap allocator, or to keep memory use fixed. Each kind of
16/// job gets its own `static StaticDeferred` and its own task, which runs the job through a
17/// [`Ticket`]. All methods take `&self`, so the `static` can be used from anywhere.
18///
19/// Needs a [`critical-section`](https://docs.rs/critical-section) implementation, which
20/// embassy and the HALs provide. With `std`, add
21/// `critical-section = { version = "1", features = ["std"] }` to your own dependencies.
22///
23/// Panics in the job are not caught. On targets where a panic unwinds instead of halting,
24/// such as `std`, the `StaticDeferred` then reports [`State::Cancelled`].
25///
26/// Wait on it ([`join`](Self::join) or [`cancel_and_wait`](Self::cancel_and_wait)) from one
27/// task at a time; waiting twice from the same task, for example with `join!`, is fine.
28/// Waiting from several tasks at once also works, but uses more CPU while they wait, and a
29/// `join` that ends without a result may then report [`Error::Cancelled`] instead of
30/// [`Error::NotStarted`]. A `join` that returns `Ok` always has the result of its run.
31///
32/// # Examples
33///
34/// ```rust,ignore
35/// use async_deferred::{StaticDeferred, Ticket};
36///
37/// static SENSOR: StaticDeferred<u16> = StaticDeferred::new();
38///
39/// #[embassy_executor::task]
40/// async fn sensor_task(ticket: Ticket<'static, u16>) {
41/// ticket.run(read_sensor()).await;
42/// }
43///
44/// #[embassy_executor::main]
45/// async fn main(spawner: embassy_executor::Spawner) {
46/// spawner.spawn(sensor_task(SENSOR.begin().unwrap()).unwrap());
47///
48/// // ... do other work ...
49///
50/// if let Some(value) = SENSOR.take() {
51/// // use the reading
52/// }
53/// }
54/// ```
55pub struct StaticDeferred<T> {
56 shared: Mutex<RefCell<Shared<T>>>,
57}
58
59struct Shared<T> {
60 phase: Phase<T>,
61 /// Increases with every `begin`, so a task from an earlier run can't affect this one.
62 run: u32,
63 /// Tickets and running tasks that still exist, from this run or earlier ones.
64 live: u32,
65 /// The task of the current run, woken when it is cancelled.
66 task: Option<Waker>,
67 /// Whoever waits in `join` or `cancel_and_wait`.
68 waiter: Option<Waiter>,
69 /// The id given to the next waiter, to tell waiters apart.
70 next_waiter: u32,
71 /// The run a `join` waits for, and whether its result was taken by someone else.
72 /// Only that run's outcome is kept, so later runs can't change what the `join` reports.
73 awaited: Option<Awaited>,
74}
75
76/// A waiting task's waker, with the id of its `join` or `cancel_and_wait`.
77struct Waiter {
78 id: u32,
79 waker: Waker,
80}
81
82#[derive(Clone, Copy, PartialEq, Eq)]
83struct Awaited {
84 run: u32,
85 taken: bool,
86}
87
88enum Phase<T> {
89 NotStarted,
90 Pending,
91 Done(T),
92 Cancelled,
93}
94
95impl<T> Shared<T> {
96 fn is_current(&self, run: u32) -> bool {
97 self.run == run && matches!(self.phase, Phase::Pending)
98 }
99
100 /// Stores the waker of the task running the current run. The waker it replaces belongs
101 /// to that same task, so it is returned to be dropped, not woken: waking it would make
102 /// the task poll itself again and again.
103 fn set_task_waker(&mut self, waker: &Waker) -> Option<Waker> {
104 match &self.task {
105 Some(current) if current.will_wake(waker) => None,
106 _ => self.task.replace(waker.clone()),
107 }
108 }
109
110 /// Stores the waker of the waiter with this `id`, giving it an id on its first call.
111 ///
112 /// - The same waker is already stored: nothing changes, whichever waiter stored it.
113 /// Two waiters in one task, as with `join!`, share their task's waker, and waking it
114 /// would only make that task wake itself.
115 /// - A different waker of the same waiter: the old one is only dropped.
116 /// - A waker of another waiter: it is returned with `true`, to be woken so that waiter
117 /// registers again, and several waiters take turns.
118 fn set_waiter_waker(&mut self, id: &mut Option<u32>, waker: &Waker) -> Option<(Waker, bool)> {
119 let id = *id.get_or_insert_with(|| {
120 self.next_waiter = self.next_waiter.wrapping_add(1);
121 self.next_waiter
122 });
123 match &self.waiter {
124 Some(current) if current.waker.will_wake(waker) => None,
125 _ => self
126 .waiter
127 .replace(Waiter {
128 id,
129 waker: waker.clone(),
130 })
131 .map(|old| (old.waker, old.id != id)),
132 }
133 }
134
135 /// Moves the result out if the run has finished, and records that it was taken, so a
136 /// `join` still waiting for that run reports `NotStarted` rather than `Cancelled`.
137 /// Every way of taking the result goes through here.
138 fn take_result(&mut self) -> Option<T> {
139 match mem::replace(&mut self.phase, Phase::NotStarted) {
140 Phase::Done(value) => {
141 if let Some(awaited) = &mut self.awaited {
142 if awaited.run == self.run {
143 awaited.taken = true;
144 }
145 }
146 Some(value)
147 }
148 other => {
149 self.phase = other;
150 None
151 }
152 }
153 }
154
155 /// Ends the current run without a result and resets to `NotStarted`. The new run number
156 /// tells the task and any waiting `join` that this run ended.
157 fn end_run(&mut self) {
158 self.phase = Phase::NotStarted;
159 self.run = self.run.wrapping_add(1);
160 }
161
162 fn take_waiter(&mut self) -> Option<Waker> {
163 self.waiter.take().map(|waiter| waiter.waker)
164 }
165}
166
167/// Wakes a replaced waker of another waiter; a waiter's own old waker is just dropped.
168fn wake_other(replaced: Option<(Waker, bool)>) {
169 if let Some((waker, true)) = replaced {
170 waker.wake();
171 }
172}
173
174fn wake(waker: Option<Waker>) {
175 if let Some(waker) = waker {
176 waker.wake();
177 }
178}
179
180impl<T> StaticDeferred<T> {
181 /// Creates a `StaticDeferred` with no task, for use in a `static`.
182 pub const fn new() -> Self {
183 Self {
184 shared: Mutex::new(RefCell::new(Shared {
185 phase: Phase::NotStarted,
186 run: 0,
187 live: 0,
188 task: None,
189 waiter: None,
190 next_waiter: 0,
191 awaited: None,
192 })),
193 }
194 }
195
196 fn with<R>(&self, f: impl FnOnce(&mut Shared<T>) -> R) -> R {
197 critical_section::with(|cs| f(&mut self.shared.borrow_ref_mut(cs)))
198 }
199
200 /// Starts a new run and returns its [`Ticket`]. Pass the ticket to the task that runs
201 /// the job, and call [`Ticket::run`] there.
202 ///
203 /// Returns [`BeginError::AlreadyStarted`] if a run is in progress or its result has
204 /// not been taken. If the ticket is dropped without running, for example because the
205 /// task could not be spawned, the `StaticDeferred` goes back to
206 /// [`State::NotStarted`].
207 pub fn begin(&self) -> Result<Ticket<'_, T>, BeginError> {
208 self.with(|shared| {
209 if matches!(shared.phase, Phase::Pending | Phase::Done(_)) {
210 return Err(BeginError::AlreadyStarted);
211 }
212 shared.run = shared.run.wrapping_add(1);
213 shared.phase = Phase::Pending;
214 shared.live += 1;
215 Ok(Ticket {
216 deferred: self,
217 run: shared.run,
218 })
219 })
220 }
221
222 /// Returns the current [`State`] without waiting.
223 ///
224 /// Never reports a panic: panics in the job are not caught.
225 pub fn state(&self) -> State {
226 self.with(|shared| match shared.phase {
227 Phase::NotStarted => State::NotStarted,
228 Phase::Pending => State::Pending,
229 Phase::Done(_) => State::Completed,
230 Phase::Cancelled => State::Cancelled,
231 })
232 }
233
234 /// Returns `true` if no run has been started, or its result was taken.
235 pub fn is_not_started(&self) -> bool {
236 self.state() == State::NotStarted
237 }
238
239 /// Returns `true` if a run is in progress.
240 pub fn is_pending(&self) -> bool {
241 self.state() == State::Pending
242 }
243
244 /// Returns `true` if the result is available.
245 pub fn is_ready(&self) -> bool {
246 self.state() == State::Completed
247 }
248
249 /// Returns `true` if the task was dropped before it finished.
250 pub fn is_cancelled(&self) -> bool {
251 self.state() == State::Cancelled
252 }
253
254 /// Moves the result out if the run has finished, without waiting.
255 ///
256 /// On success, a new run can be started.
257 pub fn take(&self) -> Option<T> {
258 self.with(Shared::take_result)
259 }
260
261 /// Calls `f` with the result if the run has finished, without moving it out.
262 ///
263 /// Keep `f` short: on most embedded targets, interrupts are blocked while it runs. Don't
264 /// use the same `StaticDeferred` inside `f`; that panics.
265 pub fn with_result<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
266 self.with(|shared| match &shared.phase {
267 Phase::Done(value) => Some(f(value)),
268 _ => None,
269 })
270 }
271
272 /// Waits for the run to finish and moves its result out.
273 ///
274 /// Returns [`Error::NotStarted`] if no run is in progress and no result is waiting, or if
275 /// another task took the result first. Returns [`Error::Cancelled`] if the run was
276 /// cancelled or its task was dropped before it finished. A `join` only waits for the run
277 /// that was in progress when it started, never for a later one. A [`Ticket`] dropped
278 /// without running counts as a dropped task.
279 ///
280 /// With several tasks waiting at once, the error kind may be `Cancelled` where
281 /// `NotStarted` would be accurate; see the type's docs.
282 pub async fn join(&self) -> Result<T, Error> {
283 // The run this `join` waits for, once it has seen one in progress.
284 let mut waiting_for = None;
285 let mut waiter_id = None;
286 poll_fn(|cx| {
287 let (poll, to_wake) = self.with(|shared| match shared.phase {
288 // The awaited run ended and a new run number was given out since.
289 _ if waiting_for.map_or(false, |run| run != shared.run) => {
290 let taken = shared.awaited
291 == Some(Awaited {
292 run: waiting_for.unwrap_or_default(),
293 taken: true,
294 });
295 let error = if taken {
296 Error::NotStarted
297 } else {
298 Error::Cancelled
299 };
300 (Poll::Ready(Err(error)), None)
301 }
302 Phase::Pending => {
303 waiting_for = Some(shared.run);
304 if shared.awaited.map(|a| a.run) != Some(shared.run) {
305 shared.awaited = Some(Awaited {
306 run: shared.run,
307 taken: false,
308 });
309 }
310 (
311 Poll::Pending,
312 shared.set_waiter_waker(&mut waiter_id, cx.waker()),
313 )
314 }
315 Phase::NotStarted => (Poll::Ready(Err(Error::NotStarted)), None),
316 Phase::Cancelled => (Poll::Ready(Err(Error::Cancelled)), None),
317 Phase::Done(_) => (
318 Poll::Ready(Ok(shared.take_result().expect("matched above"))),
319 None,
320 ),
321 });
322 wake_other(to_wake);
323 poll
324 })
325 .await
326 }
327
328 /// Stops the run in progress and resets to [`State::NotStarted`], so a new run can begin.
329 ///
330 /// The task may still be using its executor resources, such as an embassy task pool
331 /// slot, when this returns. To start a new run right away in a full task pool, use
332 /// [`cancel_and_wait`](Self::cancel_and_wait) instead.
333 /// Returns `false` and does nothing if no run is in progress.
334 pub fn cancel(&self) -> bool {
335 let (cancelled, task, waiter) = self.with(|shared| {
336 if matches!(shared.phase, Phase::Pending) {
337 shared.end_run();
338 (true, shared.task.take(), shared.take_waiter())
339 } else {
340 (false, None, None)
341 }
342 });
343 wake(task);
344 wake(waiter);
345 cancelled
346 }
347
348 /// Like [`cancel`](Self::cancel), and waits until no task of this `StaticDeferred` is
349 /// still running, including tasks cancelled earlier.
350 ///
351 /// On a single-threaded executor such as embassy, their task pool slots are free when
352 /// this returns. It waits for every ticket from [`begin`](Self::begin) to be run or
353 /// dropped, so don't start a new run from elsewhere while waiting. A ticket that is
354 /// neither run nor dropped, for example passed to [`mem::forget`], makes this wait
355 /// forever.
356 /// Returns `true` if a run was in progress.
357 ///
358 /// ```rust,ignore
359 /// // The sensor hung: stop it, then start again once its task is gone.
360 /// SENSOR.cancel_and_wait().await;
361 /// if let Ok(ticket) = SENSOR.begin() {
362 /// if let Ok(token) = sensor_task(ticket) {
363 /// spawner.spawn(token);
364 /// }
365 /// }
366 /// ```
367 pub async fn cancel_and_wait(&self) -> bool {
368 let cancelled = self.cancel();
369 let mut waiter_id = None;
370 poll_fn(|cx| {
371 let (poll, to_wake) = self.with(|shared| {
372 if shared.live == 0 {
373 (Poll::Ready(()), None)
374 } else {
375 (
376 Poll::Pending,
377 shared.set_waiter_waker(&mut waiter_id, cx.waker()),
378 )
379 }
380 });
381 wake_other(to_wake);
382 poll
383 })
384 .await;
385 cancelled
386 }
387}
388
389impl<T> Default for StaticDeferred<T> {
390 /// Same as [`StaticDeferred::new`].
391 fn default() -> Self {
392 Self::new()
393 }
394}
395
396impl<T> core::fmt::Debug for StaticDeferred<T> {
397 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
398 f.debug_struct("StaticDeferred")
399 .field("state", &self.state())
400 .finish_non_exhaustive()
401 }
402}
403
404/// Permission to run one job for a [`StaticDeferred`], returned by
405/// [`StaticDeferred::begin`].
406///
407/// Pass it to the task that does the work and call [`run`](Self::run) there. Dropping it
408/// without running resets the `StaticDeferred` to [`State::NotStarted`].
409#[must_use = "the job only runs once the ticket's `run` is awaited"]
410pub struct Ticket<'a, T> {
411 deferred: &'a StaticDeferred<T>,
412 run: u32,
413}
414
415impl<T> core::fmt::Debug for Ticket<'_, T> {
416 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
417 f.debug_struct("Ticket").field("run", &self.run).finish()
418 }
419}
420
421impl<'a, T> Ticket<'a, T> {
422 /// Runs `future` and makes its output the result of the [`StaticDeferred`].
423 ///
424 /// Returns early, without a result, if the run is cancelled. If the task is dropped while
425 /// the job is running, the `StaticDeferred` reports [`State::Cancelled`]. If it is dropped
426 /// before the job starts, it counts as a ticket dropped without running: the state goes
427 /// back to [`State::NotStarted`].
428 pub async fn run<F>(self, future: F)
429 where
430 F: Future<Output = T>,
431 {
432 // From here on, `Running` reports what happens to this run.
433 let ticket = ManuallyDrop::new(self);
434 let running = Running {
435 deferred: ticket.deferred,
436 run: ticket.run,
437 };
438
439 let mut future = pin!(future);
440 let output = poll_fn(|cx| {
441 let (current, replaced) = running.deferred.with(|shared| {
442 if shared.is_current(running.run) {
443 (true, shared.set_task_waker(cx.waker()))
444 } else {
445 (false, None)
446 }
447 });
448 // This task's own old waker: dropped outside the critical section, not woken.
449 drop(replaced);
450 if !current {
451 return Poll::Ready(None);
452 }
453 future.as_mut().poll(cx).map(Some)
454 })
455 .await;
456
457 if let Some(value) = output {
458 let (leftover, waiter, task) = running.deferred.with(move |shared| {
459 if shared.is_current(running.run) {
460 shared.phase = Phase::Done(value);
461 (None, shared.take_waiter(), shared.task.take())
462 } else {
463 // Cancelled while finishing: discard the value.
464 (Some(value), None, None)
465 }
466 });
467 // Dropped outside the critical section: their `Drop` may run any code.
468 drop((leftover, task));
469 wake(waiter);
470 }
471 }
472}
473
474impl<T> Drop for Ticket<'_, T> {
475 fn drop(&mut self) {
476 // Never ran: for example the task could not be spawned.
477 let waiter = self.deferred.with(|shared| {
478 shared.live -= 1;
479 if shared.is_current(self.run) {
480 shared.end_run();
481 }
482 shared.take_waiter()
483 });
484 wake(waiter);
485 }
486}
487
488/// Owned by a running job; reports a task dropped before finishing.
489struct Running<'a, T> {
490 deferred: &'a StaticDeferred<T>,
491 run: u32,
492}
493
494impl<T> Drop for Running<'_, T> {
495 fn drop(&mut self) {
496 let (waiter, task) = self.deferred.with(|shared| {
497 shared.live -= 1;
498 let task = if shared.is_current(self.run) {
499 shared.phase = Phase::Cancelled;
500 shared.task.take()
501 } else {
502 None
503 };
504 (shared.take_waiter(), task)
505 });
506 // Dropped outside the critical section: its `Drop` may run any code.
507 drop(task);
508 wake(waiter);
509 }
510}