From 2a057c1197d70d1d9b31a090c28dd7b929fdb6ae Mon Sep 17 00:00:00 2001 From: Botahamec Date: Mon, 31 Jan 2022 09:42:47 -0500 Subject: Added ordering --- src/datetime.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 65 insertions(+), 3 deletions(-) (limited to 'src/datetime.rs') diff --git a/src/datetime.rs b/src/datetime.rs index c739d46..282a56b 100644 --- a/src/datetime.rs +++ b/src/datetime.rs @@ -1,4 +1,9 @@ -use crate::{timezone::UtcOffset, Date, Month, Time, TimeZone, Year}; +use crate::{ + timezone::{Utc, UtcOffset}, + Date, Month, Time, TimeZone, Year, +}; + +use core::{cmp::Ordering, hash::Hash}; #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct NaiveDateTime { @@ -6,7 +11,7 @@ pub struct NaiveDateTime { time: Time, } -#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] +#[derive(Copy, Clone, Eq, Debug)] pub struct DateTime { utc_datetime: NaiveDateTime, timezone: Tz, @@ -14,6 +19,7 @@ pub struct DateTime { impl DateTime { // TODO unix epoch constant + // TODO docs pub fn from_utc(utc_datetime: NaiveDateTime, timezone: Tz) -> Self { Self { @@ -23,7 +29,8 @@ impl DateTime { } pub fn offset(&self) -> UtcOffset { - self.timezone.utc_offset(self.utc_datetime) + let utc = DateTime::::from_utc(self.utc_datetime, Utc); + self.timezone.utc_offset(utc) } pub fn timezone(&self) -> &Tz { @@ -87,4 +94,59 @@ impl NaiveDateTime { } } +impl PartialOrd for NaiveDateTime { + fn partial_cmp(&self, other: &Self) -> Option { + let date_ordering = self.date.cmp(&other.date); + let time_ordering = self.time.cmp(&other.time); + + if date_ordering != Ordering::Equal { + Some(date_ordering) + } else if time_ordering != Ordering::Equal { + Some(time_ordering) + } else { + Some(Ordering::Equal) + } + } +} + +impl Ord for NaiveDateTime { + fn cmp(&self, other: &Self) -> Ordering { + let date_ordering = self.date.cmp(&other.date); + let time_ordering = self.time.cmp(&other.time); + + if date_ordering != Ordering::Equal { + date_ordering + } else if time_ordering != Ordering::Equal { + time_ordering + } else { + Ordering::Equal + } + } +} + +// TODO think harder about the fact that we don't consider timezone (how will UtcOffset work) +impl PartialEq> for DateTime { + fn eq(&self, other: &DateTime) -> bool { + self.utc_datetime == other.utc_datetime + } +} + +impl Hash for DateTime { + fn hash(&self, state: &mut H) { + self.utc_datetime.hash(state) + } +} + +impl PartialOrd> for DateTime { + fn partial_cmp(&self, other: &DateTime) -> Option { + self.utc_datetime.partial_cmp(&other.utc_datetime) + } +} + +impl Ord for DateTime { + fn cmp(&self, other: &Self) -> Ordering { + self.utc_datetime.cmp(&other.utc_datetime) + } +} + // TODO addition -- cgit v1.2.3