1use std::{
7 fmt,
8 ops::Range,
9 str::FromStr,
10 time::{Duration, SystemTime, UNIX_EPOCH},
11};
12
13use chrono::{DateTime, Datelike, NaiveDate, Timelike, Utc};
14use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
15use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
16use thiserror::Error;
17
18use crate::decimal::{UnsignedDecimalError, parse_bounded_u64};
19
20const TIMESTAMP_LEN: usize = 27;
21const TIMESTAMP_PATTERN: &str =
22 "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{6}Z$";
23const DURATION_MILLIS_PATTERN: &str = "^(0|[1-9][0-9]{0,18})$";
24const MICROS_PER_SECOND: i128 = 1_000_000;
25
26#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
32pub struct Timestamp(i64);
33
34impl Timestamp {
35 pub const MIN: Self = Self(-62_167_219_200_000_000);
37
38 pub const MAX: Self = Self(253_402_300_799_999_999);
40
41 pub const fn from_unix_micros(value: i64) -> Result<Self, TimestampError> {
48 if value < Self::MIN.0 || value > Self::MAX.0 {
49 return Err(TimestampError::OutOfRange);
50 }
51 Ok(Self(value))
52 }
53
54 #[must_use]
56 pub const fn unix_micros(self) -> i64 {
57 self.0
58 }
59
60 pub fn to_system_time(self) -> Result<SystemTime, TimestampError> {
67 if self.0 >= 0 {
68 UNIX_EPOCH
69 .checked_add(Duration::from_micros(self.0.unsigned_abs()))
70 .ok_or(TimestampError::SystemTimeOutOfRange)
71 } else {
72 UNIX_EPOCH
73 .checked_sub(Duration::from_micros(self.0.unsigned_abs()))
74 .ok_or(TimestampError::SystemTimeOutOfRange)
75 }
76 }
77}
78
79impl fmt::Debug for Timestamp {
80 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
81 formatter
82 .debug_tuple("Timestamp")
83 .field(&format_args!("{self}"))
84 .finish()
85 }
86}
87
88impl fmt::Display for Timestamp {
89 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
90 let date_time = DateTime::<Utc>::from_timestamp_micros(self.0).ok_or(fmt::Error)?;
91 write!(
92 formatter,
93 "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:06}Z",
94 date_time.year(),
95 date_time.month(),
96 date_time.day(),
97 date_time.hour(),
98 date_time.minute(),
99 date_time.second(),
100 date_time.nanosecond() / 1_000,
101 )
102 }
103}
104
105impl FromStr for Timestamp {
106 type Err = TimestampError;
107
108 fn from_str(value: &str) -> Result<Self, Self::Err> {
109 if value.len() != TIMESTAMP_LEN {
110 return Err(TimestampError::InvalidLength {
111 expected: TIMESTAMP_LEN,
112 actual: value.len(),
113 });
114 }
115 let bytes = value.as_bytes();
116 if bytes[4] != b'-'
117 || bytes[7] != b'-'
118 || bytes[10] != b'T'
119 || bytes[13] != b':'
120 || bytes[16] != b':'
121 || bytes[19] != b'.'
122 || bytes[26] != b'Z'
123 {
124 return Err(TimestampError::InvalidFormat);
125 }
126
127 let year =
128 i32::try_from(parse_decimal(bytes, 0..4)?).map_err(|_| TimestampError::InvalidValue)?;
129 let month = parse_decimal(bytes, 5..7)?;
130 let day = parse_decimal(bytes, 8..10)?;
131 let hour = parse_decimal(bytes, 11..13)?;
132 let minute = parse_decimal(bytes, 14..16)?;
133 let second = parse_decimal(bytes, 17..19)?;
134 let microsecond = parse_decimal(bytes, 20..26)?;
135
136 let date = NaiveDate::from_ymd_opt(year, month, day).ok_or(TimestampError::InvalidValue)?;
137 let date_time = date
138 .and_hms_micro_opt(hour, minute, second, microsecond)
139 .ok_or(TimestampError::InvalidValue)?;
140 let unix_micros = date_time.and_utc().timestamp_micros();
141 Self::from_unix_micros(unix_micros)
142 }
143}
144
145impl TryFrom<SystemTime> for Timestamp {
146 type Error = TimestampError;
147
148 fn try_from(value: SystemTime) -> Result<Self, Self::Error> {
149 match value.duration_since(UNIX_EPOCH) {
150 Ok(duration) => timestamp_from_duration(duration, false),
151 Err(error) => timestamp_from_duration(error.duration(), true),
152 }
153 }
154}
155
156impl TryFrom<Timestamp> for SystemTime {
157 type Error = TimestampError;
158
159 fn try_from(value: Timestamp) -> Result<Self, Self::Error> {
160 value.to_system_time()
161 }
162}
163
164impl Serialize for Timestamp {
165 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
166 where
167 S: Serializer,
168 {
169 serializer.collect_str(self)
170 }
171}
172
173impl<'de> Deserialize<'de> for Timestamp {
174 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
175 where
176 D: Deserializer<'de>,
177 {
178 deserializer.deserialize_str(TimestampVisitor)
179 }
180}
181
182impl JsonSchema for Timestamp {
183 fn schema_name() -> std::borrow::Cow<'static, str> {
184 "Timestamp".into()
185 }
186
187 fn schema_id() -> std::borrow::Cow<'static, str> {
188 concat!(module_path!(), "::Timestamp").into()
189 }
190
191 fn json_schema(_: &mut SchemaGenerator) -> Schema {
192 json_schema!({
193 "type": "string",
194 "format": "date-time",
195 "minLength": 27,
196 "maxLength": 27,
197 "pattern": TIMESTAMP_PATTERN
198 })
199 }
200
201 fn inline_schema() -> bool {
202 true
203 }
204}
205
206#[derive(Clone, Debug, Eq, Error, PartialEq)]
208#[non_exhaustive]
209pub enum TimestampError {
210 #[error("timestamp is {actual} bytes; expected {expected}")]
212 InvalidLength {
213 expected: usize,
215 actual: usize,
217 },
218
219 #[error("timestamp must use canonical UTC text")]
221 InvalidFormat,
222
223 #[error("timestamp contains an invalid calendar or clock value")]
225 InvalidValue,
226
227 #[error("timestamp is outside the supported range")]
229 OutOfRange,
230
231 #[error("timestamp contains sub-microsecond precision")]
233 SubmicrosecondPrecision,
234
235 #[error("timestamp cannot be represented by SystemTime on this platform")]
237 SystemTimeOutOfRange,
238}
239
240struct TimestampVisitor;
241
242impl de::Visitor<'_> for TimestampVisitor {
243 type Value = Timestamp;
244
245 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
246 formatter.write_str("a canonical UTC timestamp with six fractional digits")
247 }
248
249 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
250 where
251 E: de::Error,
252 {
253 value.parse().map_err(E::custom)
254 }
255}
256
257fn parse_decimal(bytes: &[u8], range: Range<usize>) -> Result<u32, TimestampError> {
258 bytes[range]
259 .iter()
260 .try_fold(0_u32, |value, byte| {
261 byte.is_ascii_digit()
262 .then_some(value * 10 + u32::from(*byte - b'0'))
263 })
264 .ok_or(TimestampError::InvalidFormat)
265}
266
267fn timestamp_from_duration(
268 duration: Duration,
269 before_epoch: bool,
270) -> Result<Timestamp, TimestampError> {
271 if duration.subsec_nanos() % 1_000 != 0 {
272 return Err(TimestampError::SubmicrosecondPrecision);
273 }
274 let magnitude =
275 i128::from(duration.as_secs()) * MICROS_PER_SECOND + i128::from(duration.subsec_micros());
276 let value = if before_epoch { -magnitude } else { magnitude };
277 let value = i64::try_from(value).map_err(|_| TimestampError::OutOfRange)?;
278 Timestamp::from_unix_micros(value)
279}
280
281#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
287pub struct DurationMillis(i64);
288
289impl DurationMillis {
290 pub const ZERO: Self = Self(0);
292
293 pub const MAX: Self = Self(i64::MAX);
295
296 pub const fn new(milliseconds: i64) -> Result<Self, DurationMillisError> {
302 if milliseconds < 0 {
303 return Err(DurationMillisError::Negative { milliseconds });
304 }
305 Ok(Self(milliseconds))
306 }
307
308 #[must_use]
310 pub const fn as_i64(self) -> i64 {
311 self.0
312 }
313
314 #[must_use]
316 pub const fn checked_add(self, other: Self) -> Option<Self> {
317 match self.0.checked_add(other.0) {
318 Some(value) => Some(Self(value)),
319 None => None,
320 }
321 }
322
323 #[must_use]
325 pub const fn checked_sub(self, other: Self) -> Option<Self> {
326 match self.0.checked_sub(other.0) {
327 Some(value) if value >= 0 => Some(Self(value)),
328 _ => None,
329 }
330 }
331}
332
333impl TryFrom<i64> for DurationMillis {
334 type Error = DurationMillisError;
335
336 fn try_from(value: i64) -> Result<Self, Self::Error> {
337 Self::new(value)
338 }
339}
340
341impl fmt::Display for DurationMillis {
342 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
343 self.0.fmt(formatter)
344 }
345}
346
347impl FromStr for DurationMillis {
348 type Err = DurationMillisError;
349
350 fn from_str(value: &str) -> Result<Self, Self::Err> {
351 let parsed = parse_bounded_u64(value, i64::MAX.unsigned_abs())
352 .map_err(DurationMillisError::from_decimal_error)?;
353 let milliseconds = i64::try_from(parsed).map_err(|_| DurationMillisError::TooLarge)?;
354 Ok(Self(milliseconds))
355 }
356}
357
358impl TryFrom<u64> for DurationMillis {
359 type Error = DurationMillisError;
360
361 fn try_from(value: u64) -> Result<Self, Self::Error> {
362 let value = i64::try_from(value).map_err(|_| DurationMillisError::TooLarge)?;
363 Ok(Self(value))
364 }
365}
366
367impl TryFrom<Duration> for DurationMillis {
368 type Error = DurationMillisError;
369
370 fn try_from(value: Duration) -> Result<Self, Self::Error> {
371 if value.subsec_nanos() % 1_000_000 != 0 {
372 return Err(DurationMillisError::SubmillisecondPrecision);
373 }
374 let milliseconds =
375 i64::try_from(value.as_millis()).map_err(|_| DurationMillisError::TooLarge)?;
376 Ok(Self(milliseconds))
377 }
378}
379
380impl From<DurationMillis> for i64 {
381 fn from(value: DurationMillis) -> Self {
382 value.0
383 }
384}
385
386impl From<DurationMillis> for Duration {
387 fn from(value: DurationMillis) -> Self {
388 Self::from_millis(value.0.unsigned_abs())
389 }
390}
391
392impl Serialize for DurationMillis {
393 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
394 where
395 S: Serializer,
396 {
397 serializer.collect_str(self)
398 }
399}
400
401impl<'de> Deserialize<'de> for DurationMillis {
402 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
403 where
404 D: Deserializer<'de>,
405 {
406 deserializer.deserialize_str(DurationMillisVisitor)
407 }
408}
409
410impl JsonSchema for DurationMillis {
411 fn schema_name() -> std::borrow::Cow<'static, str> {
412 "DurationMillis".into()
413 }
414
415 fn schema_id() -> std::borrow::Cow<'static, str> {
416 concat!(module_path!(), "::DurationMillis").into()
417 }
418
419 fn json_schema(_: &mut SchemaGenerator) -> Schema {
420 json_schema!({
421 "type": "string",
422 "minLength": 1,
423 "maxLength": 19,
424 "pattern": DURATION_MILLIS_PATTERN
425 })
426 }
427
428 fn inline_schema() -> bool {
429 true
430 }
431}
432
433#[derive(Clone, Debug, Eq, Error, PartialEq)]
435#[non_exhaustive]
436pub enum DurationMillisError {
437 #[error("duration must not be negative")]
439 Negative {
440 milliseconds: i64,
442 },
443
444 #[error("duration must contain only unsigned ASCII decimal digits")]
446 InvalidFormat,
447
448 #[error("duration contains a leading zero")]
450 NonCanonical,
451
452 #[error("duration exceeds the supported millisecond range")]
454 TooLarge,
455
456 #[error("duration contains sub-millisecond precision")]
458 SubmillisecondPrecision,
459}
460
461impl DurationMillisError {
462 fn from_decimal_error(error: UnsignedDecimalError) -> Self {
463 match error {
464 UnsignedDecimalError::Empty | UnsignedDecimalError::InvalidCharacter { .. } => {
465 Self::InvalidFormat
466 }
467 UnsignedDecimalError::LeadingZero => Self::NonCanonical,
468 UnsignedDecimalError::TooLong { .. } | UnsignedDecimalError::Overflow => Self::TooLarge,
469 }
470 }
471}
472
473struct DurationMillisVisitor;
474
475impl de::Visitor<'_> for DurationMillisVisitor {
476 type Value = DurationMillis;
477
478 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
479 formatter.write_str("a canonical decimal string containing non-negative milliseconds")
480 }
481
482 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
483 where
484 E: de::Error,
485 {
486 value.parse().map_err(E::custom)
487 }
488}
489
490#[cfg(test)]
491mod tests {
492 use super::*;
493 use serde_json::{Value, from_str, from_value, to_string, to_value};
494
495 #[test]
496 fn timestamps_round_trip_canonical_boundaries() {
497 for (text, micros) in [
498 ("0000-01-01T00:00:00.000000Z", Timestamp::MIN.0),
499 ("1969-12-31T23:59:59.999999Z", -1),
500 ("1970-01-01T00:00:00.000000Z", 0),
501 ("2000-02-29T12:34:56.123456Z", 951_827_696_123_456),
502 ("9999-12-31T23:59:59.999999Z", Timestamp::MAX.0),
503 ] {
504 let timestamp = text.parse::<Timestamp>().unwrap();
505 assert_eq!(timestamp.unix_micros(), micros);
506 assert_eq!(timestamp.to_string(), text);
507 assert_eq!(Timestamp::from_unix_micros(micros).unwrap(), timestamp);
508 }
509 }
510
511 #[test]
512 fn timestamps_reject_noncanonical_or_invalid_values() {
513 for value in [
514 "1970-01-01T00:00:00Z",
515 "1970-01-01T00:00:00.000Z",
516 "1970-01-01t00:00:00.000000Z",
517 "1970-01-01T00:00:00.000000z",
518 "1970-01-01T00:00:00.000000+00:00",
519 "2025-02-29T00:00:00.000000Z",
520 "2024-13-01T00:00:00.000000Z",
521 "2024-01-01T24:00:00.000000Z",
522 "2024-01-01T23:60:00.000000Z",
523 "2024-01-01T23:59:60.000000Z",
524 "٢٠٢٤-01-01T00:00:00.000000Z",
525 ] {
526 assert!(value.parse::<Timestamp>().is_err(), "accepted {value:?}");
527 }
528
529 assert_eq!(
530 Timestamp::from_unix_micros(Timestamp::MIN.0 - 1),
531 Err(TimestampError::OutOfRange)
532 );
533 assert_eq!(
534 Timestamp::from_unix_micros(Timestamp::MAX.0 + 1),
535 Err(TimestampError::OutOfRange)
536 );
537 }
538
539 #[test]
540 fn timestamp_system_time_conversion_is_exact() {
541 for micros in [-1_i64, 0, 1, 1_234_567] {
542 let timestamp = Timestamp::from_unix_micros(micros).unwrap();
543 let system_time = timestamp.to_system_time().unwrap();
544 assert_eq!(Timestamp::try_from(system_time).unwrap(), timestamp);
545 }
546
547 let submicrosecond = UNIX_EPOCH.checked_add(Duration::from_nanos(100)).unwrap();
550 assert_eq!(
551 Timestamp::try_from(submicrosecond),
552 Err(TimestampError::SubmicrosecondPrecision)
553 );
554 }
555
556 #[test]
557 fn timestamp_serde_and_schema_enforce_the_wire_contract() {
558 let timestamp = Timestamp::from_unix_micros(0).unwrap();
559 let encoded = to_string(×tamp).unwrap();
560 assert_eq!(encoded, "\"1970-01-01T00:00:00.000000Z\"");
561 assert_eq!(from_str::<Timestamp>(&encoded).unwrap(), timestamp);
562 assert!(from_value::<Timestamp>(Value::Null).is_err());
563
564 let schema = to_value(schemars::schema_for!(Timestamp)).unwrap();
565 assert_eq!(schema["type"], "string");
566 assert_eq!(schema["format"], "date-time");
567 assert_eq!(schema["minLength"], TIMESTAMP_LEN);
568 assert_eq!(schema["maxLength"], TIMESTAMP_LEN);
569 assert_eq!(schema["pattern"], TIMESTAMP_PATTERN);
570 }
571
572 #[test]
573 fn duration_millis_enforces_bounds_and_checked_arithmetic() {
574 assert_eq!(DurationMillis::new(0).unwrap(), DurationMillis::ZERO);
575 assert_eq!(
576 DurationMillis::new(-1),
577 Err(DurationMillisError::Negative { milliseconds: -1 })
578 );
579 assert_eq!(
580 DurationMillis::try_from(i64::MAX as u64 + 1),
581 Err(DurationMillisError::TooLarge)
582 );
583
584 let one = DurationMillis::new(1).unwrap();
585 assert_eq!(one.checked_add(one).unwrap().as_i64(), 2);
586 assert_eq!(one.checked_sub(one), Some(DurationMillis::ZERO));
587 assert_eq!(one.checked_sub(DurationMillis::new(2).unwrap()), None);
588 assert_eq!(DurationMillis::MAX.checked_add(one), None);
589 }
590
591 #[test]
592 fn duration_millis_std_conversion_never_truncates() {
593 let exact = Duration::from_millis(1_234);
594 let encoded = DurationMillis::try_from(exact).unwrap();
595 assert_eq!(encoded.as_i64(), 1_234);
596 assert_eq!(Duration::from(encoded), exact);
597
598 assert_eq!(
599 DurationMillis::try_from(Duration::from_nanos(1)),
600 Err(DurationMillisError::SubmillisecondPrecision)
601 );
602 }
603
604 #[test]
605 fn duration_millis_serde_and_schema_enforce_the_wire_contract() {
606 let duration = DurationMillis::new(42).unwrap();
607 assert_eq!(to_string(&duration).unwrap(), "\"42\"");
608 assert_eq!(from_str::<DurationMillis>("\"42\"").unwrap(), duration);
609 assert!(from_str::<DurationMillis>("42").is_err());
610 assert!(from_str::<DurationMillis>("\"-1\"").is_err());
611 assert!(from_str::<DurationMillis>("\"01\"").is_err());
612 assert!(from_str::<DurationMillis>("\"1.5\"").is_err());
613
614 let schema = to_value(schemars::schema_for!(DurationMillis)).unwrap();
615 assert_eq!(schema["type"], "string");
616 assert_eq!(schema["minLength"], 1);
617 assert_eq!(schema["maxLength"], 19);
618 assert_eq!(schema["pattern"], DURATION_MILLIS_PATTERN);
619 }
620}