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