timed_map/
clock.rs

1#[cfg(feature = "std")]
2use super::*;
3
4/// Provides elapsed time since the creation of the implementer, in seconds.
5///
6/// This is designed to enable `TimedMap` to work in both `std` and `no_std` environments.
7///
8/// When the `std` feature is enabled, the implementer is expected to use `StdClock`,
9/// which relies on `std::time::Instant` for timekeeping.
10///
11/// In `no_std` environments, users should implement the `elapsed_seconds_since_creation` manually,
12/// typically using a custom time source such as embedded system's hardware timer.
13///
14/// # Example usage:
15/// ```rs
16/// struct CustomClock;
17///
18/// impl Clock for CustomClock {
19///     fn elapsed_seconds_since_creation(&self) -> u64 {
20///     // Hardware-specific implementation to measure the elapsed time.
21///         0 // placeholder
22///     }
23/// }
24///
25/// let clock = CustomClock;
26/// let current_time = clock.elapsed_seconds_since_creation();
27/// ```
28pub trait Clock {
29    /// Returns the elapsed time since the creation of the implementer, in seconds.
30    fn elapsed_seconds_since_creation(&self) -> u64;
31}
32
33/// A default `Clock` implementation when `std` is enabled.
34///
35/// When `std` is enabled, this is automatically utilized in `TimedMap`
36/// to avoid requiring users to implement the `Clock` trait themselves.
37#[cfg(feature = "std")]
38#[derive(Clone, Debug)]
39pub struct StdClock {
40    creation: Instant,
41}
42
43#[cfg(feature = "std")]
44impl Default for StdClock {
45    fn default() -> Self {
46        Self {
47            creation: Instant::now(),
48        }
49    }
50}
51
52#[cfg(feature = "std")]
53impl Clock for StdClock {
54    fn elapsed_seconds_since_creation(&self) -> u64 {
55        self.creation.elapsed().as_secs()
56    }
57}