use crate::{Date, Duration, Error, Instant};
use ::chrono::{DateTime, Datelike, TimeDelta, Utc};
impl TryFrom<DateTime<Utc>> for Instant {
type Error = Error;
fn try_from(time: DateTime<Utc>) -> Result<Self, Error> {
let nanoseconds = time.timestamp_subsec_nanos();
if nanoseconds >= 1_000_000_000 {
return Err(Error::data(format!(
"The time {time} is a leap second, which SOML cannot represent"
)));
}
Self::from_unix(time.timestamp(), nanoseconds).ok_or_else(|| {
Error::data(format!("The time {time} is outside the years 0001 to 9999"))
})
}
}
impl From<Instant> for DateTime<Utc> {
fn from(instant: Instant) -> Self {
Self::from_timestamp(instant.unix_seconds(), instant.nanoseconds())
.expect("chrono's range holds every SOML instant")
}
}
impl TryFrom<TimeDelta> for Duration {
type Error = Error;
fn try_from(delta: TimeDelta) -> Result<Self, Error> {
delta
.num_nanoseconds()
.map(Self::from_nanoseconds)
.ok_or_else(|| {
Error::data(format!(
"The duration {delta} is outside the SOML range of about 292 years"
))
})
}
}
impl From<Duration> for TimeDelta {
fn from(duration: Duration) -> Self {
Self::nanoseconds(duration.nanoseconds())
}
}
serde_with_module! {
date_time, ::chrono::DateTime<::chrono::Utc>, crate::Instant
}
serde_with_module! {
time_delta, ::chrono::TimeDelta, crate::Duration
}
impl TryFrom<::chrono::NaiveDate> for Date {
type Error = Error;
fn try_from(date: ::chrono::NaiveDate) -> Result<Self, Error> {
u16::try_from(date.year())
.ok()
.and_then(|year| Self::new(year, date.month() as u8, date.day() as u8))
.ok_or_else(|| {
Error::data(format!("The date {date} is outside the years 0001 to 9999"))
})
}
}
impl From<Date> for ::chrono::NaiveDate {
fn from(date: Date) -> Self {
Self::from_ymd_opt(
i32::from(date.year()),
u32::from(date.month()),
u32::from(date.day()),
)
.expect("the native Gregorian calendar holds every SOML date")
}
}
serde_with_module! {
naive_date, ::chrono::NaiveDate, crate::Date
}