Skip to main content

refix_message/value/
utc_timestamp.rs

1use super::{Date, Time, TimePrecision};
2use std::cmp::Ordering;
3use std::hash::{Hash, Hasher};
4
5const NANOS_PER_DAY: i64 = 86_400_000_000_000;
6
7/// A FIX UTCTimestamp as nanoseconds since the Unix epoch, keeping its precision.
8///
9/// Equality and ordering compare the instant and ignore the precision.
10#[derive(Clone, Copy, Debug)]
11pub struct UtcTimestamp {
12    unix_nanos: i64,
13    precision: TimePrecision,
14}
15
16impl UtcTimestamp {
17    /// The instant `unix_nanos` after the Unix epoch, written to `precision`.
18    pub const fn new(unix_nanos: i64, precision: TimePrecision) -> Self {
19        Self {
20            unix_nanos,
21            precision,
22        }
23    }
24
25    /// Nanoseconds since 1970-01-01 00:00:00 UTC.
26    pub const fn unix_nanos(&self) -> i64 {
27        self.unix_nanos
28    }
29
30    /// The precision the value was written to, such as `MILLIS` for `.123`.
31    pub const fn precision(&self) -> TimePrecision {
32        self.precision
33    }
34
35    /// The same instant at another precision.
36    pub const fn with_precision(self, precision: TimePrecision) -> Self {
37        Self {
38            unix_nanos: self.unix_nanos,
39            precision,
40        }
41    }
42
43    /// The date in UTC.
44    pub fn date(&self) -> Date {
45        Date::from_days_since_epoch(self.unix_nanos.div_euclid(NANOS_PER_DAY))
46            .expect("an i64 of nanoseconds spans only years 1677 to 2262")
47    }
48
49    /// The time of day in UTC, at the timestamp's precision.
50    pub fn time(&self) -> Time {
51        Time::new(self.unix_nanos.rem_euclid(NANOS_PER_DAY), self.precision)
52            .expect("what's left of a day is within a day")
53    }
54
55    /// Reads a FIX timestamp such as `20261030-14:29:51.123`.
56    pub(crate) fn parse(text: &[u8]) -> Option<Self> {
57        let (date, rest) = text.split_at_checked(8)?;
58        let date = Date::parse(date)?;
59        let time = Time::parse(rest.strip_prefix(b"-")?)?;
60        let nanos = i128::from(date.days_since_epoch()) * i128::from(NANOS_PER_DAY)
61            + i128::from(time.nanos_since_midnight());
62        Some(Self::new(i64::try_from(nanos).ok()?, time.precision()))
63    }
64}
65
66impl PartialEq for UtcTimestamp {
67    fn eq(&self, other: &Self) -> bool {
68        self.unix_nanos == other.unix_nanos
69    }
70}
71
72impl Eq for UtcTimestamp {}
73
74impl Hash for UtcTimestamp {
75    fn hash<H: Hasher>(&self, state: &mut H) {
76        self.unix_nanos.hash(state);
77    }
78}
79
80impl PartialOrd for UtcTimestamp {
81    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
82        Some(self.cmp(other))
83    }
84}
85
86impl Ord for UtcTimestamp {
87    fn cmp(&self, other: &Self) -> Ordering {
88        self.unix_nanos.cmp(&other.unix_nanos)
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95
96    fn parse(text: &str) -> Option<UtcTimestamp> {
97        UtcTimestamp::parse(text.as_bytes())
98    }
99
100    fn parts(text: &str) -> (i64, TimePrecision) {
101        let value = parse(text).unwrap();
102        (value.unix_nanos(), value.precision())
103    }
104
105    mod construction {
106        use super::*;
107
108        #[test]
109        fn changes_the_precision_and_keeps_the_instant() {
110            let value = UtcTimestamp::new(1_793_370_591_123_456_789, TimePrecision::NANOS);
111
112            let coarser = value.with_precision(TimePrecision::MILLIS);
113
114            assert_eq!(coarser.precision(), TimePrecision::MILLIS);
115            assert_eq!(coarser.unix_nanos(), 1_793_370_591_123_456_789);
116        }
117    }
118
119    mod parsing {
120        use super::*;
121
122        #[test]
123        fn reads_whole_seconds() {
124            assert_eq!(
125                parts("20261030-14:29:51"),
126                (1_793_370_591_000_000_000, TimePrecision::SECONDS)
127            );
128        }
129
130        #[test]
131        fn reads_the_common_precisions() {
132            assert_eq!(
133                parts("20261030-14:29:51.123"),
134                (1_793_370_591_123_000_000, TimePrecision::MILLIS)
135            );
136            assert_eq!(
137                parts("20261030-14:29:51.123456"),
138                (1_793_370_591_123_456_000, TimePrecision::MICROS)
139            );
140            assert_eq!(
141                parts("20261030-14:29:51.123456789"),
142                (1_793_370_591_123_456_789, TimePrecision::NANOS)
143            );
144        }
145
146        #[test]
147        fn reads_times_around_the_epoch() {
148            assert_eq!(parts("19700101-00:00:00").0, 0);
149            assert_eq!(parts("19691231-23:59:59.999").0, -1_000_000);
150        }
151
152        #[test]
153        fn folds_a_leap_second_into_the_next_day() {
154            assert_eq!(parts("20161231-23:59:60").0, parts("20170101-00:00:00").0);
155        }
156
157        #[test]
158        fn rejects_a_date_that_does_not_exist() {
159            assert_eq!(parse("20230229-00:00:00"), None);
160        }
161
162        #[test]
163        fn rejects_a_time_that_does_not_exist() {
164            assert_eq!(parse("20261030-24:00:00"), None);
165        }
166
167        #[test]
168        fn rejects_other_shapes() {
169            for text in [
170                "",
171                "20261030",
172                "20261030-14:29",
173                "2026-10-30T14:29:51",
174                "20261030T14:29:51",
175                "20261030-14.29.51",
176                "20261030-14:29:51Z",
177                "20261030-14:29:51,123",
178                "20261030-14:29:5a",
179                "+0261030-14:29:51",
180                "20261030-14:29:51.12a",
181            ] {
182                assert_eq!(parse(text), None, "{text:?}");
183            }
184        }
185
186        #[test]
187        fn reads_the_whole_i64_range() {
188            assert_eq!(parts("22620411-23:47:16.854775807").0, i64::MAX);
189            assert_eq!(parts("16770921-00:12:43.145224192").0, i64::MIN);
190        }
191
192        #[test]
193        fn rejects_instants_beyond_i64() {
194            for text in [
195                "22620411-23:47:16.854775808",
196                "16770921-00:12:43.145224191",
197                "99991231-23:59:59",
198                "00000101-00:00:00",
199            ] {
200                assert_eq!(parse(text), None, "{text:?}");
201            }
202        }
203    }
204
205    mod splitting {
206        use super::*;
207
208        fn split(value: UtcTimestamp) -> (Date, i64) {
209            (value.date(), value.time().nanos_since_midnight())
210        }
211
212        fn date(year: u16, month: u8, day: u8) -> Date {
213            Date::new(year, month, day).unwrap()
214        }
215
216        #[test]
217        fn splits_into_date_and_time() {
218            let value = parse("20261030-14:29:51.123").unwrap();
219            assert_eq!(split(value), (date(2026, 10, 30), 52_191_123_000_000));
220        }
221
222        #[test]
223        fn keeps_the_precision() {
224            let value = parse("20261030-14:29:51.123456").unwrap();
225            assert_eq!(value.time().precision(), TimePrecision::MICROS);
226        }
227
228        #[test]
229        fn splits_times_before_the_epoch() {
230            let value = parse("19691231-23:59:59.999").unwrap();
231            assert_eq!(split(value), (date(1969, 12, 31), 86_399_999_000_000));
232        }
233
234        #[test]
235        fn reads_a_leap_second_as_the_next_day() {
236            let value = parse("20161231-23:59:60").unwrap();
237            assert_eq!(split(value), (date(2017, 1, 1), 0));
238        }
239
240        #[test]
241        fn splits_the_ends_of_the_i64_range() {
242            let last = UtcTimestamp::new(i64::MAX, TimePrecision::NANOS);
243            assert_eq!(split(last), (date(2262, 4, 11), 85_636_854_775_807));
244            let first = UtcTimestamp::new(i64::MIN, TimePrecision::NANOS);
245            assert_eq!(split(first), (date(1677, 9, 21), 763_145_224_192));
246        }
247    }
248
249    mod equality {
250        use super::*;
251        use std::hash::DefaultHasher;
252
253        fn hash_of(value: UtcTimestamp) -> u64 {
254            let mut hasher = DefaultHasher::new();
255            value.hash(&mut hasher);
256            hasher.finish()
257        }
258
259        #[test]
260        fn compares_instants_across_precisions() {
261            assert_eq!(
262                parse("20261030-14:29:51"),
263                parse("20261030-14:29:51.000000")
264            );
265            assert_ne!(parse("20261030-14:29:51"), parse("20261030-14:29:51.001"));
266        }
267
268        #[test]
269        fn equal_instants_hash_alike() {
270            assert_eq!(
271                hash_of(UtcTimestamp::new(1_000, TimePrecision::MICROS)),
272                hash_of(UtcTimestamp::new(1_000, TimePrecision::NANOS))
273            );
274        }
275
276        #[test]
277        fn orders_by_instant() {
278            assert!(
279                UtcTimestamp::new(1, TimePrecision::NANOS)
280                    < UtcTimestamp::new(1_000_000_000, TimePrecision::SECONDS)
281            );
282        }
283    }
284}