Skip to main content

ControllableClock

Trait ControllableClock 

Source
pub trait ControllableClock: Clock {
    // Required methods
    fn set_time(&self, instant: DateTime<Utc>);
    fn add_duration(&self, duration: Duration);
    fn reset(&self);
}
Expand description

A trait representing a clock that can be controlled.

This trait extends Clock to provide methods for manually setting and advancing the clock’s time. It’s primarily designed for testing scenarios where you need precise control over time.

§Warning

This trait should only be used in testing code, not in production code.

§Examples

use qubit_clock::{Clock, ControllableClock, MockClock};
use chrono::{DateTime, Duration, Utc};

let clock = MockClock::new();

// Set to a specific time
let fixed_time = DateTime::parse_from_rfc3339(
    "2024-01-01T00:00:00Z"
).unwrap().with_timezone(&Utc);
clock.set_time(fixed_time);

assert_eq!(clock.time(), fixed_time);

// Advance by 1 hour
clock.add_duration(Duration::hours(1));
assert_eq!(
    clock.time(),
    fixed_time + Duration::hours(1)
);

Required Methods§

Source

fn set_time(&self, instant: DateTime<Utc>)

Sets or aligns the clock to a specific time.

The exact semantics depend on the implementation. For MockClock, this reanchors the current timeline instant to read as instant without changing elapsed mock time.

§Arguments
  • instant - The time to set the clock to (UTC).
§Examples
use qubit_clock::{Clock, ControllableClock, MockClock};
use chrono::{DateTime, Utc};

let clock = MockClock::new();
let time = DateTime::parse_from_rfc3339(
    "2024-01-01T00:00:00Z"
).unwrap().with_timezone(&Utc);

clock.set_time(time);
assert_eq!(clock.time(), time);
Source

fn add_duration(&self, duration: Duration)

Advances the clock by the specified duration.

Implementations may reject durations they cannot represent. For MockClock, negative durations panic because mock timeline time is monotonic.

§Arguments
  • duration - The duration to advance the clock by.
§Examples
use qubit_clock::{Clock, ControllableClock, MockClock};
use chrono::Duration;

let clock = MockClock::new();
let before = clock.time();

clock.add_duration(Duration::hours(1));

let after = clock.time();
assert_eq!(after - before, Duration::hours(1));
Source

fn reset(&self)

Resets the clock to its initial state.

The exact behavior of this method depends on the implementation. For MockClock, it resets the shared mock timeline and wall-clock anchor captured when the clock was created.

§Examples
use qubit_clock::{Clock, ControllableClock, MockClock};
use chrono::Duration;

let clock = MockClock::new();
let initial = clock.time();

clock.add_duration(Duration::hours(1));
clock.reset();

// After reset, time should return to the initial frozen value.
assert_eq!(clock.time(), initial);

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§