Skip to main content

token_bucket/clock/
impl.rs

1use super::*;
2
3/// Default construction capturing the current monotonic instant.
4impl Default for MonotonicClock {
5    /// Creates a `MonotonicClock` anchored at `Instant::now()`.
6    #[inline(always)]
7    fn default() -> Self {
8        Self::new()
9    }
10}
11
12/// Core monotonic time measurement operations for `MonotonicClock`.
13impl MonotonicClock {
14    /// Creates a new monotonic clock anchored at the current instant.
15    #[inline(always)]
16    pub fn new() -> Self {
17        Self {
18            origin: Instant::now(),
19        }
20    }
21
22    /// Creates a monotonic clock anchored at a caller-supplied instant.
23    ///
24    /// # Arguments
25    ///
26    /// - `Instant` - The monotonic origin instant.
27    #[inline(always)]
28    pub fn from_instant(origin: Instant) -> Self {
29        Self { origin }
30    }
31
32    /// Returns the monotonic origin instant of this clock.
33    ///
34    /// # Arguments
35    ///
36    /// - `&Self` - The monotonic clock.
37    ///
38    /// # Returns
39    ///
40    /// - `Instant` - The origin timestamp.
41    #[inline(always)]
42    pub fn get_origin(&self) -> Instant {
43        self.origin
44    }
45
46    /// Returns elapsed nanoseconds since clock creation, saturating at `u64::MAX`.
47    ///
48    /// # Arguments
49    ///
50    /// - `&Self` - The monotonic clock.
51    ///
52    /// # Returns
53    ///
54    /// - `u64` - Elapsed monotonic nanoseconds.
55    #[inline(always)]
56    pub fn now_ns(&self) -> u64 {
57        let elapsed: Duration = Instant::now().saturating_duration_since(self.get_origin());
58        elapsed
59            .as_secs()
60            .saturating_mul(CLOCK_NANOS_PER_SEC)
61            .saturating_add(u64::from(elapsed.subsec_nanos()))
62    }
63
64    /// Converts an explicit `Instant` into elapsed nanoseconds since this clock's origin.
65    ///
66    /// # Arguments
67    ///
68    /// - `&Self` - The monotonic clock.
69    /// - `Instant` - The instant to convert.
70    ///
71    /// # Returns
72    ///
73    /// - `u64` - Elapsed monotonic nanoseconds, saturating at `0` and `u64::MAX`.
74    #[inline(always)]
75    pub fn elapsed_ns_at(&self, instant: Instant) -> u64 {
76        let elapsed: Duration = instant.saturating_duration_since(self.get_origin());
77        elapsed
78            .as_secs()
79            .saturating_mul(CLOCK_NANOS_PER_SEC)
80            .saturating_add(u64::from(elapsed.subsec_nanos()))
81    }
82}