1use alloc::sync::Arc;
2use core::fmt;
3use core::time::Duration;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6#[derive(Clone)]
12pub struct Clock(Arc<dyn Fn() -> SystemTime + Send + Sync>);
13
14impl Clock {
15 pub fn system() -> Self {
17 Self(Arc::new(SystemTime::now))
18 }
19
20 pub fn from_fn(now: impl Fn() -> SystemTime + Send + Sync + 'static) -> Self {
22 Self(Arc::new(now))
23 }
24
25 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
43pub(crate) fn unix_seconds(time: SystemTime) -> u64 {
45 time.duration_since(UNIX_EPOCH)
46 .map_or(0, |elapsed| elapsed.as_secs())
47}
48
49pub(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
56pub(crate) fn later(time: SystemTime, by: Duration) -> SystemTime {
59 [
60 by,
61 Duration::from_secs(100 * 365 * 86_400),
62 Duration::from_secs(365 * 86_400),
63 ]
64 .into_iter()
65 .filter(|step| *step <= by)
66 .find_map(|step| time.checked_add(step))
67 .unwrap_or(time)
68}