1use super::{Error, ErrorCode, MAX_PORTABLE_UNIX_MILLIS, MIN_PORTABLE_UNIX_MILLIS};
10use std::fmt;
11use std::str::FromStr;
12use std::time::{Duration, SystemTime, UNIX_EPOCH};
13
14const MILLIS_PER_DAY: i64 = 86_400_000;
15
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub struct Timestamp(i64);
20
21impl Timestamp {
22 pub const MIN: Timestamp = Timestamp(MIN_PORTABLE_UNIX_MILLIS);
24 pub const MAX: Timestamp = Timestamp(MAX_PORTABLE_UNIX_MILLIS);
26
27 pub const fn from_unix_millis(millis: i64) -> Self {
31 Self(millis)
32 }
33
34 pub const fn unix_millis(self) -> i64 {
36 self.0
37 }
38
39 pub const fn is_portable(self) -> bool {
41 self.0 >= MIN_PORTABLE_UNIX_MILLIS && self.0 <= MAX_PORTABLE_UNIX_MILLIS
42 }
43
44 pub fn from_system_time(time: SystemTime) -> Self {
47 match time.duration_since(UNIX_EPOCH) {
48 Ok(after) => Self(i64::try_from(after.as_millis()).unwrap_or(i64::MAX)),
49 Err(before) => {
50 let before = before.duration();
51 let whole = i64::try_from(before.as_millis()).unwrap_or(i64::MAX);
52 let partial = before > Duration::from_millis(whole.unsigned_abs());
53 Self(whole.saturating_neg().saturating_sub(i64::from(partial)))
54 }
55 }
56 }
57
58 pub fn now() -> Self {
60 Self::from_system_time(SystemTime::now())
61 }
62
63 pub fn to_iso_string(self) -> Result<String, Error> {
67 if !self.is_portable() {
68 return Err(Error::new(
69 ErrorCode::Invalid,
70 "time is outside the portable range",
71 ));
72 }
73 Ok(format_unchecked(self.0))
74 }
75
76 pub fn parse(text: &str) -> Result<Self, Error> {
81 parse(text).ok_or_else(|| {
82 Error::new(
83 ErrorCode::Invalid,
84 format!("{text:?} is not a Date.toISOString() time"),
85 )
86 })
87 }
88}
89
90impl fmt::Display for Timestamp {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 match self.to_iso_string() {
93 Ok(text) => f.write_str(&text),
94 Err(_) => write!(f, "{}ms", self.0),
95 }
96 }
97}
98
99impl FromStr for Timestamp {
100 type Err = Error;
101
102 fn from_str(text: &str) -> Result<Self, Error> {
103 Self::parse(text)
104 }
105}
106
107impl From<SystemTime> for Timestamp {
108 fn from(time: SystemTime) -> Self {
109 Self::from_system_time(time)
110 }
111}
112
113fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
116 let year = if month <= 2 { year - 1 } else { year };
117 let era = year.div_euclid(400);
118 let year_of_era = year - era * 400;
119 let month_index = (month + 9) % 12;
120 let day_of_year = (153 * month_index + 2) / 5 + day - 1;
121 let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
122 era * 146_097 + day_of_era - 719_468
123}
124
125fn civil_from_days(days: i64) -> (i64, i64, i64) {
128 let days = days + 719_468;
129 let era = days.div_euclid(146_097);
130 let day_of_era = days - era * 146_097;
131 let year_of_era =
132 (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
133 let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
134 let month_index = (5 * day_of_year + 2) / 153;
135 let day = day_of_year - (153 * month_index + 2) / 5 + 1;
136 let month = if month_index < 10 {
137 month_index + 3
138 } else {
139 month_index - 9
140 };
141 let year = year_of_era + era * 400 + i64::from(month <= 2);
142 (year, month, day)
143}
144
145fn format_unchecked(millis: i64) -> String {
146 let days = millis.div_euclid(MILLIS_PER_DAY);
147 let of_day = millis.rem_euclid(MILLIS_PER_DAY);
148 let (year, month, day) = civil_from_days(days);
149 let year = if (0..=9999).contains(&year) {
150 format!("{year:04}")
151 } else if year < 0 {
152 format!("-{:06}", -year)
153 } else {
154 format!("+{year:06}")
155 };
156 format!(
157 "{year}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
158 of_day / 3_600_000,
159 of_day / 60_000 % 60,
160 of_day / 1000 % 60,
161 of_day % 1000
162 )
163}
164
165fn parse(text: &str) -> Option<Timestamp> {
166 let bytes = text.as_bytes();
167 let (sign, year_digits) = match bytes.first()? {
168 b'+' => (1, 6),
169 b'-' => (-1, 6),
170 _ => (1, 4),
171 };
172 let year_start = usize::from(year_digits == 6);
173 let rest = year_start + year_digits;
174 if bytes.len() != rest + 20 {
175 return None;
176 }
177 let number = |start: usize, len: usize| -> Option<i64> {
178 let digits = bytes.get(start..start + len)?;
179 digits.iter().try_fold(0i64, |acc, &b| {
180 b.is_ascii_digit().then(|| acc * 10 + i64::from(b - b'0'))
181 })
182 };
183 for (offset, separator) in [
184 (0, b'-'),
185 (3, b'-'),
186 (6, b'T'),
187 (9, b':'),
188 (12, b':'),
189 (15, b'.'),
190 (19, b'Z'),
191 ] {
192 if bytes[rest + offset] != separator {
193 return None;
194 }
195 }
196 let year = sign * number(year_start, year_digits)?;
197 let month = number(rest + 1, 2)?;
198 let day = number(rest + 4, 2)?;
199 let hour = number(rest + 7, 2)?;
200 let minute = number(rest + 10, 2)?;
201 let second = number(rest + 13, 2)?;
202 let milli = number(rest + 16, 3)?;
203 if !(1..=12).contains(&month) || day < 1 || hour > 23 || minute > 59 || second > 59 {
204 return None;
205 }
206 let days = days_from_civil(year, month, day);
207 if civil_from_days(days) != (year, month, day) {
208 return None;
209 }
210 let millis = days * MILLIS_PER_DAY + ((hour * 60 + minute) * 60 + second) * 1000 + milli;
211 (format_unchecked(millis) == text).then_some(Timestamp(millis))
213}
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218
219 #[test]
220 fn formats_like_date_to_iso_string() {
221 for (millis, text) in [
222 (0, "1970-01-01T00:00:00.000Z"),
223 (-1, "1969-12-31T23:59:59.999Z"),
224 (1_788_264_000_000, "2026-09-01T12:00:00.000Z"),
225 (-62_135_596_800_000, "0001-01-01T00:00:00.000Z"),
226 (-62_167_219_200_000, "0000-01-01T00:00:00.000Z"),
227 (-62_198_755_200_000, "-000001-01-01T00:00:00.000Z"),
228 (253_402_300_799_999, "9999-12-31T23:59:59.999Z"),
229 (253_402_300_800_000, "+010000-01-01T00:00:00.000Z"),
230 (MIN_PORTABLE_UNIX_MILLIS, "-271821-04-20T00:00:00.000Z"),
231 (MAX_PORTABLE_UNIX_MILLIS, "+275760-09-13T00:00:00.000Z"),
232 (951_782_400_000, "2000-02-29T00:00:00.000Z"),
233 ] {
234 let time = Timestamp::from_unix_millis(millis);
235 assert_eq!(time.to_iso_string().unwrap(), text);
236 assert_eq!(Timestamp::parse(text).unwrap(), time, "{text}");
237 }
238 }
239
240 #[test]
241 fn rejects_out_of_range_formatting_but_parses_six_digit_years() {
242 let late = Timestamp::from_unix_millis(MAX_PORTABLE_UNIX_MILLIS + 1);
243 assert!(!late.is_portable());
244 assert_eq!(late.to_iso_string().unwrap_err().code(), ErrorCode::Invalid);
245 assert_eq!(
246 Timestamp::parse("+275760-09-13T00:00:00.001Z").unwrap(),
247 late
248 );
249 let early = Timestamp::parse("-271821-04-19T23:59:59.999Z").unwrap();
250 assert_eq!(early.unix_millis(), MIN_PORTABLE_UNIX_MILLIS - 1);
251 assert_eq!(late.to_string(), "8640000000000001ms");
252 }
253
254 #[test]
255 fn parse_accepts_only_the_canonical_form() {
256 for text in [
257 "",
258 "2026-09-01T12:00:00Z",
259 "2026-09-01T12:00:00.000",
260 "2026-09-01T12:00:00.000+00:00",
261 "2026-9-01T12:00:00.000Z",
262 "+002026-09-01T12:00:00.000Z",
263 "-000000-01-01T00:00:00.000Z",
264 "10000-01-01T00:00:00.000Z",
265 "2026-02-30T00:00:00.000Z",
266 "2026-13-01T00:00:00.000Z",
267 "2026-00-01T00:00:00.000Z",
268 "2026-09-01T24:00:00.000Z",
269 "2026-09-01T12:60:00.000Z",
270 "2026-09-01T12:00:60.000Z",
271 "2026-09-01 12:00:00.000Z",
272 "2026-09-01T12:00:00.0a0Z",
273 "2026-09-01T12:00:00.000Z",
274 ] {
275 assert!(Timestamp::parse(text).is_err(), "{text:?}");
276 }
277 }
278
279 #[test]
280 fn system_time_truncates_toward_the_past() {
281 let after = UNIX_EPOCH + Duration::from_micros(1_500);
282 assert_eq!(Timestamp::from(after).unix_millis(), 1);
283 let before = UNIX_EPOCH - Duration::from_micros(1_500);
284 assert_eq!(Timestamp::from(before).unix_millis(), -2);
285 let exact = UNIX_EPOCH - Duration::from_millis(3);
286 assert_eq!(Timestamp::from(exact).unix_millis(), -3);
287 assert!(Timestamp::now().is_portable());
288 }
289
290 #[test]
291 fn day_arithmetic_round_trips_across_the_portable_range() {
292 let first = MIN_PORTABLE_UNIX_MILLIS / MILLIS_PER_DAY;
293 let last = MAX_PORTABLE_UNIX_MILLIS / MILLIS_PER_DAY;
294 let mut day = first;
295 while day <= last {
296 let (year, month, date) = civil_from_days(day);
297 assert_eq!(days_from_civil(year, month, date), day);
298 day += 997;
299 }
300 }
301}