Skip to main content

Clock

Trait Clock 

Source
pub trait Clock: Send + Sync {
    // Required methods
    fn now(&self) -> Monotonic;
    fn wall(&self) -> Wall;
}
Available on crate feature std only.
Expand description

A source of time.

Clock exposes both kinds of reading this crate keeps separate: a monotonic reading via Clock::now and a wall-clock reading via Clock::wall. Implementations must be safe to share across threads.

In production, take a Clock (or &dyn Clock, or Arc<dyn Clock>) as a dependency and use SystemClock at the top of your call graph. In tests, substitute ManualClock and drive time forward by calling ManualClock::advance.

Clock is also implemented for Arc<C> and &C where C: Clock, so the same value can be shared and reused freely.

§Examples

use clock_lib::{Clock, ManualClock, SystemClock};
use std::time::Duration;

fn took_at_least<C: Clock>(clock: &C, start: clock_lib::Monotonic, target: Duration) -> bool {
    clock.now().duration_since(start) >= target
}

// Production
let sys = SystemClock::new();
let start = sys.now();
assert!(!took_at_least(&sys, start, Duration::from_secs(60 * 60)));

// Test — no sleep, fully deterministic
let test = ManualClock::new();
let start = test.now();
test.advance(Duration::from_secs(60 * 60));
assert!(took_at_least(&test, start, Duration::from_secs(60 * 60)));

Required Methods§

Source

fn now(&self) -> Monotonic

Returns the current monotonic reading.

Source

fn wall(&self) -> Wall

Returns the current wall-clock reading.

Implementations on Foreign Types§

Source§

impl<C: Clock + ?Sized> Clock for &C

Source§

fn now(&self) -> Monotonic

Source§

fn wall(&self) -> Wall

Source§

impl<C: Clock + ?Sized> Clock for Arc<C>

Source§

fn now(&self) -> Monotonic

Source§

fn wall(&self) -> Wall

Implementors§