Skip to main content

time/
realtime.rs

1use crate::{Error, Result};
2use core::time::Duration;
3
4const NANOS_PER_SECOND: i128 = 1_000_000_000;
5
6/// Signed nanoseconds since 1970-01-01 00:00:00 UTC, without timezone or DST.
7/// Leap seconds follow the supplying source's Unix/POSIX time convention.
8/// The full i128 range is representable; conversions and clock arithmetic are checked.
9#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
10pub struct Timestamp(i128);
11
12impl Timestamp {
13    pub const fn from_nanos(nanoseconds: i128) -> Self {
14        Self(nanoseconds)
15    }
16
17    pub const fn as_nanos(self) -> i128 {
18        self.0
19    }
20
21    /// Whole Unix seconds, rounding toward the past (including before the epoch).
22    pub fn try_as_seconds(self) -> Result<i64> {
23        self.0
24            .div_euclid(NANOS_PER_SECOND)
25            .try_into()
26            .map_err(|_| Error::Overflow)
27    }
28
29    /// Convert for consumers whose timestamp format excludes pre-epoch dates.
30    pub fn try_into_duration(self) -> Result<Duration> {
31        if self.0 < 0 {
32            return Err(Error::Overflow);
33        }
34        let seconds = u64::try_from(self.0 / NANOS_PER_SECOND).map_err(|_| Error::Overflow)?;
35        Ok(Duration::new(seconds, (self.0 % NANOS_PER_SECOND) as u32))
36    }
37}
38
39impl From<Duration> for Timestamp {
40    fn from(value: Duration) -> Self {
41        // Duration's u64 seconds always fit in signed i128 nanoseconds.
42        Self(value.as_nanos() as i128)
43    }
44}
45
46/// Provenance claimed by a trusted runtime caller, not an authentication mechanism.
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub enum ClockSource {
49    Host,
50    Rtc,
51    /// The firmware's build date, used as the fallback epoch when no real-time
52    /// clock, network or manual source established UTC. It is never written
53    /// back to a real-time clock.
54    BuildDate,
55    Manual,
56    Network,
57}
58
59/// An epoch sample supplied by a platform or synchronization service.
60///
61/// `resolution` is the source's quantization, not an accuracy guarantee. `accuracy`
62/// is a source-reported uncertainty at sampling time; None means unknown. Neither
63/// field promises long-term accuracy: oscillator drift and suspend accumulate error.
64/// The caller must account for acquisition/transport delay before submitting it.
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub struct RealtimeSample {
67    pub timestamp: Timestamp,
68    pub source: ClockSource,
69    pub resolution: Duration,
70    pub accuracy: Option<Duration>,
71}
72
73/// A trustworthy Unix epoch source: RTC driver, host, manual input or network service.
74///
75/// Reading is explicit, only at bootstrap or `Manager::synchronize`; realtime reads
76/// never poll the source. A source must return an error rather than fabricate an
77/// epoch when unavailable. The sample is anchored when read completes; slow sources
78/// should compensate latency and include its uncertainty in the supplied accuracy.
79pub trait RealtimeSource: Send + Sync {
80    fn read(&self) -> Result<RealtimeSample>;
81}
82
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub struct Synchronization {
85    pub source: ClockSource,
86    pub at_monotonic: Duration,
87    pub resolution: Duration,
88    pub accuracy: Option<Duration>,
89}
90
91/// No synchronization means UTC is invalid, regardless of the monotonic reading.
92/// The correction starts at zero and is reset by explicit invalidation; it is
93/// replaced (never accumulated) by each successful set operation.
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
95pub struct RealtimeStatus {
96    pub correction_nanoseconds: i128,
97    pub synchronization: Option<Synchronization>,
98}