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