Skip to main content

embassy_time/
instant.rs

1use core::fmt;
2use core::ops::{Add, AddAssign, Sub, SubAssign};
3
4use super::{Duration, GCD_1G, GCD_1K, GCD_1M, TICK_HZ};
5
6#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
7#[cfg_attr(feature = "defmt", derive(defmt::Format))]
8/// An Instant in time, based on the MCU's clock ticks since startup.
9pub struct Instant {
10    ticks: u64,
11}
12
13impl Instant {
14    /// The smallest (earliest) value that can be represented by the `Instant` type.
15    pub const MIN: Instant = Instant { ticks: u64::MIN };
16    /// The largest (latest) value that can be represented by the `Instant` type.
17    pub const MAX: Instant = Instant { ticks: u64::MAX };
18
19    /// Returns an Instant representing the current time.
20    #[inline]
21    pub fn now() -> Instant {
22        Instant {
23            ticks: embassy_time_driver::now(),
24        }
25    }
26
27    /// Create an Instant from a tick count since system boot.
28    pub const fn from_ticks(ticks: u64) -> Self {
29        Self { ticks }
30    }
31
32    /// Create an Instant from a nanosecond count since system boot.
33    pub const fn from_nanos(nanos: u64) -> Self {
34        Self {
35            ticks: nanos * (TICK_HZ / GCD_1G) / (1_000_000_000 / GCD_1G),
36        }
37    }
38
39    /// Create an Instant from a microsecond count since system boot.
40    pub const fn from_micros(micros: u64) -> Self {
41        Self {
42            ticks: micros * (TICK_HZ / GCD_1M) / (1_000_000 / GCD_1M),
43        }
44    }
45
46    /// Create an Instant from a millisecond count since system boot.
47    pub const fn from_millis(millis: u64) -> Self {
48        Self {
49            ticks: millis * (TICK_HZ / GCD_1K) / (1000 / GCD_1K),
50        }
51    }
52
53    /// Create an Instant from a second count since system boot.
54    pub const fn from_secs(seconds: u64) -> Self {
55        Self {
56            ticks: seconds * TICK_HZ,
57        }
58    }
59
60    /// Try to create an Instant from a nanosecond count since system boot.
61    /// Fails if the number of nanoseconds is too large.
62    pub const fn try_from_nanos(nanos: u64) -> Option<Self> {
63        let Some(value) = nanos.checked_mul(TICK_HZ / GCD_1G) else {
64            return None;
65        };
66        Some(Self {
67            ticks: value / (1_000_000_000 / GCD_1G),
68        })
69    }
70
71    /// Try to create an Instant from a microsecond count since system boot.
72    /// Fails if the number of microseconds is too large.
73    pub const fn try_from_micros(micros: u64) -> Option<Self> {
74        let Some(value) = micros.checked_mul(TICK_HZ / GCD_1M) else {
75            return None;
76        };
77        Some(Self {
78            ticks: value / (1_000_000 / GCD_1M),
79        })
80    }
81
82    /// Try to create an Instant from a millisecond count since system boot.
83    /// Fails if the number of milliseconds is too large.
84    pub const fn try_from_millis(millis: u64) -> Option<Self> {
85        let Some(value) = millis.checked_mul(TICK_HZ / GCD_1K) else {
86            return None;
87        };
88        Some(Self {
89            ticks: value / (1000 / GCD_1K),
90        })
91    }
92
93    /// Try to create an Instant from a second count since system boot.
94    /// Fails if the number of seconds is too large.
95    pub const fn try_from_secs(seconds: u64) -> Option<Self> {
96        let Some(ticks) = seconds.checked_mul(TICK_HZ) else {
97            return None;
98        };
99        Some(Self { ticks })
100    }
101
102    /// Tick count since system boot.
103    pub const fn as_ticks(&self) -> u64 {
104        self.ticks
105    }
106
107    /// Seconds since system boot.
108    pub const fn as_secs(&self) -> u64 {
109        self.ticks / TICK_HZ
110    }
111
112    /// Milliseconds since system boot.
113    pub const fn as_millis(&self) -> u64 {
114        self.ticks * (1000 / GCD_1K) / (TICK_HZ / GCD_1K)
115    }
116
117    /// Microseconds since system boot.
118    pub const fn as_micros(&self) -> u64 {
119        self.ticks * (1_000_000 / GCD_1M) / (TICK_HZ / GCD_1M)
120    }
121
122    /// Nanoseconds since system boot.
123    pub const fn as_nanos(&self) -> u64 {
124        self.ticks * (1_000_000_000 / GCD_1G) / (TICK_HZ / GCD_1G)
125    }
126
127    /// Duration between this Instant and another Instant
128    ///
129    /// ## Panics
130    ///
131    /// Panics if the computed duration overflows.
132    /// Avoid panics with [`Instant::checked_duration_since()`] or [`Instant::saturating_duration_since()`].
133    pub fn duration_since(&self, earlier: Instant) -> Duration {
134        Duration {
135            ticks: unwrap!(self.ticks.checked_sub(earlier.ticks)),
136        }
137    }
138
139    /// Duration between this Instant and another Instant
140    ///
141    /// This is a panic-free [`Instant::duration_since()`].
142    #[inline]
143    pub const fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
144        if self.ticks < earlier.ticks {
145            None
146        } else {
147            Some(Duration {
148                ticks: self.ticks - earlier.ticks,
149            })
150        }
151    }
152
153    /// Returns the duration since the "earlier" Instant.
154    /// If the "earlier" instant is in the future, the duration is set to zero.
155    ///
156    /// This is a panic-free alternative to [`Instant::duration_since()`].
157    #[inline]
158    pub const fn saturating_duration_since(&self, earlier: Instant) -> Duration {
159        Duration {
160            ticks: if self.ticks < earlier.ticks {
161                0
162            } else {
163                self.ticks - earlier.ticks
164            },
165        }
166    }
167
168    /// Duration elapsed since this Instant.
169    ///
170    /// ## Panics
171    ///
172    /// Panics if the computed duration overflows.
173    pub fn elapsed(&self) -> Duration {
174        Instant::now() - *self
175    }
176
177    /// Adds one Duration to self, returning a new `Instant` or None in the event of an overflow.
178    pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
179        self.ticks.checked_add(duration.ticks).map(|ticks| Instant { ticks })
180    }
181
182    /// Subtracts one Duration to self, returning a new `Instant` or None in the event of an overflow.
183    pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
184        self.ticks.checked_sub(duration.ticks).map(|ticks| Instant { ticks })
185    }
186
187    /// Adds a Duration to self. In case of overflow, the maximum value is returned.
188    #[inline]
189    pub const fn saturating_add(mut self, duration: Duration) -> Self {
190        self.ticks = self.ticks.saturating_add(duration.ticks);
191        self
192    }
193
194    /// Subtracts a Duration from self. In case of overflow, the minimum value is returned.
195    #[inline]
196    pub const fn saturating_sub(mut self, duration: Duration) -> Self {
197        self.ticks = self.ticks.saturating_sub(duration.ticks);
198        self
199    }
200}
201
202impl Add<Duration> for Instant {
203    type Output = Instant;
204
205    /// Computes `Instant + Duration`. [Read more](Add)
206    ///
207    /// ## Panics
208    ///
209    /// Panics if the computed instant overflows.
210    fn add(self, other: Duration) -> Instant {
211        self.checked_add(other)
212            .expect("overflow when adding duration to instant")
213    }
214}
215
216impl AddAssign<Duration> for Instant {
217    /// Computes `Instant += Duration`. [Read more](AddAssign)
218    ///
219    /// ## Panics
220    ///
221    /// Panics if the computed instant overflows.
222    fn add_assign(&mut self, other: Duration) {
223        *self = *self + other;
224    }
225}
226
227impl Sub<Duration> for Instant {
228    type Output = Instant;
229
230    /// Computes `Instant - Duration`. [Read more](Sub)
231    ///
232    /// ## Panics
233    ///
234    /// Panics if the computed instant overflows.
235    fn sub(self, other: Duration) -> Instant {
236        self.checked_sub(other)
237            .expect("overflow when subtracting duration from instant")
238    }
239}
240
241impl SubAssign<Duration> for Instant {
242    /// Computes `Instant -= Duration`. [Read more](SubAssign)
243    ///
244    /// ## Panics
245    ///
246    /// Panics if the computed instant overflows.
247    fn sub_assign(&mut self, other: Duration) {
248        *self = *self - other;
249    }
250}
251
252impl Sub<Instant> for Instant {
253    type Output = Duration;
254
255    /// Computes `Instant - Instant`. [Read more](Sub)
256    ///
257    /// ## Panics
258    ///
259    /// Panics if the computed duration overflows in [`Instant::duration_since`].
260    fn sub(self, other: Instant) -> Duration {
261        self.duration_since(other)
262    }
263}
264
265impl<'a> fmt::Display for Instant {
266    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
267        write!(f, "{} ticks", self.ticks)
268    }
269}