platform/
time.rs

1// SPDX-FileCopyrightText: 2025 Jens Pitkänen <jens.pitkanen@helsinki.fi>
2//
3// SPDX-License-Identifier: GPL-3.0-or-later
4
5use core::{
6    fmt::Debug,
7    ops::{Add, Sub},
8    time::Duration,
9};
10
11/// Analogous to the standard library `Instant` type, representing a point in
12/// time.
13#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
14pub struct Instant(Duration);
15
16impl Debug for Instant {
17    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
18        if *self >= Instant::reference() {
19            f.debug_tuple("Instant")
20                .field(&(self.duration_since(Instant::reference())))
21                .field(&"after reference point")
22                .finish()
23        } else {
24            f.debug_tuple("Instant")
25                .field(&(Instant::reference().duration_since(*self)))
26                .field(&"before reference point")
27                .finish()
28        }
29    }
30}
31
32impl Instant {
33    /// An arbitrary point in time to use as a starting point for other
34    /// instances of [`Instant`].
35    ///
36    /// Generally intended to be used once in the platform implementation. Use
37    /// [`Platform::now`](crate::Platform::now) to get the current point in
38    /// time.
39    pub const fn reference() -> Instant {
40        Instant(Duration::from_secs(u64::MAX / 2))
41    }
42
43    /// Returns the duration from `past_instant` to `self`.
44    ///
45    /// Returns None if `past_instant` is after `self`.
46    pub fn duration_since(self, past_instant: Instant) -> Option<Duration> {
47        if self.0 >= past_instant.0 {
48            Some(self.0 - past_instant.0)
49        } else {
50            None
51        }
52    }
53}
54
55impl Sub<Duration> for Instant {
56    type Output = Instant;
57    fn sub(self, rhs: Duration) -> Self::Output {
58        Instant(self.0 - rhs)
59    }
60}
61
62impl Add<Duration> for Instant {
63    type Output = Instant;
64    fn add(self, rhs: Duration) -> Self::Output {
65        Instant(self.0 + rhs)
66    }
67}