hdmi_hal_async/time/mod.rs
1//! Time for the procedures that drive the PHY and SCDC: a monotonic clock, an async delay,
2//! and the [`Timestamp`] the clock reads.
3//!
4//! This is the async counterpart to `hdmi_hal::time`. [`Timestamp`] and [`Clock`] are
5//! hdmi-hal's, re-exported: reading a counter does not wait, so the clock is neither `async`
6//! nor fallible in either crate. [`Delay`] is async, and has a `Send` twin, [`SendDelay`].
7//!
8//! `Clock` has no twin, since `now` is not `async`, but code that holds a clock across an
9//! `.await` in a task spawned on a multi-threaded executor bounds it `C: Clock + Sync`: a
10//! future holding `&C` is `Send` only when `C` is `Sync`. A clock with state then keeps it in
11//! an atomic or a lock, not a `Cell`.
12//!
13//! Two traits, not one: the clock is read where nothing waits (stamping an event, checking a
14//! deadline), the delay is `async` while the clock is not, and a platform may take them from
15//! different peripherals, a free-running counter and a timer. A procedure that needs both
16//! bounds on both; a test double may implement both on one type, advancing its clock by each
17//! delay.
18//!
19//! Neither trait has a forwarding implementation for references, as
20//! [`DdcBus`](crate::ddc::DdcBus) has none: `impl<D: Delay> Delay for &mut D` would conflict
21//! with [`SendDelay`]'s blanket implementation (E0119), since another crate may implement
22//! `SendDelay` for a reference to its own type, and hdmi-hal's traits keep the same shape. An
23//! implementation may implement either trait for a reference to its own type.
24//!
25//! That is also how one test double serves as both when a procedure takes the clock (`&C`)
26//! and the delay (`&mut D`) as separate arguments: the double keeps its time in a `Cell` (or
27//! an atomic, for `Send` code) and implements `Clock` for itself and `Delay` (or
28//! `SendDelay`) for `&Double`, so `&double` and `&mut &double` can be passed at once.
29//!
30//! # Over embedded-hal-async
31//!
32//! [`Delay`] is the stack's own trait rather than a bound on embedded-hal-async's `DelayNs`:
33//! generic code bounded by `DelayNs` cannot produce a `Send` future, and that crate has no
34//! `Send` twin. An implementation over a `DelayNs` is a few lines: convert the duration to
35//! microseconds, rounding up, and split values beyond `u32`.
36//!
37//! ```
38//! use core::time::Duration;
39//! use embedded_hal_async::delay::DelayNs;
40//! use hdmi_hal_async::time::Delay;
41//!
42//! struct HalDelay<D>(D);
43//!
44//! impl<D: DelayNs> Delay for HalDelay<D> {
45//! async fn delay(&mut self, duration: Duration) {
46//! let mut us = duration.as_nanos().div_ceil(1_000);
47//! while us > 0 {
48//! let step = us.min(u128::from(u32::MAX));
49//! self.0.delay_us(step as u32).await;
50//! us -= step;
51//! }
52//! }
53//! }
54//! ```
55//!
56//! That covers the plain [`Delay`]. A [`SendDelay`] cannot be written generically over
57//! `DelayNs`: its futures are not known to be `Send`, which is why the twin exists. A
58//! `SendDelay` is implemented over a concrete timer whose future is `Send` (embassy-time's
59//! timer, tokio's `sleep`), and a wrapper that implements `Delay` generically cannot also
60//! implement `SendDelay` for one concrete timer (E0119).
61
62use core::time::Duration;
63
64pub use hdmi_hal::time::{Clock, Timestamp};
65
66/// An async delay.
67///
68/// This is the async counterpart to `hdmi_hal::time::Delay`. The contract is identical; only
69/// the method signature gains `async`.
70///
71/// Infallible: a timer that cannot wait leaves the caller nothing to recover with.
72///
73/// # Cancellation
74///
75/// The future may be dropped before it completes, for example when the caller races the
76/// delay against an event. A dropped delay has done nothing that needs undoing, and the
77/// implementation is ready for the next call.
78pub trait Delay {
79 /// Wait at least `duration`, rounding up to the implementation's own tick; never less,
80 /// so a minimum wait holds whatever the timer.
81 ///
82 /// Measured on the platform's [`Clock`]: `now()` read after `delay(d)` completes is at
83 /// least `d` later than `now()` read before it. A test double whose delay does not
84 /// advance its clock breaks this.
85 async fn delay(&mut self, duration: Duration);
86}
87
88/// [`Delay`] with a `Send` future, for procedures spawned on a multi-threaded executor.
89///
90/// The same method and contract, cancellation included, returning a future that is `Send`.
91/// Every `SendDelay` is a `Delay`, through a blanket implementation; a type implements one of
92/// the two. As with the other twins, bound generic code by `SendDelay` alone, and with both
93/// traits in scope call `SendDelay::delay(…)` to avoid an ambiguous method call.
94pub trait SendDelay: Send {
95 /// See [`Delay::delay`].
96 fn delay(&mut self, duration: Duration) -> impl Future<Output = ()> + Send;
97}
98
99impl<T: SendDelay> Delay for T {
100 fn delay(&mut self, duration: Duration) -> impl Future<Output = ()> {
101 <T as SendDelay>::delay(self, duration)
102 }
103}
104
105#[cfg(test)]
106mod tests {
107 use super::*;
108 use core::cell::Cell;
109
110 /// A clock and delay on one type, the delay advancing the clock, as a test double does.
111 struct SimTime {
112 now: Cell<u64>,
113 }
114
115 impl Clock for SimTime {
116 fn now(&self) -> Timestamp {
117 Timestamp::from_micros(self.now.get())
118 }
119 }
120
121 impl Delay for SimTime {
122 async fn delay(&mut self, duration: Duration) {
123 let us = duration.as_nanos().div_ceil(1_000) as u64;
124 self.now.set(self.now.get() + us);
125 }
126 }
127
128 async fn wait_until<T: Clock + Delay>(
129 time: &mut T,
130 deadline: Timestamp,
131 poll: Duration,
132 ) -> u32 {
133 let mut polls = 0;
134 while time.now() < deadline {
135 time.delay(poll).await;
136 polls += 1;
137 }
138 polls
139 }
140
141 #[pollster::test]
142 async fn clock_and_delay_compose_on_one_type() {
143 let mut time = SimTime { now: Cell::new(0) };
144 let start = time.now();
145 let deadline = start.checked_add(Duration::from_millis(5)).unwrap();
146 assert_eq!(
147 wait_until(&mut time, deadline, Duration::from_millis(1)).await,
148 5
149 );
150 assert_eq!(
151 time.now().checked_duration_since(start),
152 Some(Duration::from_millis(5))
153 );
154 }
155
156 /// Implements only the `Send` twin; it adds up what it was asked to wait.
157 #[derive(Default)]
158 struct SendMockDelay {
159 waited: Duration,
160 }
161
162 impl SendDelay for SendMockDelay {
163 async fn delay(&mut self, duration: Duration) {
164 self.waited += duration;
165 }
166 }
167
168 async fn wait_plain<D: Delay>(delay: &mut D) {
169 delay.delay(Duration::from_millis(1)).await;
170 }
171
172 async fn wait_send<D: SendDelay>(delay: &mut D) {
173 SendDelay::delay(delay, Duration::from_millis(2)).await;
174 }
175
176 /// The compiler proves this `Send` bound for every `D: SendDelay`.
177 fn spawnable<D: SendDelay>(delay: &mut D) -> impl Future<Output = ()> + Send + '_ {
178 wait_send(delay)
179 }
180
181 fn assert_send<T: Send>(value: T) -> T {
182 value
183 }
184
185 #[pollster::test]
186 async fn send_twin_is_usable_as_delay() {
187 let mut delay = SendMockDelay::default();
188 wait_plain(&mut delay).await;
189 assert_eq!(delay.waited, Duration::from_millis(1));
190 }
191
192 #[pollster::test]
193 async fn send_twin_future_is_send_in_generic_code() {
194 let mut delay = SendMockDelay::default();
195 assert_send(spawnable(&mut delay)).await;
196 assert_eq!(delay.waited, Duration::from_millis(2));
197 }
198
199 #[test]
200 fn timestamp_and_clock_are_hdmi_hals() {
201 let t: Timestamp = hdmi_hal::time::Timestamp::from_micros(7);
202 let _: hdmi_hal::time::Timestamp = t;
203 fn takes_sync_clock<C: hdmi_hal::time::Clock>(clock: &C) -> Timestamp {
204 clock.now()
205 }
206 let time = SimTime { now: Cell::new(3) };
207 assert_eq!(takes_sync_clock(&time).as_micros(), 3);
208 }
209}