printobserver_core/clock.rs
1//! The one time source this crate reads.
2//!
3//! Core never calls the system clock. Every instant it stamps, and every
4//! comparison it makes against one — a bounded intervention's expiry, the
5//! agent's minimum interval — is read through a [`Clock`], so that expiry is
6//! driven by time passing and by nothing else and a test drives it by
7//! advancing this one dependency alone.
8
9use printobserver_types::Timestamp;
10
11/// The instant core reads the current time from.
12///
13/// Shareable across threads, because the expiry driver reads it from a thread
14/// of its own while callers read it from theirs.
15pub trait Clock: Send + Sync {
16 /// The instant now.
17 fn now(&self) -> Timestamp;
18}
19
20/// The system's own clock, which is what a running supervisor is given.
21#[derive(Debug, Clone, Copy, Default)]
22pub struct SystemClock;
23
24impl Clock for SystemClock {
25 fn now(&self) -> Timestamp {
26 Timestamp::now()
27 }
28}
29
30/// The instant `seconds` after `instant`.
31///
32/// Sub-second precision is kept: a bounded change asked to stand for a minute
33/// stands for a minute, rather than for a minute less however far into a second
34/// it happened to be made.
35///
36/// # Errors
37///
38/// Returns the timestamp crate's own error when the sum denotes no
39/// representable instant.
40pub fn plus_seconds(
41 instant: Timestamp,
42 seconds: i64,
43) -> Result<Timestamp, printobserver_types::TimestampError> {
44 instant.plus_seconds(seconds)
45}
46
47/// How many whole seconds `later` is after `earlier`, saturating.
48#[must_use]
49pub fn seconds_between(earlier: Timestamp, later: Timestamp) -> i64 {
50 unix_seconds(later).saturating_sub(unix_seconds(earlier))
51}
52
53/// One instant as whole seconds after the Unix epoch.
54#[must_use]
55pub fn unix_seconds(instant: Timestamp) -> i64 {
56 instant.as_utc().timestamp()
57}