Skip to main content

matter_kit/platform/
time.rs

1//! Monotonic time, in the units the specification uses.
2//!
3//! Matter states its timings in milliseconds (MRP intervals, subscription intervals) and
4//! in seconds (fail-safe, idle-mode duration), and its wall-clock times in microseconds
5//! since the Matter epoch. Doing arithmetic across those in a `u32` is how off-by-1000
6//! bugs happen, so there is one duration type, it is microseconds in a `u64`, and it
7//! saturates rather than wraps.
8//!
9//! `u64` microseconds is about 584 000 years, so saturation is unreachable in practice —
10//! but it is the behaviour a hostile peer's timing values should meet, rather than a
11//! debug-build panic and a release-build wrap.
12
13/// A span of time, in microseconds.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
15pub struct Duration(u64);
16
17impl Duration {
18    /// No time at all.
19    pub const ZERO: Self = Self(0);
20
21    /// The longest representable span, used as "never".
22    pub const MAX: Self = Self(u64::MAX);
23
24    /// From microseconds.
25    #[must_use]
26    pub const fn from_micros(micros: u64) -> Self {
27        Self(micros)
28    }
29
30    /// From milliseconds, saturating.
31    #[must_use]
32    pub const fn from_millis(millis: u64) -> Self {
33        Self(millis.saturating_mul(1_000))
34    }
35
36    /// From seconds, saturating.
37    #[must_use]
38    pub const fn from_secs(secs: u64) -> Self {
39        Self(secs.saturating_mul(1_000_000))
40    }
41
42    /// As microseconds.
43    #[must_use]
44    pub const fn as_micros(self) -> u64 {
45        self.0
46    }
47
48    /// As whole milliseconds, rounding down.
49    #[must_use]
50    pub const fn as_millis(self) -> u64 {
51        self.0.wrapping_div(1_000)
52    }
53
54    /// As whole seconds, rounding down.
55    #[must_use]
56    pub const fn as_secs(self) -> u64 {
57        self.0.wrapping_div(1_000_000)
58    }
59
60    /// Addition that saturates instead of wrapping.
61    #[must_use]
62    pub const fn saturating_add(self, other: Self) -> Self {
63        Self(self.0.saturating_add(other.0))
64    }
65
66    /// Subtraction that saturates at zero.
67    #[must_use]
68    pub const fn saturating_sub(self, other: Self) -> Self {
69        Self(self.0.saturating_sub(other.0))
70    }
71
72    /// Multiplication by a scalar, saturating.
73    #[must_use]
74    pub const fn saturating_mul(self, factor: u64) -> Self {
75        Self(self.0.saturating_mul(factor))
76    }
77
78    /// Multiplication by a rational `numerator / denominator`, saturating.
79    ///
80    /// MRP's backoff constants are rationals — a base of 1.6, a jitter of 0.25, a margin
81    /// of 1.1 (Core §4.12.2.1) — and doing that in floating point on a microcontroller
82    /// that has no FPU is both slow and needlessly imprecise. This is how the crate
83    /// computes them.
84    #[must_use]
85    pub const fn mul_ratio(self, numerator: u64, denominator: u64) -> Self {
86        // Split into whole and fractional parts to keep the product inside `u64` for the
87        // spans Matter actually uses. `checked_div`/`checked_rem` rather than `/` and `%`
88        // so a zero denominator is a value — `Duration::MAX`, i.e. "never" — instead of a
89        // division trap.
90        let (Some(whole), Some(rest)) = (
91            self.0.checked_div(denominator),
92            self.0.checked_rem(denominator),
93        ) else {
94            return Self::MAX;
95        };
96        let Some(fraction) = rest.saturating_mul(numerator).checked_div(denominator) else {
97            return Self::MAX;
98        };
99        Self(whole.saturating_mul(numerator).saturating_add(fraction))
100    }
101}
102
103/// A point on a monotonic timeline.
104///
105/// The origin is whatever the [`Timer`](super::Timer) chose; only differences are
106/// meaningful. It never goes backwards and is unaffected by the wall clock changing.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
108pub struct Instant(u64);
109
110impl Instant {
111    /// The timeline's origin.
112    pub const ZERO: Self = Self(0);
113
114    /// The furthest representable point, used as "never".
115    pub const MAX: Self = Self(u64::MAX);
116
117    /// From microseconds since the origin.
118    #[must_use]
119    pub const fn from_micros(micros: u64) -> Self {
120        Self(micros)
121    }
122
123    /// As microseconds since the origin.
124    #[must_use]
125    pub const fn as_micros(self) -> u64 {
126        self.0
127    }
128
129    /// As milliseconds since the origin — Core §7.19.2.7's `systime-ms`.
130    ///
131    /// Truncating, like every other reading of a coarser clock from a finer one. The
132    /// specification's own use of it is a client correlating its clock with the node's
133    /// (§11.12.7.3), where a sub-millisecond difference is below the jitter of the message
134    /// carrying it.
135    #[must_use]
136    pub const fn as_millis(self) -> u64 {
137        self.0 / 1000
138    }
139
140    /// This instant plus a span, saturating.
141    #[must_use]
142    pub const fn saturating_add(self, d: Duration) -> Self {
143        Self(self.0.saturating_add(d.0))
144    }
145
146    /// This instant minus a span, saturating at the origin.
147    #[must_use]
148    pub const fn saturating_sub(self, d: Duration) -> Self {
149        Self(self.0.saturating_sub(d.0))
150    }
151
152    /// How long from `earlier` to this instant; zero if this one is not later.
153    #[must_use]
154    pub const fn saturating_duration_since(self, earlier: Self) -> Duration {
155        Duration(self.0.saturating_sub(earlier.0))
156    }
157
158    /// Whether this instant has been reached at `now`.
159    #[must_use]
160    pub const fn is_elapsed_at(self, now: Self) -> bool {
161        now.0 >= self.0
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn unit_conversions() {
171        assert_eq!(Duration::from_millis(1).as_micros(), 1_000);
172        assert_eq!(Duration::from_secs(1).as_millis(), 1_000);
173        assert_eq!(Duration::from_micros(1_999).as_millis(), 1);
174    }
175
176    #[test]
177    fn arithmetic_saturates_rather_than_wrapping() {
178        assert_eq!(
179            Duration::MAX.saturating_add(Duration::from_secs(1)),
180            Duration::MAX
181        );
182        assert_eq!(
183            Duration::ZERO.saturating_sub(Duration::from_secs(1)),
184            Duration::ZERO
185        );
186        assert_eq!(Duration::MAX.saturating_mul(2), Duration::MAX);
187        assert_eq!(
188            Instant::MAX.saturating_add(Duration::from_secs(1)),
189            Instant::MAX
190        );
191        assert_eq!(
192            Instant::ZERO.saturating_sub(Duration::from_secs(1)),
193            Instant::ZERO
194        );
195        // Saturating from_secs, so a hostile "seconds" value cannot wrap into a short one.
196        assert_eq!(Duration::from_secs(u64::MAX), Duration::MAX);
197    }
198
199    #[test]
200    fn mul_ratio_is_mrps_arithmetic() {
201        // MRP_BACKOFF_BASE is 1.6 (Core §4.12.2.1).
202        let base = Duration::from_millis(300);
203        assert_eq!(base.mul_ratio(16, 10).as_millis(), 480);
204        // 1.1 margin.
205        assert_eq!(base.mul_ratio(11, 10).as_millis(), 330);
206        // A quarter, for jitter.
207        assert_eq!(base.mul_ratio(1, 4).as_millis(), 75);
208        // Precision is kept for values that do not divide evenly.
209        assert_eq!(Duration::from_micros(7).mul_ratio(16, 10).as_micros(), 11);
210        // A zero denominator does not divide by zero.
211        assert_eq!(base.mul_ratio(1, 0), Duration::MAX);
212    }
213
214    #[test]
215    fn instants_order_and_subtract() {
216        let a = Instant::from_micros(100);
217        let b = Instant::from_micros(250);
218        assert!(a < b);
219        assert_eq!(b.saturating_duration_since(a), Duration::from_micros(150));
220        assert_eq!(a.saturating_duration_since(b), Duration::ZERO);
221        assert!(a.is_elapsed_at(b));
222        assert!(!b.is_elapsed_at(a));
223        assert!(
224            a.is_elapsed_at(a),
225            "a deadline is reached at its own instant"
226        );
227    }
228}