]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/solid/time.rs
Rollup merge of #105443 - compiler-errors:move-more, r=oli-obk
[rust.git] / library / std / src / sys / solid / time.rs
1 use super::{abi, error::expect_success};
2 use crate::{mem::MaybeUninit, time::Duration};
3
4 pub use super::itron::time::Instant;
5
6 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
7 pub struct SystemTime(abi::time_t);
8
9 pub const UNIX_EPOCH: SystemTime = SystemTime(0);
10
11 impl SystemTime {
12     pub fn now() -> SystemTime {
13         let rtc = unsafe {
14             let mut out = MaybeUninit::zeroed();
15             expect_success(abi::SOLID_RTC_ReadTime(out.as_mut_ptr()), &"SOLID_RTC_ReadTime");
16             out.assume_init()
17         };
18         let t = unsafe {
19             libc::mktime(&mut libc::tm {
20                 tm_sec: rtc.tm_sec,
21                 tm_min: rtc.tm_min,
22                 tm_hour: rtc.tm_hour,
23                 tm_mday: rtc.tm_mday,
24                 tm_mon: rtc.tm_mon - 1,
25                 tm_year: rtc.tm_year,
26                 tm_wday: rtc.tm_wday,
27                 tm_yday: 0,
28                 tm_isdst: 0,
29                 tm_gmtoff: 0,
30                 tm_zone: crate::ptr::null_mut(),
31             })
32         };
33         assert_ne!(t, -1, "mktime failed");
34         SystemTime(t)
35     }
36
37     pub(super) fn from_time_t(t: abi::time_t) -> Self {
38         Self(t)
39     }
40
41     pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
42         if self.0 >= other.0 {
43             Ok(Duration::from_secs((self.0 as u64).wrapping_sub(other.0 as u64)))
44         } else {
45             Err(Duration::from_secs((other.0 as u64).wrapping_sub(self.0 as u64)))
46         }
47     }
48
49     pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
50         Some(SystemTime(self.0.checked_add(other.as_secs().try_into().ok()?)?))
51     }
52
53     pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
54         Some(SystemTime(self.0.checked_sub(other.as_secs().try_into().ok()?)?))
55     }
56 }