stm32_hal2/
instant.rs

1//! This module fits the requirement of `rtic-monotonic`, but has uses beyond that.
2
3use core::{
4    self,
5    cmp::{Ord, Ordering, PartialOrd},
6    ops::{Add, Sub},
7    time::Duration,
8};
9
10/// A time instant, from the start of a timer, with nanosecond precision. Has  methods similar
11/// to that found in `core::Duration`.
12#[derive(Eq, PartialEq, PartialOrd, Copy, Clone, Default)]
13pub struct Instant {
14    /// Total count, in microseconds. We use a signed integer for use with Durations.
15    count_ns: i128,
16    // todo: Count ticks instead?
17}
18
19/// An instant. Designed to be, in its most basic sense, similar to `std::time::Instant`. Created
20/// from the `now()` method on a `Timer`. Can be compared to create a `core::Duration`. Standalone
21/// methods on this struct are similar to those on `Duration`, but return timestamps since the timer start.
22impl Instant {
23    pub(crate) fn new(count_ns: i128) -> Self {
24        Self { count_ns }
25    }
26
27    /// The time, in seconds.
28    pub fn as_secs(&self) -> f32 {
29        self.count_ns as f32 / 1_000_000_000.
30    }
31
32    /// The time, in milliseconds.
33    pub fn as_millis(&self) -> u32 {
34        (self.count_ns / 1_000_000) as u32
35    }
36
37    /// The time, in milliseconds as an f32.
38    pub fn as_millis_f32(&self) -> f32 {
39        self.count_ns as f32 / 1_000_000.
40    }
41
42    /// The time, in microseconds
43    pub fn as_micros(&self) -> u64 {
44        (self.count_ns / 1_000) as u64
45    }
46
47    /// The time, in nanoseconds
48    pub fn as_nanos(&self) -> u128 {
49        self.count_ns as u128
50    }
51}
52
53impl Ord for Instant {
54    fn cmp(&self, other: &Self) -> Ordering {
55        // self.count_us.cmp(&other.count_us)
56        self.count_ns.cmp(&other.count_ns)
57    }
58}
59
60impl Add<Duration> for Instant {
61    type Output = Self;
62
63    fn add(self, rhs: Duration) -> Self::Output {
64        Self {
65            count_ns: self.count_ns + rhs.as_nanos() as i128,
66        }
67    }
68}
69
70impl Sub<Duration> for Instant {
71    type Output = Self;
72
73    fn sub(self, rhs: Duration) -> Self::Output {
74        Self {
75            count_ns: self.count_ns - rhs.as_nanos() as i128,
76        }
77    }
78}
79
80impl Sub<Self> for Instant {
81    type Output = Duration;
82
83    fn sub(self, rhs: Self) -> Self::Output {
84        // todo: Handle negative overflow.
85        Duration::from_nanos((self.count_ns - rhs.count_ns) as u64)
86    }
87}