pub struct ManualClock { /* private fields */ }std only.Expand description
A clock under your control, for deterministic testing.
ManualClock captures the OS monotonic and wall-clock anchors at
construction, then advances only when you call
advance. The clock never moves on its own, so tests
against time-driven code become point-in-time deterministic.
ManualClock is Send + Sync. Wrap it in an Arc to share with the
code under test; both the test driver and the production code can hold
references to the same clock and observe consistent readings.
§Examples
use clock_lib::{Clock, ManualClock, Monotonic};
use std::sync::Arc;
use std::time::Duration;
// A "ttl expired?" check that can be driven without sleeping.
fn expired<C: Clock>(clock: &C, stamp: Monotonic, ttl: Duration) -> bool {
clock.now().duration_since(stamp) >= ttl
}
let clock = Arc::new(ManualClock::new());
let stamp = clock.now();
assert!(!expired(&*clock, stamp, Duration::from_secs(60)));
clock.advance(Duration::from_secs(60));
assert!(expired(&*clock, stamp, Duration::from_secs(60)));Implementations§
Source§impl ManualClock
impl ManualClock
Sourcepub fn new() -> Self
pub fn new() -> Self
Constructs a new manual clock anchored at the current OS time.
§Examples
use clock_lib::ManualClock;
let clock = ManualClock::new();Sourcepub fn advance(&self, by: Duration)
pub fn advance(&self, by: Duration)
Advances the clock forward by by.
Successive calls accumulate. If the cumulative offset would exceed
u64::MAX nanoseconds (≈584 years), the offset saturates —
well outside any plausible test scenario.
§Examples
use clock_lib::{Clock, ManualClock};
use std::time::Duration;
let clock = ManualClock::new();
let a = clock.now();
clock.advance(Duration::from_secs(5));
let b = clock.now();
assert_eq!(b.duration_since(a), Duration::from_secs(5));Sourcepub fn offset(&self) -> Duration
pub fn offset(&self) -> Duration
Returns the cumulative offset that has been added to this clock since it was constructed.
§Examples
use clock_lib::ManualClock;
use std::time::Duration;
let clock = ManualClock::new();
clock.advance(Duration::from_secs(1));
clock.advance(Duration::from_secs(2));
assert_eq!(clock.offset(), Duration::from_secs(3));