time/interop/
offsetdatetime_systemtime.rs

1use core::cmp::Ordering;
2use core::ops::Sub;
3use std::time::SystemTime;
4
5use crate::{Duration, OffsetDateTime};
6
7impl Sub<SystemTime> for OffsetDateTime {
8    type Output = Duration;
9
10    /// # Panics
11    ///
12    /// This may panic if an overflow occurs.
13    #[inline]
14    fn sub(self, rhs: SystemTime) -> Self::Output {
15        self - Self::from(rhs)
16    }
17}
18
19impl Sub<OffsetDateTime> for SystemTime {
20    type Output = Duration;
21
22    /// # Panics
23    ///
24    /// This may panic if an overflow occurs.
25    #[inline]
26    fn sub(self, rhs: OffsetDateTime) -> Self::Output {
27        OffsetDateTime::from(self) - rhs
28    }
29}
30
31impl PartialEq<SystemTime> for OffsetDateTime {
32    #[inline]
33    fn eq(&self, rhs: &SystemTime) -> bool {
34        self == &Self::from(*rhs)
35    }
36}
37
38impl PartialEq<OffsetDateTime> for SystemTime {
39    #[inline]
40    fn eq(&self, rhs: &OffsetDateTime) -> bool {
41        &OffsetDateTime::from(*self) == rhs
42    }
43}
44
45impl PartialOrd<SystemTime> for OffsetDateTime {
46    #[inline]
47    fn partial_cmp(&self, other: &SystemTime) -> Option<Ordering> {
48        self.partial_cmp(&Self::from(*other))
49    }
50}
51
52impl PartialOrd<OffsetDateTime> for SystemTime {
53    #[inline]
54    fn partial_cmp(&self, other: &OffsetDateTime) -> Option<Ordering> {
55        OffsetDateTime::from(*self).partial_cmp(other)
56    }
57}
58
59impl From<SystemTime> for OffsetDateTime {
60    #[inline]
61    fn from(system_time: SystemTime) -> Self {
62        match system_time.duration_since(SystemTime::UNIX_EPOCH) {
63            Ok(duration) => Self::UNIX_EPOCH + duration,
64            Err(err) => Self::UNIX_EPOCH - err.duration(),
65        }
66    }
67}
68
69impl From<OffsetDateTime> for SystemTime {
70    #[inline]
71    fn from(datetime: OffsetDateTime) -> Self {
72        let duration = datetime - OffsetDateTime::UNIX_EPOCH;
73
74        if duration.is_zero() {
75            Self::UNIX_EPOCH
76        } else if duration.is_positive() {
77            Self::UNIX_EPOCH + duration.unsigned_abs()
78        } else {
79            debug_assert!(duration.is_negative());
80            Self::UNIX_EPOCH - duration.unsigned_abs()
81        }
82    }
83}