use crate::{Duration, Error, Instant};
use ::chrono::{DateTime, 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
}