Skip to main content

refix_message/interop/
chrono.rs

1use super::exact_precision;
2use crate::{Date, OutOfRange, Time, UtcTimestamp};
3use chrono_04::{DateTime, Datelike, NaiveDate, NaiveTime, Timelike, Utc};
4
5impl From<Date> for NaiveDate {
6    fn from(date: Date) -> Self {
7        NaiveDate::from_ymd_opt(date.year().into(), date.month().into(), date.day().into())
8            .expect("years 0 to 9999 are within chrono's range")
9    }
10}
11
12impl TryFrom<NaiveDate> for Date {
13    type Error = OutOfRange;
14
15    fn try_from(date: NaiveDate) -> Result<Self, Self::Error> {
16        u16::try_from(date.year())
17            .ok()
18            .and_then(|year| Date::new(year, date.month() as u8, date.day() as u8))
19            .ok_or(OutOfRange)
20    }
21}
22
23impl From<Time> for NaiveTime {
24    /// Keeps a leap second, which chrono holds as `23:59:59` and over a second of nanoseconds.
25    fn from(time: Time) -> Self {
26        let nanos = time.nanos_since_midnight();
27        let seconds = (nanos / 1_000_000_000).min(86_399);
28        let nano = nanos - seconds * 1_000_000_000;
29        NaiveTime::from_num_seconds_from_midnight_opt(seconds as u32, nano as u32)
30            .expect("a leap second follows 23:59:59")
31    }
32}
33
34impl From<NaiveTime> for Time {
35    /// A leap second before 23:59 counts as the first second of the next minute, as in a message.
36    fn from(time: NaiveTime) -> Self {
37        let nanos = i64::from(time.num_seconds_from_midnight()) * 1_000_000_000
38            + i64::from(time.nanosecond());
39        Time::new(nanos, exact_precision(nanos)).expect("a chrono time is within a day")
40    }
41}
42
43impl From<UtcTimestamp> for DateTime<Utc> {
44    fn from(timestamp: UtcTimestamp) -> Self {
45        DateTime::from_timestamp_nanos(timestamp.unix_nanos())
46    }
47}
48
49impl TryFrom<DateTime<Utc>> for UtcTimestamp {
50    type Error = OutOfRange;
51
52    /// A leap second counts as the first second of the next minute, as in a message.
53    fn try_from(timestamp: DateTime<Utc>) -> Result<Self, Self::Error> {
54        let nanos = timestamp.timestamp_nanos_opt().ok_or(OutOfRange)?;
55        Ok(UtcTimestamp::new(nanos, exact_precision(nanos)))
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62    use crate::TimePrecision;
63
64    fn naive_date(year: i32, month: u32, day: u32) -> NaiveDate {
65        NaiveDate::from_ymd_opt(year, month, day).unwrap()
66    }
67
68    fn naive_time(hour: u32, minute: u32, second: u32, nano: u32) -> NaiveTime {
69        NaiveTime::from_hms_nano_opt(hour, minute, second, nano).unwrap()
70    }
71
72    mod date {
73        use super::*;
74
75        #[test]
76        fn converts_to_chrono() {
77            let date = Date::new(2026, 10, 30).unwrap();
78            assert_eq!(NaiveDate::from(date), naive_date(2026, 10, 30));
79        }
80
81        #[test]
82        fn converts_from_chrono() {
83            let date = Date::new(2026, 10, 30).unwrap();
84            assert_eq!(Date::try_from(naive_date(2026, 10, 30)), Ok(date));
85        }
86
87        #[test]
88        fn round_trips_the_first_and_last_fix_years() {
89            for date in [
90                Date::new(0, 1, 1).unwrap(),
91                Date::new(9999, 12, 31).unwrap(),
92            ] {
93                assert_eq!(Date::try_from(NaiveDate::from(date)), Ok(date));
94            }
95        }
96
97        #[test]
98        fn rejects_a_year_before_zero_or_after_9999() {
99            for chrono in [naive_date(-1, 12, 31), naive_date(10_000, 1, 1)] {
100                assert_eq!(Date::try_from(chrono), Err(OutOfRange));
101            }
102        }
103    }
104
105    mod time {
106        use super::*;
107
108        #[test]
109        fn converts_to_chrono() {
110            let time = Time::new(52_191_123_000_000, TimePrecision::MILLIS).unwrap();
111            assert_eq!(NaiveTime::from(time), naive_time(14, 29, 51, 123_000_000));
112        }
113
114        #[test]
115        fn converts_from_chrono() {
116            let time = Time::from(naive_time(14, 29, 51, 123_000_000));
117            assert_eq!(time.nanos_since_midnight(), 52_191_123_000_000);
118            assert_eq!(time.precision(), TimePrecision::MILLIS);
119        }
120
121        #[test]
122        fn round_trips_the_first_and_last_nanoseconds_of_the_day() {
123            for nanos in [0, 86_400_999_999_999] {
124                let time = Time::new(nanos, TimePrecision::NANOS).unwrap();
125                assert_eq!(Time::from(NaiveTime::from(time)), time);
126            }
127        }
128
129        #[test]
130        fn keeps_a_leap_second_at_the_end_of_the_day() {
131            let leap = Time::new(86_400_500_000_000, TimePrecision::MILLIS).unwrap();
132            assert_eq!(NaiveTime::from(leap), naive_time(23, 59, 59, 1_500_000_000));
133        }
134
135        #[test]
136        fn reads_an_earlier_leap_second_as_the_next_minute() {
137            let time = Time::from(naive_time(14, 29, 59, 1_500_000_000));
138            assert_eq!(time.nanos_since_midnight(), 52_200_500_000_000);
139        }
140    }
141
142    mod timestamp {
143        use super::*;
144        use chrono_04::TimeDelta;
145
146        fn date_time(seconds: i64, nanos: u32) -> DateTime<Utc> {
147            DateTime::from_timestamp(seconds, nanos).unwrap()
148        }
149
150        #[test]
151        fn converts_to_chrono() {
152            let timestamp = UtcTimestamp::new(1_791_451_800_123_000_000, TimePrecision::MILLIS);
153            assert_eq!(
154                DateTime::<Utc>::from(timestamp),
155                date_time(1_791_451_800, 123_000_000)
156            );
157        }
158
159        #[test]
160        fn converts_from_chrono() {
161            let timestamp = UtcTimestamp::try_from(date_time(1_791_451_800, 123_000_000)).unwrap();
162            assert_eq!(timestamp.unix_nanos(), 1_791_451_800_123_000_000);
163            assert_eq!(timestamp.precision(), TimePrecision::MILLIS);
164        }
165
166        #[test]
167        fn round_trips_the_ends_of_an_i64() {
168            for nanos in [i64::MIN, i64::MAX] {
169                let timestamp = UtcTimestamp::new(nanos, TimePrecision::NANOS);
170                assert_eq!(
171                    UtcTimestamp::try_from(DateTime::<Utc>::from(timestamp)),
172                    Ok(timestamp)
173                );
174            }
175        }
176
177        #[test]
178        fn rejects_a_timestamp_beyond_an_i64_of_nanoseconds() {
179            let past_the_end = DateTime::from_timestamp_nanos(i64::MAX)
180                .checked_add_signed(TimeDelta::nanoseconds(1))
181                .unwrap();
182            for chrono in [
183                past_the_end,
184                DateTime::<Utc>::MIN_UTC,
185                DateTime::<Utc>::MAX_UTC,
186            ] {
187                assert_eq!(UtcTimestamp::try_from(chrono), Err(OutOfRange));
188            }
189        }
190
191        #[test]
192        fn reads_a_leap_second_as_the_next_day() {
193            let leap = naive_date(2016, 12, 31)
194                .and_hms_nano_opt(23, 59, 59, 1_500_000_000)
195                .unwrap()
196                .and_utc();
197            let timestamp = UtcTimestamp::try_from(leap).unwrap();
198            assert_eq!(timestamp.unix_nanos(), 1_483_228_800_500_000_000);
199        }
200    }
201}