Skip to main content

can_iso_tp/
timer.rs

1//! Clock abstraction to support `std` and `no_std` environments.
2
3use core::time::Duration;
4
5/// Abstraction over a monotonic clock.
6///
7/// ISO-TP needs a monotonically increasing time source to implement deadlines (N_As, N_Ar, …) and
8/// pacing (STmin).
9pub trait Clock {
10    /// Instant type produced by the clock.
11    type Instant: Copy + PartialOrd;
12
13    /// Current instant.
14    fn now(&self) -> Self::Instant;
15    /// Elapsed duration since an instant.
16    fn elapsed(&self, earlier: Self::Instant) -> Duration;
17    /// Add a duration to an instant (saturating if needed).
18    fn add(&self, instant: Self::Instant, dur: Duration) -> Self::Instant;
19}
20
21#[cfg(feature = "std")]
22/// Standard library clock wrapper.
23#[derive(Clone, Copy, Debug, Default)]
24pub struct StdClock;
25
26#[cfg(feature = "std")]
27impl Clock for StdClock {
28    type Instant = std::time::Instant;
29
30    /// Return `Instant::now()`.
31    fn now(&self) -> Self::Instant {
32        std::time::Instant::now()
33    }
34
35    /// Use `Instant::elapsed()`.
36    fn elapsed(&self, earlier: Self::Instant) -> Duration {
37        earlier.elapsed()
38    }
39
40    /// Add with `checked_add`, saturating on overflow.
41    fn add(&self, instant: Self::Instant, dur: Duration) -> Self::Instant {
42        instant.checked_add(dur).unwrap_or(instant)
43    }
44}