Skip to main content

Crate clock

Crate clock 

Source
Expand description

Simple clocks in Rust.

This crate provides Clock, an enum that is either the real clock or a FakeClock with a controllable time. Code that depends on a Clock reads the time through Clock::now and works the same way in both cases. This allows tests to set, advance, and unwind time instead of relying on real time.

Clock is generic over the timestamp. Type aliases are provided for SystemTime and Instant (SystemClock and MonotonicClock). Aliases are also available for other Rust time crates, gated behind feature flags: chrono and time.

§Using the Real Clock

The default Clock is the real clock.

use clock::SystemClock;

let clock = SystemClock::default();
let now = clock.now();

§Controlling the Time in Tests

Create a FakeClock and convert it into a Clock. Clones of FakeClock share the same time so there is no need to wrap it in an Rc or Arc.

use clock::{FakeClock, SystemClock};
use std::time::{Duration, SystemTime};

let fake = FakeClock::from(SystemTime::now());
let clock: SystemClock = fake.clone().into();

let t = clock.now();
fake.advance(Duration::from_secs(60));
assert_eq!(clock.now(), t + Duration::from_secs(60));

fake.unwind(Duration::from_secs(60));
assert_eq!(clock.now(), t);

§Custom Timestamps

Implement Now for your own type to use it as a Clock timestamp. The type is required to be Copy.

use clock::{Clock, Now};
use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Debug, Clone, Copy, PartialEq)]
struct SecondsSinceEpoch(u64);

impl Now for SecondsSinceEpoch {
    fn now() -> Self {
        Self(SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs())
    }
}

let real = Clock::<SecondsSinceEpoch>::default();
let fake = Clock::fake(SecondsSinceEpoch(42));
assert_eq!(fake.now(), SecondsSinceEpoch(42));

Modules§

chrono
Aliases for the chrono crate.
time
Aliases for the time crate.

Structs§

FakeClock
Fake, controllable clock.

Enums§

Clock
Clock that provides the current time.

Traits§

Now
A timestamp that can provide the current real time.

Type Aliases§

FakeMonotonicClock
FakeClock that reports Instant.
FakeSystemClock
FakeClock that reports SystemTime.
MonotonicClock
A Clock that reports Instant.
SystemClock
A Clock that reports SystemTime.