token-bucket 11.1.0

Zero-dependency, lock-free atomic GCRA, Fixed-Window, Token-Bucket, and 64-way sharded bounded keyed rate-limiting engine.
Documentation
use super::*;

/// Default construction capturing the current monotonic instant.
impl Default for MonotonicClock {
    /// Creates a `MonotonicClock` anchored at `Instant::now()`.
    #[inline(always)]
    fn default() -> Self {
        Self::new()
    }
}

/// Core monotonic time measurement operations for `MonotonicClock`.
impl MonotonicClock {
    /// Creates a new monotonic clock anchored at the current instant.
    #[inline(always)]
    pub fn new() -> Self {
        Self {
            origin: Instant::now(),
        }
    }

    /// Creates a monotonic clock anchored at a caller-supplied instant.
    ///
    /// # Arguments
    ///
    /// - `Instant` - The monotonic origin instant.
    #[inline(always)]
    pub fn from_instant(origin: Instant) -> Self {
        Self { origin }
    }

    /// Returns the monotonic origin instant of this clock.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The monotonic clock.
    ///
    /// # Returns
    ///
    /// - `Instant` - The origin timestamp.
    #[inline(always)]
    pub fn get_origin(&self) -> Instant {
        self.origin
    }

    /// Returns elapsed nanoseconds since clock creation, saturating at `u64::MAX`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The monotonic clock.
    ///
    /// # Returns
    ///
    /// - `u64` - Elapsed monotonic nanoseconds.
    #[inline(always)]
    pub fn now_ns(&self) -> u64 {
        let elapsed: Duration = Instant::now().saturating_duration_since(self.get_origin());
        elapsed
            .as_secs()
            .saturating_mul(CLOCK_NANOS_PER_SEC)
            .saturating_add(u64::from(elapsed.subsec_nanos()))
    }

    /// Converts an explicit `Instant` into elapsed nanoseconds since this clock's origin.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The monotonic clock.
    /// - `Instant` - The instant to convert.
    ///
    /// # Returns
    ///
    /// - `u64` - Elapsed monotonic nanoseconds, saturating at `0` and `u64::MAX`.
    #[inline(always)]
    pub fn elapsed_ns_at(&self, instant: Instant) -> u64 {
        let elapsed: Duration = instant.saturating_duration_since(self.get_origin());
        elapsed
            .as_secs()
            .saturating_mul(CLOCK_NANOS_PER_SEC)
            .saturating_add(u64::from(elapsed.subsec_nanos()))
    }
}