Skip to main content

coqui_peer/
clock.rs

1use alloc::sync::Arc;
2use core::fmt;
3use core::time::Duration;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6/// The wall clock a [`TrustStore`](crate::TrustStore) or a pairing desk reads for expiry and
7/// retirement times.
8///
9/// [`Clock::system`] (the default) reads the system time; [`Clock::from_fn`] takes any
10/// function, so a test can move time without sleeping.
11#[derive(Clone)]
12pub struct Clock(Arc<dyn Fn() -> SystemTime + Send + Sync>);
13
14impl Clock {
15    /// The system clock.
16    pub fn system() -> Self {
17        Self(Arc::new(SystemTime::now))
18    }
19
20    /// A clock that reads `now`.
21    pub fn from_fn(now: impl Fn() -> SystemTime + Send + Sync + 'static) -> Self {
22        Self(Arc::new(now))
23    }
24
25    /// The current time.
26    pub fn now(&self) -> SystemTime {
27        (self.0)()
28    }
29}
30
31impl Default for Clock {
32    fn default() -> Self {
33        Self::system()
34    }
35}
36
37impl fmt::Debug for Clock {
38    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
39        formatter.write_str("Clock")
40    }
41}
42
43/// Whole seconds since the Unix epoch; a time before it is 0.
44pub(crate) fn unix_seconds(time: SystemTime) -> u64 {
45    time.duration_since(UNIX_EPOCH)
46        .map_or(0, |elapsed| elapsed.as_secs())
47}
48
49/// The time `seconds` after the Unix epoch, saturating at the latest time this platform holds.
50pub(crate) fn from_unix_seconds(seconds: u64) -> SystemTime {
51    UNIX_EPOCH
52        .checked_add(Duration::from_secs(seconds))
53        .unwrap_or_else(|| UNIX_EPOCH + Duration::from_secs(u64::from(u32::MAX)))
54}
55
56/// `time` plus `by`, or the latest of `time` plus a century, a year, or nothing that the platform
57/// can hold: `None` means "never", and neither it nor a `Duration::MAX` overflows.
58pub(crate) fn later(time: SystemTime, by: Option<Duration>) -> SystemTime {
59    let by = by.unwrap_or(Duration::MAX);
60    [
61        by,
62        Duration::from_secs(100 * 365 * 86_400),
63        Duration::from_secs(365 * 86_400),
64    ]
65    .into_iter()
66    .filter(|step| *step <= by)
67    .find_map(|step| time.checked_add(step))
68    .unwrap_or(time)
69}