Skip to main content

hdmi_hal/time/
mod.rs

1//! Time for the procedures that drive the PHY and SCDC: a monotonic clock, a delay, and the
2//! [`Timestamp`] the clock reads.
3//!
4//! Two traits, not one: the clock is read where nothing waits (stamping an event, checking a
5//! deadline), and a platform may take them from different peripherals, a free-running counter
6//! and a timer. A procedure that needs both bounds on both; a test double may implement both
7//! on one type, advancing its clock by each delay.
8//!
9//! Neither trait has a forwarding implementation for references (`impl Clock for &C`), as
10//! [`DdcBus`](crate::ddc::DdcBus) has none: hdmi-hal-async's `Delay` cannot have one beside
11//! its `Send` twin's blanket implementation, and the sync traits keep the same shape. An
12//! implementation may implement either trait for a reference to its own type.
13//!
14//! That is also how one test double serves as both when a procedure takes the clock (`&C`)
15//! and the delay (`&mut D`) as separate arguments: the double keeps its time in a `Cell` (or
16//! an atomic, for `Send` code) and implements `Clock` for itself and `Delay` for `&Double`,
17//! so `&double` and `&mut &double` can be passed at once.
18//!
19//! # Over embedded-hal
20//!
21//! [`Delay`] is the stack's own trait rather than a bound on embedded-hal's `DelayNs`, so that
22//! the async companion can have a `Send` twin. An implementation over a `DelayNs` is a few
23//! lines: convert the duration to microseconds, rounding up, and split values beyond `u32`.
24//!
25//! ```
26//! use core::time::Duration;
27//! use embedded_hal::delay::DelayNs;
28//! use hdmi_hal::time::Delay;
29//!
30//! struct HalDelay<D>(D);
31//!
32//! impl<D: DelayNs> Delay for HalDelay<D> {
33//!     fn delay(&mut self, duration: Duration) {
34//!         let mut us = duration.as_nanos().div_ceil(1_000);
35//!         while us > 0 {
36//!             let step = us.min(u128::from(u32::MAX));
37//!             self.0.delay_us(step as u32);
38//!             us -= step;
39//!         }
40//!     }
41//! }
42//! ```
43
44use core::time::Duration;
45
46/// A point in time: microseconds from an arbitrary monotonic epoch.
47///
48/// Only differences between timestamps from one [`Clock`] mean anything. A type of its own
49/// rather than a bare `u64`, so microseconds are not mixed with other counts; `u64`
50/// microseconds do not wrap in any lifetime a device has.
51#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
52pub struct Timestamp(u64);
53
54impl Timestamp {
55    /// The timestamp `micros` microseconds after the epoch.
56    pub const fn from_micros(micros: u64) -> Self {
57        Self(micros)
58    }
59
60    /// Microseconds since the epoch.
61    pub const fn as_micros(self) -> u64 {
62        self.0
63    }
64
65    /// The time from `earlier` to `self`, or `None` if `earlier` is later.
66    pub const fn checked_duration_since(self, earlier: Timestamp) -> Option<Duration> {
67        match self.0.checked_sub(earlier.0) {
68            Some(micros) => Some(Duration::from_micros(micros)),
69            None => None,
70        }
71    }
72
73    /// The time from `earlier` to `self`, or zero if `earlier` is later.
74    pub const fn saturating_duration_since(self, earlier: Timestamp) -> Duration {
75        Duration::from_micros(self.0.saturating_sub(earlier.0))
76    }
77
78    /// The timestamp `duration` after `self`, or `None` on overflow.
79    ///
80    /// A duration that is not a whole number of microseconds is rounded up, so a deadline
81    /// computed with it is never earlier than asked.
82    pub const fn checked_add(self, duration: Duration) -> Option<Timestamp> {
83        let micros = duration.as_nanos().div_ceil(1_000);
84        if micros > u64::MAX as u128 {
85            return None;
86        }
87        match self.0.checked_add(micros as u64) {
88            Some(micros) => Some(Self(micros)),
89            None => None,
90        }
91    }
92}
93
94/// A monotonic clock.
95///
96/// Neither fallible nor `async`: reading a counter does not wait. Takes `&self`, so one clock
97/// can be shared; an implementation with state uses interior mutability. Code that holds a
98/// clock across an `.await` in a task spawned on a multi-threaded executor needs it to be
99/// `Sync` as well (`C: Clock + Sync`), so such a clock keeps its state in an atomic or a lock,
100/// not a `Cell`.
101///
102/// Resolution is the implementation's, and it documents it. The TMDS bring-up procedures
103/// (spiritlevel) wait and poll in steps of 1 ms by default, so a clock of 1 ms or finer
104/// keeps their timing as configured; a coarser one is still correct, but the times they
105/// report are as coarse as the clock.
106pub trait Clock {
107    /// The current time. Never earlier than any time this clock returned before.
108    fn now(&self) -> Timestamp;
109}
110
111/// A delay.
112///
113/// Infallible: a timer that cannot wait leaves the caller nothing to recover with.
114pub trait Delay {
115    /// Wait at least `duration`, rounding up to the implementation's own tick; never less,
116    /// so a minimum wait holds whatever the timer.
117    ///
118    /// Measured on the platform's [`Clock`]: `now()` read after `delay(d)` is at least `d`
119    /// later than `now()` read before it. A test double whose delay does not advance its
120    /// clock breaks this.
121    fn delay(&mut self, duration: Duration);
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127    use core::cell::Cell;
128
129    #[test]
130    fn timestamp_round_trips_micros() {
131        const T: Timestamp = Timestamp::from_micros(1_500);
132        assert_eq!(T.as_micros(), 1_500);
133        assert_eq!(Timestamp::default().as_micros(), 0);
134    }
135
136    #[test]
137    fn duration_since_is_checked_or_saturating() {
138        let a = Timestamp::from_micros(1_000);
139        let b = Timestamp::from_micros(3_500);
140        assert_eq!(
141            b.checked_duration_since(a),
142            Some(Duration::from_micros(2_500))
143        );
144        assert_eq!(a.checked_duration_since(b), None);
145        assert_eq!(a.checked_duration_since(a), Some(Duration::ZERO));
146        assert_eq!(b.saturating_duration_since(a), Duration::from_micros(2_500));
147        assert_eq!(a.saturating_duration_since(b), Duration::ZERO);
148    }
149
150    #[test]
151    fn checked_add_rounds_up_to_the_microsecond() {
152        let t = Timestamp::from_micros(10);
153        assert_eq!(
154            t.checked_add(Duration::from_millis(1)),
155            Some(Timestamp::from_micros(1_010))
156        );
157        assert_eq!(
158            t.checked_add(Duration::from_nanos(1)),
159            Some(Timestamp::from_micros(11))
160        );
161        assert_eq!(t.checked_add(Duration::ZERO), Some(t));
162    }
163
164    #[test]
165    fn checked_add_reports_overflow() {
166        let t = Timestamp::from_micros(u64::MAX - 1);
167        assert_eq!(
168            t.checked_add(Duration::from_micros(1)),
169            Some(Timestamp::from_micros(u64::MAX))
170        );
171        assert_eq!(t.checked_add(Duration::from_micros(2)), None);
172        assert_eq!(Timestamp::default().checked_add(Duration::MAX), None);
173    }
174
175    #[test]
176    fn timestamps_order_by_time() {
177        assert!(Timestamp::from_micros(1) < Timestamp::from_micros(2));
178    }
179
180    /// A clock and delay on one type, the delay advancing the clock, as a test double does.
181    struct SimTime {
182        now: Cell<u64>,
183    }
184
185    impl Clock for SimTime {
186        fn now(&self) -> Timestamp {
187            Timestamp::from_micros(self.now.get())
188        }
189    }
190
191    impl Delay for SimTime {
192        fn delay(&mut self, duration: Duration) {
193            let us = duration.as_nanos().div_ceil(1_000) as u64;
194            self.now.set(self.now.get() + us);
195        }
196    }
197
198    fn wait_until<T: Clock + Delay>(time: &mut T, deadline: Timestamp, poll: Duration) -> u32 {
199        let mut polls = 0;
200        while time.now() < deadline {
201            time.delay(poll);
202            polls += 1;
203        }
204        polls
205    }
206
207    #[test]
208    fn clock_and_delay_compose_on_one_type() {
209        let mut time = SimTime { now: Cell::new(0) };
210        let start = time.now();
211        let deadline = start.checked_add(Duration::from_millis(5)).unwrap();
212        assert_eq!(wait_until(&mut time, deadline, Duration::from_millis(1)), 5);
213        assert_eq!(
214            time.now().checked_duration_since(start),
215            Some(Duration::from_millis(5))
216        );
217    }
218}