60 lines
1.8 KiB
Rust
60 lines
1.8 KiB
Rust
use prometeu_hal::WallClock;
|
|
use std::sync::atomic::{AtomicU64, Ordering};
|
|
|
|
/// A native harness-controlled civil clock. Reads and runtime ticks never advance it.
|
|
#[derive(Debug, Default)]
|
|
pub struct ControlledWallClock {
|
|
seconds: AtomicU64,
|
|
}
|
|
|
|
impl ControlledWallClock {
|
|
pub fn new(seconds: u64) -> Self {
|
|
Self { seconds: AtomicU64::new(seconds) }
|
|
}
|
|
|
|
/// Set civil time explicitly, including backwards adjustments.
|
|
pub fn set(&self, seconds: u64) {
|
|
self.seconds.store(seconds, Ordering::Relaxed);
|
|
}
|
|
|
|
/// Advance civil time explicitly, saturating at the largest timestamp.
|
|
// `try_update` requires Rust 1.95; keep older stable CI toolchains compatible.
|
|
#[allow(deprecated)]
|
|
pub fn advance(&self, seconds: u64) {
|
|
// Harness control may retry on a concurrent update; reads remain a single load.
|
|
let _ = self.seconds.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
|
|
Some(current.saturating_add(seconds))
|
|
});
|
|
}
|
|
}
|
|
|
|
impl WallClock for ControlledWallClock {
|
|
fn utc_unix_seconds(&self) -> u64 {
|
|
self.seconds.load(Ordering::Relaxed)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn explicit_changes_allow_regression_and_saturate_without_advancing_on_read() {
|
|
let clock = ControlledWallClock::default();
|
|
assert_eq!(clock.utc_unix_seconds(), 0);
|
|
clock.set(100);
|
|
for _ in 0..10 {
|
|
assert_eq!(clock.utc_unix_seconds(), 100);
|
|
}
|
|
clock.advance(9);
|
|
assert_eq!(clock.utc_unix_seconds(), 109);
|
|
clock.set(3);
|
|
assert_eq!(clock.utc_unix_seconds(), 3);
|
|
clock.advance(u64::MAX);
|
|
clock.advance(1);
|
|
assert_eq!(clock.utc_unix_seconds(), u64::MAX);
|
|
clock.set(0);
|
|
assert_eq!(clock.utc_unix_seconds(), 0);
|
|
}
|
|
}
|