Skip to main content

refix_message/value/
time.rs

1use super::{TimePrecision, number};
2use std::cmp::Ordering;
3use std::hash::{Hash, Hasher};
4
5/// A FIX time of day, as in a UTCTimeOnly or LocalMktTime field, keeping its precision.
6///
7/// Equality and ordering compare the time and ignore the precision.
8#[derive(Clone, Copy, Debug)]
9pub struct Time {
10    nanos_since_midnight: i64,
11    precision: TimePrecision,
12}
13
14impl Time {
15    /// The time `nanos_since_midnight` after midnight, written to `precision`.
16    ///
17    /// `None` past the end of a day, which has 86,401 seconds with a leap second.
18    pub const fn new(nanos_since_midnight: i64, precision: TimePrecision) -> Option<Self> {
19        if matches!(nanos_since_midnight, 0..86_401_000_000_000) {
20            Some(Self {
21                nanos_since_midnight,
22                precision,
23            })
24        } else {
25            None
26        }
27    }
28
29    /// Nanoseconds since midnight.
30    pub const fn nanos_since_midnight(&self) -> i64 {
31        self.nanos_since_midnight
32    }
33
34    /// The precision the value was written to, such as `MILLIS` for `.123`.
35    pub const fn precision(&self) -> TimePrecision {
36        self.precision
37    }
38
39    /// Reads a FIX time such as `14:29:51.123`.
40    ///
41    /// A leap second, `:60`, counts as the first second of the next minute.
42    pub(crate) fn parse(text: &[u8]) -> Option<Self> {
43        let (time, rest) = text.split_at_checked(8)?;
44        if time[2] != b':' || time[5] != b':' {
45            return None;
46        }
47        let hour = number(&time[0..2])?;
48        let minute = number(&time[3..5])?;
49        let second = number(&time[6..8])?;
50        if hour > 23 || minute > 59 || second > 60 {
51            return None;
52        }
53        let (precision, fraction) = match rest {
54            [] => (TimePrecision::SECONDS, 0),
55            [b'.', digits @ ..] if !digits.is_empty() => {
56                let count = u8::try_from(digits.len()).ok()?;
57                let precision = TimePrecision::from_fraction_digits(count)?;
58                (precision, number(digits)?)
59            }
60            _ => return None,
61        };
62        let seconds = hour * 3_600 + minute * 60 + second;
63        Self::new(
64            seconds * 1_000_000_000 + fraction * precision.unit_nanos(),
65            precision,
66        )
67    }
68}
69
70impl PartialEq for Time {
71    fn eq(&self, other: &Self) -> bool {
72        self.nanos_since_midnight == other.nanos_since_midnight
73    }
74}
75
76impl Eq for Time {}
77
78impl Hash for Time {
79    fn hash<H: Hasher>(&self, state: &mut H) {
80        self.nanos_since_midnight.hash(state);
81    }
82}
83
84impl PartialOrd for Time {
85    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
86        Some(self.cmp(other))
87    }
88}
89
90impl Ord for Time {
91    fn cmp(&self, other: &Self) -> Ordering {
92        self.nanos_since_midnight.cmp(&other.nanos_since_midnight)
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    fn parse(text: &str) -> Option<Time> {
101        Time::parse(text.as_bytes())
102    }
103
104    fn parts(text: &str) -> (i64, TimePrecision) {
105        let value = parse(text).unwrap();
106        (value.nanos_since_midnight(), value.precision())
107    }
108
109    mod construction {
110        use super::*;
111
112        #[test]
113        fn keeps_its_parts() {
114            let value = Time::new(52_191_123_000_000, TimePrecision::MILLIS).unwrap();
115            assert_eq!(value.nanos_since_midnight(), 52_191_123_000_000);
116            assert_eq!(value.precision(), TimePrecision::MILLIS);
117        }
118
119        #[test]
120        fn takes_a_day_with_a_leap_second() {
121            assert!(Time::new(0, TimePrecision::NANOS).is_some());
122            assert!(Time::new(86_400_999_999_999, TimePrecision::NANOS).is_some());
123            assert_eq!(Time::new(86_401_000_000_000, TimePrecision::NANOS), None);
124            assert_eq!(Time::new(-1, TimePrecision::NANOS), None);
125        }
126    }
127
128    mod parsing {
129        use super::*;
130
131        #[test]
132        fn reads_whole_seconds() {
133            assert_eq!(
134                parts("14:29:51"),
135                (52_191_000_000_000, TimePrecision::SECONDS)
136            );
137        }
138
139        #[test]
140        fn reads_the_common_precisions() {
141            assert_eq!(
142                parts("14:29:51.123"),
143                (52_191_123_000_000, TimePrecision::MILLIS)
144            );
145            assert_eq!(
146                parts("14:29:51.123456"),
147                (52_191_123_456_000, TimePrecision::MICROS)
148            );
149            assert_eq!(
150                parts("14:29:51.123456789"),
151                (52_191_123_456_789, TimePrecision::NANOS)
152            );
153        }
154
155        #[test]
156        fn reads_any_fraction_up_to_nine_digits() {
157            for (fraction, nanos) in [
158                ("1", 100_000_000),
159                ("1234", 123_400_000),
160                ("1234567", 123_456_700),
161            ] {
162                let (since_midnight, precision) = parts(&format!("14:29:51.{fraction}"));
163                assert_eq!(since_midnight, 52_191_000_000_000 + nanos, "{fraction}");
164                assert_eq!(usize::from(precision.fraction_digits()), fraction.len());
165            }
166        }
167
168        #[test]
169        fn keeps_the_precision_of_a_zero_fraction() {
170            assert_eq!(
171                parts("14:29:51.000"),
172                (52_191_000_000_000, TimePrecision::MILLIS)
173            );
174        }
175
176        #[test]
177        fn reads_the_ends_of_the_day() {
178            assert_eq!(parts("00:00:00").0, 0);
179            assert_eq!(parts("23:59:59.999999999").0, 86_399_999_999_999);
180        }
181
182        #[test]
183        fn reads_a_leap_second_after_the_last_second_of_the_day() {
184            assert_eq!(parts("23:59:60").0, 86_400_000_000_000);
185            assert_eq!(parts("23:59:60.999999999").0, 86_400_999_999_999);
186        }
187
188        #[test]
189        fn rejects_times_out_of_range() {
190            for text in ["24:00:00", "14:60:00", "14:29:61"] {
191                assert_eq!(parse(text), None, "{text:?}");
192            }
193        }
194
195        #[test]
196        fn rejects_an_empty_or_sub_nanosecond_fraction() {
197            for fraction in [".", ".1234567890", ".123456789012"] {
198                let text = format!("14:29:51{fraction}");
199                assert_eq!(parse(&text), None, "{text:?}");
200            }
201        }
202
203        #[test]
204        fn rejects_other_shapes() {
205            for text in [
206                "",
207                "14:29",
208                "14:29:5",
209                "142951",
210                "14.29.51",
211                "14:29:51Z",
212                "14:29:51,123",
213                "14:29:5a",
214                "+4:29:51",
215                "14:29:51.12a",
216                "T14:29:51",
217            ] {
218                assert_eq!(parse(text), None, "{text:?}");
219            }
220        }
221    }
222
223    mod equality {
224        use super::*;
225        use std::hash::DefaultHasher;
226
227        fn hash_of(value: Time) -> u64 {
228            let mut hasher = DefaultHasher::new();
229            value.hash(&mut hasher);
230            hasher.finish()
231        }
232
233        #[test]
234        fn compares_times_across_precisions() {
235            assert_eq!(parse("14:29:51"), parse("14:29:51.000000"));
236            assert_ne!(parse("14:29:51"), parse("14:29:51.001"));
237        }
238
239        #[test]
240        fn equal_times_hash_alike() {
241            assert_eq!(
242                hash_of(Time::new(1_000, TimePrecision::MICROS).unwrap()),
243                hash_of(Time::new(1_000, TimePrecision::NANOS).unwrap())
244            );
245        }
246
247        #[test]
248        fn orders_by_time() {
249            assert!(parse("14:29:51.999") < parse("14:29:52"));
250            assert!(parse("23:59:59.999999999") < parse("23:59:60"));
251        }
252    }
253}