1use core::time::Duration;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
5pub struct SystemTime {
6 since_unix_epoch: Duration,
7}
8
9pub const UNIX_EPOCH: SystemTime = SystemTime::from_unix_duration(Duration::ZERO);
11
12impl SystemTime {
13 #[inline]
15 pub const fn from_unix_duration(since_unix_epoch: Duration) -> Self {
16 Self { since_unix_epoch }
17 }
18
19 #[inline]
21 pub const fn as_unix_duration(self) -> Duration {
22 self.since_unix_epoch
23 }
24
25 #[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 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}