1use crate::{Date, Duration, Error, Instant};
22use ::chrono::{DateTime, Datelike, TimeDelta, Utc};
23
24impl TryFrom<DateTime<Utc>> for Instant {
25 type Error = Error;
26
27 fn try_from(time: DateTime<Utc>) -> Result<Self, Error> {
31 let nanoseconds = time.timestamp_subsec_nanos();
33 if nanoseconds >= 1_000_000_000 {
34 return Err(Error::data(format!(
35 "The time {time} is a leap second, which SOML cannot represent"
36 )));
37 }
38
39 Self::from_unix(time.timestamp(), nanoseconds).ok_or_else(|| {
41 Error::data(format!("The time {time} is outside the years 0001 to 9999"))
42 })
43 }
44}
45
46impl From<Instant> for DateTime<Utc> {
47 fn from(instant: Instant) -> Self {
48 Self::from_timestamp(instant.unix_seconds(), instant.nanoseconds())
49 .expect("chrono's range holds every SOML instant")
50 }
51}
52
53impl TryFrom<TimeDelta> for Duration {
54 type Error = Error;
55
56 fn try_from(delta: TimeDelta) -> Result<Self, Error> {
60 delta
61 .num_nanoseconds()
62 .map(Self::from_nanoseconds)
63 .ok_or_else(|| {
64 Error::data(format!(
65 "The duration {delta} is outside the SOML range of about 292 years"
66 ))
67 })
68 }
69}
70
71impl From<Duration> for TimeDelta {
72 fn from(duration: Duration) -> Self {
73 Self::nanoseconds(duration.nanoseconds())
74 }
75}
76
77serde_with_module! {
78 date_time, ::chrono::DateTime<::chrono::Utc>, crate::Instant
82}
83
84serde_with_module! {
85 time_delta, ::chrono::TimeDelta, crate::Duration
89}
90
91impl TryFrom<::chrono::NaiveDate> for Date {
92 type Error = Error;
93
94 fn try_from(date: ::chrono::NaiveDate) -> Result<Self, Error> {
98 u16::try_from(date.year())
99 .ok()
100 .and_then(|year| Self::new(year, date.month() as u8, date.day() as u8))
101 .ok_or_else(|| {
102 Error::data(format!("The date {date} is outside the years 0001 to 9999"))
103 })
104 }
105}
106
107impl From<Date> for ::chrono::NaiveDate {
108 fn from(date: Date) -> Self {
109 Self::from_ymd_opt(
110 i32::from(date.year()),
111 u32::from(date.month()),
112 u32::from(date.day()),
113 )
114 .expect("the native Gregorian calendar holds every SOML date")
115 }
116}
117
118serde_with_module! {
119 naive_date, ::chrono::NaiveDate, crate::Date
123}