grow-graylog 0.2.0

Rust SDK for Graylog Open by Grow Codes
Documentation
// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
//! Injectable monotonic clock.

use std::fmt;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// Monotonic time source.
pub trait Clock: Send + Sync {
    /// Current instant.
    fn now(&self) -> Instant;
}

/// The real clock ([`Instant::now`]).
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemClock;

impl Clock for SystemClock {
    fn now(&self) -> Instant {
        Instant::now()
    }
}

/// A clock that only moves when [`ManualClock::advance`] is called (tests).
#[derive(Clone)]
pub struct ManualClock {
    base: Instant,
    offset: Arc<Mutex<Duration>>,
}

impl Default for ManualClock {
    fn default() -> Self {
        ManualClock::new()
    }
}

impl ManualClock {
    /// A clock frozen at the current instant.
    pub fn new() -> Self {
        ManualClock {
            base: Instant::now(),
            offset: Arc::new(Mutex::new(Duration::ZERO)),
        }
    }

    /// Moves the clock forward.
    pub fn advance(&self, by: Duration) {
        let mut offset = self.offset.lock().unwrap_or_else(|e| e.into_inner());
        *offset += by;
    }
}

impl Clock for ManualClock {
    fn now(&self) -> Instant {
        self.base + *self.offset.lock().unwrap_or_else(|e| e.into_inner())
    }
}

impl fmt::Debug for ManualClock {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ManualClock").finish_non_exhaustive()
    }
}