cap_primitives/time/
system_clock.rs

1use crate::time::{Duration, SystemTime, SystemTimeError};
2use ambient_authority::AmbientAuthority;
3use std::time;
4
5/// A reference to a system clock, useful for talking to external entities like
6/// the file system or other processes.
7///
8/// This does not directly correspond to anything in `std`, however its methods
9/// correspond to [methods in `std::time::SystemTime`].
10///
11/// [methods in `std::time::SystemTime`]: https://doc.rust-lang.org/std/time/struct.SystemTime.html#impl
12pub struct SystemClock(());
13
14impl SystemClock {
15    /// An anchor in time which can be used to create new `SystemTime`
16    /// instances or learn about where in time a `SystemTime` lies.
17    ///
18    /// This corresponds to [`std::time::SystemTime::UNIX_EPOCH`].
19    pub const UNIX_EPOCH: SystemTime = SystemTime {
20        std: time::SystemTime::UNIX_EPOCH,
21    };
22
23    /// Constructs a new instance of `Self`.
24    ///
25    /// # Ambient Authority
26    ///
27    /// This uses ambient authority to accesses clocks.
28    #[inline]
29    pub const fn new(ambient_authority: AmbientAuthority) -> Self {
30        let _ = ambient_authority;
31        Self(())
32    }
33
34    /// Returns an instant corresponding to "now".
35    ///
36    /// This corresponds to [`std::time::SystemTime::now`].
37    #[inline]
38    pub fn now(&self) -> SystemTime {
39        SystemTime::from_std(time::SystemTime::now())
40    }
41
42    /// Returns the amount of time elapsed since this instant was created.
43    ///
44    /// This corresponds to [`std::time::SystemTime::elapsed`].
45    #[inline]
46    pub fn elapsed(&self, system_time: SystemTime) -> Result<Duration, SystemTimeError> {
47        system_time.std.elapsed()
48    }
49}