diff options
| author | Joe Carstairs <me@joeac.net> | 2024-11-17 09:29:32 +0000 |
|---|---|---|
| committer | Joe Carstairs <me@joeac.net> | 2024-11-17 09:30:04 +0000 |
| commit | 10f071447594f2bdcec84a461df9ad648f71f44b (patch) | |
| tree | 645924a4948f39a4d9e2ec270d79fc6c2a3a937a /rust/schist_core/src/models/datetime_utc.rs | |
| parent | 1ae19eb3315c40e3f9062592c27fa76c11cf626c (diff) | |
Renames app to 'schist'
Diffstat (limited to 'rust/schist_core/src/models/datetime_utc.rs')
| -rw-r--r-- | rust/schist_core/src/models/datetime_utc.rs | 223 |
1 files changed, 223 insertions, 0 deletions
diff --git a/rust/schist_core/src/models/datetime_utc.rs b/rust/schist_core/src/models/datetime_utc.rs new file mode 100644 index 0000000..98d1d6c --- /dev/null +++ b/rust/schist_core/src/models/datetime_utc.rs @@ -0,0 +1,223 @@ +use std::{fmt::Display, str::FromStr}; + +use anyhow::{Context, Result}; +use chrono::{DateTime, Datelike as ChronoDatelike, NaiveDate, Timelike as ChronoTimelike, Utc}; +use diesel::{ + backend::Backend, + deserialize::{self, FromSql, FromSqlRow}, + expression::AsExpression, + serialize::{self, ToSql}, + sql_types::Text, + sqlite::Sqlite, +}; +use serde::{Deserialize, Serialize}; + +use crate::traits::{dateable::Dateable, nowlike::Nowlike, timeable::Timeable}; + +#[derive( + PartialEq, + Eq, + PartialOrd, + Ord, + Serialize, + Deserialize, + Clone, + Debug, + AsExpression, + FromSqlRow, +)] +#[diesel(sql_type=Text)] +pub struct DatetimeUtc { + chrono_datetime_utc: DateTime<Utc>, +} + +impl DatetimeUtc { + pub fn from_ymd_and_hms(year: i32, month: u32, day: u32, hour: u32, min: u32, sec: u32) -> Result<Self> { + Ok(Self { chrono_datetime_utc: NaiveDate + ::from_ymd_opt(year, month, day) + .with_context(|| format!("failed to construct datetime from ymd {:04}-{:02}-{:02}", year, month, day))? + .and_hms_opt(hour, min, sec) + .with_context(|| format!("failed to construct datetime from hms {:02}:{:02}:{:02}", hour, min, sec))? + .and_utc() + }) + } +} + +impl FromStr for DatetimeUtc { + type Err = anyhow::Error; + + /// Constructs DatetimeUtc from a date string in ISO format, in UTC + /// Example: "2024-10-24T10:30:00.000" -> 10.30am 24 Oct 2024 UTC + fn from_str(datetime_str: &str) -> Result<Self> { + let chrono_datetime_utc = datetime_str.parse::<DateTime<Utc>>()?; + Ok(Self { + chrono_datetime_utc, + }) + } +} + +impl Display for DatetimeUtc { + /// Converts to a date string in ISO format, in UTC + /// Example: 10.30am 24 Oct 2024 UTC -> "2024-10-24T10:30:00.000Z" + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "{}", self.chrono_datetime_utc.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)) + } +} + +impl Nowlike for DatetimeUtc { + fn now() -> Self { + let now = Utc::now(); + Self::from_ymd_and_hms( + now.year(), + now.month(), + now.day(), + now.hour(), + now.minute(), + now.second(), + ).unwrap() + } +} + +impl Dateable for DatetimeUtc { + fn year(&self) -> i32 { + self.chrono_datetime_utc.year() + } + + fn month(&self) -> u32 { + self.chrono_datetime_utc.month() + } + + fn day(&self) -> u32 { + self.chrono_datetime_utc.day() + } +} + +impl Timeable for DatetimeUtc { + fn hour(&self) -> u32 { + self.chrono_datetime_utc.hour() + } + + fn minute(&self) -> u32 { + self.chrono_datetime_utc.minute() + } + + fn second(&self) -> u32 { + self.chrono_datetime_utc.second() + } +} + +impl ToSql<Text, Sqlite> for DatetimeUtc { + fn to_sql<'b>( + &'b self, + out: &mut diesel::serialize::Output<'b, '_, Sqlite>, + ) -> serialize::Result { + out.set_value::<String>(self.to_string()); + Ok(serialize::IsNull::No) + } +} + +impl FromSql<Text, Sqlite> for DatetimeUtc { + fn from_sql(bytes: <Sqlite as Backend>::RawValue<'_>) -> deserialize::Result<DatetimeUtc> { + let str = <String as FromSql<Text, Sqlite>>::from_sql(bytes)?; + Ok(str.parse()?) + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn when_from_ymd_and_hms_then_ymd_and_hms_are_as_expected() { + let datetime_utc = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 12, 55, 16); + + assert!(datetime_utc.is_ok()); + let date_utc = datetime_utc.unwrap(); + assert_eq!(date_utc.year(), 1970); + assert_eq!(date_utc.month(), 11); + assert_eq!(date_utc.day(), 23); + assert_eq!(date_utc.hour(), 12); + assert_eq!(date_utc.minute(), 55); + assert_eq!(date_utc.second(), 16); + } + + #[test] + fn when_from_ymd_and_hms_then_to_string_as_expected() { + let date_utc = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 12, 55, 16); + + assert!(date_utc.is_ok()); + assert_eq!(date_utc.unwrap().to_string(), "1970-11-23T12:55:16.000Z") + } + + #[test] + fn when_with_invalid_ymd_and_hms_then_err() { + let datetime_utc_1 = DatetimeUtc::from_ymd_and_hms(1970, 0, 23, 12, 55, 16); + let datetime_utc_2 = DatetimeUtc::from_ymd_and_hms(1970, 13, 23, 12, 55, 16); + let datetime_utc_3 = DatetimeUtc::from_ymd_and_hms(1970, 11, 0, 12, 55, 16); + let datetime_utc_4 = DatetimeUtc::from_ymd_and_hms(1970, 11, 31, 12, 55, 16); + let datetime_utc_5 = DatetimeUtc::from_ymd_and_hms(1971, 2, 29, 12, 55, 16); + let datetime_utc_6 = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 25, 0, 0); + let datetime_utc_7 = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 0, 61, 0); + let datetime_utc_8 = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 0, 0, 61); + + assert!(datetime_utc_1.is_err()); + assert_eq!(datetime_utc_1.unwrap_err().to_string(), "failed to construct datetime from ymd 1970-00-23"); + assert!(datetime_utc_2.is_err()); + assert_eq!(datetime_utc_2.unwrap_err().to_string(), "failed to construct datetime from ymd 1970-13-23"); + assert!(datetime_utc_3.is_err()); + assert_eq!(datetime_utc_3.unwrap_err().to_string(), "failed to construct datetime from ymd 1970-11-00"); + assert!(datetime_utc_4.is_err()); + assert_eq!(datetime_utc_4.unwrap_err().to_string(), "failed to construct datetime from ymd 1970-11-31"); + assert!(datetime_utc_5.is_err()); + assert_eq!(datetime_utc_5.unwrap_err().to_string(), "failed to construct datetime from ymd 1971-02-29"); + assert!(datetime_utc_6.is_err()); + assert_eq!(datetime_utc_6.unwrap_err().to_string(), "failed to construct datetime from hms 25:00:00"); + assert!(datetime_utc_7.is_err()); + assert_eq!(datetime_utc_7.unwrap_err().to_string(), "failed to construct datetime from hms 00:61:00"); + assert!(datetime_utc_8.is_err()); + assert_eq!(datetime_utc_8.unwrap_err().to_string(), "failed to construct datetime from hms 00:00:61"); + } + + #[test] + fn when_from_string_then_ymd_and_hms_are_as_expected() { + let date_utc: Result<DatetimeUtc> = "1970-11-23T12:55:16.000Z".parse(); + + assert!(date_utc.is_ok()); + let datetime_utc = date_utc.unwrap(); + assert_eq!(datetime_utc.year(), 1970); + assert_eq!(datetime_utc.month(), 11); + assert_eq!(datetime_utc.day(), 23); + assert_eq!(datetime_utc.hour(), 12); + assert_eq!(datetime_utc.minute(), 55); + assert_eq!(datetime_utc.second(), 16); + } + + #[test] + fn when_from_string_then_to_string_as_expected() { + let datetime_utc: Result<DatetimeUtc> = "1970-11-23T12:55:16.000Z".parse(); + + assert!(datetime_utc.is_ok()); + assert_eq!(datetime_utc.unwrap().to_string(), "1970-11-23T12:55:16.000Z") + } + + #[test] + fn when_from_invalid_string_then_err() { + let datetime_utc_1: Result<DatetimeUtc> = "1970-00-23T00:00:00.000Z".parse(); + let datetime_utc_2: Result<DatetimeUtc> = "1970-13-23T00:00:00.000Z".parse(); + let datetime_utc_3: Result<DatetimeUtc> = "1970-11-0T00:00:00.000Z".parse(); + let datetime_utc_4: Result<DatetimeUtc> = "1970-11-31T00:00:00.000Z".parse(); + let datetime_utc_5: Result<DatetimeUtc> = "1971-02-29T00:00:00.000Z".parse(); + let datetime_utc_6: Result<DatetimeUtc> = "1970-11-23T25:00:00.000Z".parse(); + let datetime_utc_7: Result<DatetimeUtc> = "1970-11-23T00:61:00.000Z".parse(); + let datetime_utc_8: Result<DatetimeUtc> = "1970-11-23T00:00:61.000Z".parse(); + + assert!(datetime_utc_1.is_err()); + assert!(datetime_utc_2.is_err()); + assert!(datetime_utc_3.is_err()); + assert!(datetime_utc_4.is_err()); + assert!(datetime_utc_5.is_err()); + assert!(datetime_utc_6.is_err()); + assert!(datetime_utc_7.is_err()); + assert!(datetime_utc_8.is_err()); + } +} |
