hdmi_hal/cancel.rs
1//! A flag that asks a procedure to stop: [`Cancel`].
2//!
3//! A procedure that drives the PHY and SCDC over many calls (link training, a TMDS bring-up)
4//! reads the flag between its calls and, once it is set, runs its own recovery and ends with
5//! a typed result saying so. Stopping a procedure by dropping its future instead leaves the
6//! PHY and the sink in a state nothing records: a call may have been half done. So an
7//! interrupt handler or another task sets the flag, and the procedure stops at its next
8//! check.
9//!
10//! [`AtomicBool`] implements it, so a plain load and store on any target the stack builds
11//! for; references to a flag implement it too, so a driver can hold `&flag` whatever owns
12//! the flag (a `static`, an `Arc`). [`NoCancel`] never cancels.
13
14use core::sync::atomic::{AtomicBool, Ordering};
15
16/// A flag the caller sets to ask a procedure to stop.
17///
18/// A procedure reads it between its calls, never in the middle of one, and never clears
19/// it: the caller resets it before the next procedure, or that one stops at its first
20/// check.
21pub trait Cancel {
22 /// Whether the caller has asked the procedure to stop.
23 fn is_cancelled(&self) -> bool;
24}
25
26/// Never cancels.
27#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
28pub struct NoCancel;
29
30impl Cancel for NoCancel {
31 fn is_cancelled(&self) -> bool {
32 false
33 }
34}
35
36/// A flag another task or an interrupt handler sets.
37impl Cancel for AtomicBool {
38 fn is_cancelled(&self) -> bool {
39 self.load(Ordering::Relaxed)
40 }
41}
42
43/// The flag behind a reference, so a driver can hold `&flag` and the caller keep the flag.
44impl<T: Cancel + ?Sized> Cancel for &T {
45 fn is_cancelled(&self) -> bool {
46 (**self).is_cancelled()
47 }
48}
49
50#[cfg(test)]
51mod tests {
52 use super::*;
53
54 fn stopped(cancel: impl Cancel) -> bool {
55 cancel.is_cancelled()
56 }
57
58 #[test]
59 fn a_flag_cancels_once_set_and_no_cancel_never_does() {
60 let flag = AtomicBool::new(false);
61 assert!(!stopped(&flag));
62 flag.store(true, Ordering::Relaxed);
63 assert!(stopped(&flag));
64 let dynamic: &dyn Cancel = &flag;
65 assert!(stopped(dynamic));
66 assert!(!stopped(NoCancel));
67 }
68}