Skip to main content

universal_time/
system.rs

1use core::time::Duration;
2
3/// Wall clock time represented as a duration since the Unix epoch.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
5pub struct SystemTime {
6    since_unix_epoch: Duration,
7}
8
9/// Unix epoch (January 1, 1970).
10pub const UNIX_EPOCH: SystemTime = SystemTime::from_unix_duration(Duration::ZERO);
11
12impl SystemTime {
13    /// Creates a `SystemTime` from a duration since Unix epoch.
14    #[inline]
15    pub const fn from_unix_duration(since_unix_epoch: Duration) -> Self {
16        Self { since_unix_epoch }
17    }
18
19    /// Returns this timestamp as duration since Unix epoch.
20    #[inline]
21    pub const fn as_unix_duration(self) -> Duration {
22        self.since_unix_epoch
23    }
24
25    /// Returns the current system time.
26    #[inline]
27    pub fn now() -> Self {
28        if let Some(context) = crate::global::global_time_context() {
29            if let Some(now) = context.system_time() {
30                return now;
31            }
32        }
33
34        #[cfg(all(
35            feature = "std",
36            not(all(target_family = "wasm", target_os = "unknown"))
37        ))]
38        {
39            let now = std::time::SystemTime::now();
40            let since_unix_epoch = now
41                .duration_since(std::time::UNIX_EPOCH)
42                .unwrap_or(Duration::ZERO);
43            Self::from_unix_duration(since_unix_epoch)
44        }
45
46        #[cfg(any(
47            not(feature = "std"),
48            all(feature = "std", all(target_family = "wasm", target_os = "unknown"))
49        ))]
50        {
51            crate::global::panic_missing_system_time()
52        }
53    }
54
55    /// Returns the duration since another `SystemTime`.
56    pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, Duration> {
57        if self.since_unix_epoch >= earlier.since_unix_epoch {
58            Ok(self.since_unix_epoch - earlier.since_unix_epoch)
59        } else {
60            Err(earlier.since_unix_epoch - self.since_unix_epoch)
61        }
62    }
63}