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