1use std::{
4 fmt::{self, Display, Formatter},
5 ops::{Add, AddAssign, Sub, SubAssign},
6};
7
8use crate::TypeParseError;
9
10use serde::{Deserialize, Deserializer, Serialize};
11use time::{Date as TimeDate, Month, PrimitiveDateTime, Time as TimeOfDay, UtcOffset};
12
13#[cfg(test)]
14mod tests;
15
16#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
18#[repr(transparent)]
19pub struct Duration(u64);
20
21impl Duration {
22 pub const ZERO: Self = Self(0);
24 pub const MIN: Self = Self(u64::MIN);
26 pub const MAX: Self = Self(u64::MAX);
28
29 const MS_PER_SEC: u64 = 1_000;
30 const SECS_PER_MIN: u64 = 60;
31 const MINS_PER_HOUR: u64 = 60;
32 const HOURS_PER_DAY: u64 = 24;
33 const DAYS_PER_WEEK: u64 = 7;
34
35 #[must_use]
37 pub const fn from_millis(millis: u64) -> Self {
38 Self(millis)
39 }
40
41 #[must_use]
43 pub const fn try_from_i64(millis: i64) -> Option<Self> {
44 if millis < 0 {
45 None
46 } else {
47 Some(Self(millis.cast_unsigned()))
48 }
49 }
50
51 #[must_use]
53 pub const fn from_micros_truncating(micros: u64) -> Self {
54 Self(micros / Self::MS_PER_SEC)
55 }
56
57 #[must_use]
59 pub const fn from_nanos_truncating(nanos: u64) -> Self {
60 Self(nanos / 1_000_000)
61 }
62
63 #[must_use]
65 pub const fn from_secs(seconds: u64) -> Self {
66 Self(seconds.saturating_mul(Self::MS_PER_SEC))
67 }
68
69 #[must_use]
71 pub const fn from_minutes(minutes: u64) -> Self {
72 Self(
73 minutes
74 .saturating_mul(Self::SECS_PER_MIN)
75 .saturating_mul(Self::MS_PER_SEC),
76 )
77 }
78
79 #[must_use]
81 pub const fn from_hours(hours: u64) -> Self {
82 Self(
83 hours
84 .saturating_mul(Self::MINS_PER_HOUR)
85 .saturating_mul(Self::SECS_PER_MIN)
86 .saturating_mul(Self::MS_PER_SEC),
87 )
88 }
89
90 #[must_use]
92 pub const fn from_days(days: u64) -> Self {
93 Self(
94 days.saturating_mul(Self::HOURS_PER_DAY)
95 .saturating_mul(Self::MINS_PER_HOUR)
96 .saturating_mul(Self::SECS_PER_MIN)
97 .saturating_mul(Self::MS_PER_SEC),
98 )
99 }
100
101 #[must_use]
103 pub const fn from_weeks(weeks: u64) -> Self {
104 Self(
105 weeks
106 .saturating_mul(Self::DAYS_PER_WEEK)
107 .saturating_mul(Self::HOURS_PER_DAY)
108 .saturating_mul(Self::MINS_PER_HOUR)
109 .saturating_mul(Self::SECS_PER_MIN)
110 .saturating_mul(Self::MS_PER_SEC),
111 )
112 }
113
114 #[must_use]
116 pub const fn as_millis(self) -> u64 {
117 self.0
118 }
119
120 #[must_use]
122 pub const fn as_secs(self) -> u64 {
123 self.0 / Self::MS_PER_SEC
124 }
125
126 #[must_use]
128 pub const fn as_minutes(self) -> u64 {
129 self.0 / (Self::SECS_PER_MIN * Self::MS_PER_SEC)
130 }
131
132 #[must_use]
134 pub const fn as_hours(self) -> u64 {
135 self.0 / (Self::MINS_PER_HOUR * Self::SECS_PER_MIN * Self::MS_PER_SEC)
136 }
137
138 #[must_use]
140 pub const fn as_days(self) -> u64 {
141 self.0 / (Self::HOURS_PER_DAY * Self::MINS_PER_HOUR * Self::SECS_PER_MIN * Self::MS_PER_SEC)
142 }
143
144 #[must_use]
146 pub const fn as_weeks(self) -> u64 {
147 self.0
148 / (Self::DAYS_PER_WEEK
149 * Self::HOURS_PER_DAY
150 * Self::MINS_PER_HOUR
151 * Self::SECS_PER_MIN
152 * Self::MS_PER_SEC)
153 }
154
155 pub fn parse_flexible(input: &str) -> Result<Self, TypeParseError> {
162 let (digits, multiplier) = if let Some(value) = input.strip_suffix("ms") {
163 (value, 1)
164 } else if let Some(value) = input.strip_suffix('s') {
165 (value, Self::MS_PER_SEC)
166 } else if let Some(value) = input.strip_suffix('m') {
167 (value, Self::SECS_PER_MIN * Self::MS_PER_SEC)
168 } else if let Some(value) = input.strip_suffix('h') {
169 (
170 value,
171 Self::MINS_PER_HOUR * Self::SECS_PER_MIN * Self::MS_PER_SEC,
172 )
173 } else if let Some(value) = input.strip_suffix('d') {
174 (
175 value,
176 Self::HOURS_PER_DAY * Self::MINS_PER_HOUR * Self::SECS_PER_MIN * Self::MS_PER_SEC,
177 )
178 } else {
179 (input, 1)
180 };
181 if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
182 return Err(TypeParseError::InvalidDuration);
183 }
184 let value = digits
185 .parse::<u64>()
186 .map_err(|_| TypeParseError::InvalidDuration)?;
187 value
188 .checked_mul(multiplier)
189 .map(Self)
190 .ok_or(TypeParseError::InvalidDuration)
191 }
192}
193
194impl Add for Duration {
195 type Output = Self;
196
197 fn add(self, other: Self) -> Self::Output {
198 Self(self.0.saturating_add(other.0))
199 }
200}
201
202impl AddAssign for Duration {
203 fn add_assign(&mut self, other: Self) {
204 self.0 = self.0.saturating_add(other.0);
205 }
206}
207
208impl<'de> Deserialize<'de> for Duration {
209 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
210 where
211 D: Deserializer<'de>,
212 {
213 struct DurationVisitor;
214
215 impl serde::de::Visitor<'_> for DurationVisitor {
216 type Value = Duration;
217
218 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
219 formatter.write_str("milliseconds or duration string")
220 }
221
222 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
223 where
224 E: serde::de::Error,
225 {
226 Duration::try_from_i64(value)
227 .ok_or_else(|| E::custom("duration must be non-negative"))
228 }
229
230 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
231 Ok(Duration::from_millis(value))
232 }
233
234 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
235 where
236 E: serde::de::Error,
237 {
238 Duration::parse_flexible(value).map_err(E::custom)
239 }
240 }
241
242 if !deserializer.is_human_readable() {
243 return u64::deserialize(deserializer).map(Self);
244 }
245
246 deserializer.deserialize_any(DurationVisitor)
247 }
248}
249
250impl From<u64> for Duration {
251 fn from(value: u64) -> Self {
252 Self(value)
253 }
254}
255
256impl Serialize for Duration {
257 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
258 where
259 S: serde::Serializer,
260 {
261 serializer.serialize_u64(self.0)
262 }
263}
264
265impl Sub for Duration {
266 type Output = Self;
267
268 fn sub(self, other: Self) -> Self::Output {
269 Self(self.0.saturating_sub(other.0))
270 }
271}
272
273impl SubAssign for Duration {
274 fn sub_assign(&mut self, other: Self) {
275 self.0 = self.0.saturating_sub(other.0);
276 }
277}
278
279#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
281#[repr(transparent)]
282pub struct Timestamp(i64);
283
284impl Timestamp {
285 pub const EPOCH: Self = Self(0);
287 pub const MIN: Self = Self(i64::MIN);
289 pub const MAX: Self = Self(i64::MAX);
291
292 const MILLIS_PER_SEC: i64 = 1_000;
293
294 #[must_use]
296 pub const fn from_secs(seconds: i64) -> Self {
297 Self(seconds.saturating_mul(Self::MILLIS_PER_SEC))
298 }
299
300 #[must_use]
302 pub const fn from_millis(millis: i64) -> Self {
303 Self(millis)
304 }
305
306 #[must_use]
308 pub const fn try_from_i64(millis: i64) -> Option<Self> {
309 Some(Self(millis))
310 }
311
312 #[must_use]
314 pub fn try_from_u64(millis: u64) -> Option<Self> {
315 i64::try_from(millis).ok().map(Self)
316 }
317
318 #[must_use]
320 pub const fn from_micros(micros: i64) -> Self {
321 Self(micros.div_euclid(Self::MILLIS_PER_SEC))
322 }
323
324 #[must_use]
326 pub const fn from_nanos(nanos: i64) -> Self {
327 Self(nanos.div_euclid(1_000_000))
328 }
329
330 pub fn parse_rfc3339(input: &str) -> Result<Self, TypeParseError> {
337 let bytes = input.as_bytes();
338 if bytes.len() < 20
339 || bytes.get(4) != Some(&b'-')
340 || bytes.get(7) != Some(&b'-')
341 || bytes.get(10) != Some(&b'T')
342 || bytes.get(13) != Some(&b':')
343 || bytes.get(16) != Some(&b':')
344 {
345 return Err(TypeParseError::InvalidTimestamp);
346 }
347 let year = parse_i32(&bytes[0..4])?;
348 let month = Month::try_from(parse_u8(&bytes[5..7])?)
349 .map_err(|_| TypeParseError::InvalidTimestamp)?;
350 let day = parse_u8(&bytes[8..10])?;
351 let hour = parse_u8(&bytes[11..13])?;
352 let minute = parse_u8(&bytes[14..16])?;
353 let second = parse_u8(&bytes[17..19])?;
354
355 let mut cursor = 19;
356 let nanoseconds = if bytes.get(cursor) == Some(&b'.') {
357 cursor += 1;
358 let start = cursor;
359 while bytes.get(cursor).is_some_and(u8::is_ascii_digit) {
360 cursor += 1;
361 }
362 if cursor == start {
363 return Err(TypeParseError::InvalidTimestamp);
364 }
365 parse_fractional_nanoseconds(&bytes[start..cursor])?
366 } else {
367 0
368 };
369 let (sign, offset_hour, offset_minute) = parse_offset(&bytes[cursor..])?;
370 let date = TimeDate::from_calendar_date(year, month, day)
371 .map_err(|_| TypeParseError::InvalidTimestamp)?;
372 let time = TimeOfDay::from_hms_nano(hour, minute, second, nanoseconds)
373 .map_err(|_| TypeParseError::InvalidTimestamp)?;
374 let offset = UtcOffset::from_hms(
375 sign * i8::try_from(offset_hour).unwrap_or(i8::MAX),
376 sign * i8::try_from(offset_minute).unwrap_or(i8::MAX),
377 0,
378 )
379 .map_err(|_| TypeParseError::InvalidTimestamp)?;
380 let millis = PrimitiveDateTime::new(date, time)
381 .assume_offset(offset)
382 .unix_timestamp_nanos()
383 .div_euclid(1_000_000);
384 i64::try_from(millis)
385 .map(Self)
386 .map_err(|_| TypeParseError::InvalidTimestamp)
387 }
388
389 pub fn parse_flexible(input: &str) -> Result<Self, TypeParseError> {
395 input
396 .parse::<i64>()
397 .map(Self)
398 .or_else(|_| Self::parse_rfc3339(input))
399 }
400
401 #[must_use]
403 pub const fn as_millis(self) -> i64 {
404 self.0
405 }
406
407 #[must_use]
409 pub const fn as_secs(self) -> i64 {
410 self.0.div_euclid(Self::MILLIS_PER_SEC)
411 }
412
413 fn from_wide_millis_saturating(millis: i128) -> Self {
414 match i64::try_from(millis) {
415 Ok(millis) => Self(millis),
416 Err(_) if millis.is_negative() => Self::MIN,
417 Err(_) => Self::MAX,
418 }
419 }
420}
421
422impl Add<Duration> for Timestamp {
423 type Output = Self;
424
425 fn add(self, duration: Duration) -> Self::Output {
426 Self::from_wide_millis_saturating(i128::from(self.0) + i128::from(duration.as_millis()))
427 }
428}
429
430impl AddAssign<Duration> for Timestamp {
431 fn add_assign(&mut self, duration: Duration) {
432 *self = *self + duration;
433 }
434}
435
436impl<'de> Deserialize<'de> for Timestamp {
437 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
438 where
439 D: Deserializer<'de>,
440 {
441 struct TimestampVisitor;
442
443 impl serde::de::Visitor<'_> for TimestampVisitor {
444 type Value = Timestamp;
445
446 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
447 formatter.write_str("unix millis or RFC3339 timestamp")
448 }
449
450 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> {
451 Ok(Timestamp::from_millis(value))
452 }
453
454 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
455 where
456 E: serde::de::Error,
457 {
458 Timestamp::try_from_u64(value)
459 .ok_or_else(|| E::custom("unix millis exceeds i64 timestamp range"))
460 }
461
462 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
463 where
464 E: serde::de::Error,
465 {
466 Timestamp::parse_flexible(value).map_err(E::custom)
467 }
468 }
469
470 if !deserializer.is_human_readable() {
471 return i64::deserialize(deserializer).map(Self);
472 }
473
474 deserializer.deserialize_any(TimestampVisitor)
475 }
476}
477
478impl Display for Timestamp {
479 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
480 Display::fmt(&self.0, formatter)
481 }
482}
483
484impl From<i64> for Timestamp {
485 fn from(value: i64) -> Self {
486 Self(value)
487 }
488}
489
490impl Serialize for Timestamp {
491 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
492 where
493 S: serde::Serializer,
494 {
495 serializer.serialize_i64(self.0)
496 }
497}
498
499impl Sub<Duration> for Timestamp {
500 type Output = Self;
501
502 fn sub(self, duration: Duration) -> Self::Output {
503 Self::from_wide_millis_saturating(i128::from(self.0) - i128::from(duration.as_millis()))
504 }
505}
506
507impl Sub for Timestamp {
508 type Output = Duration;
509
510 fn sub(self, other: Self) -> Self::Output {
511 if self.0 <= other.0 {
512 return Duration::ZERO;
513 }
514 Duration::from_millis(
515 u64::try_from(i128::from(self.0) - i128::from(other.0)).unwrap_or(u64::MAX),
516 )
517 }
518}
519
520impl SubAssign<Duration> for Timestamp {
521 fn sub_assign(&mut self, duration: Duration) {
522 *self = *self - duration;
523 }
524}
525
526fn parse_i32(bytes: &[u8]) -> Result<i32, TypeParseError> {
527 bytes
528 .iter()
529 .try_fold(0_i32, |value, byte| {
530 byte.checked_sub(b'0')
531 .filter(|digit| *digit <= 9)
532 .and_then(|digit| value.checked_mul(10)?.checked_add(i32::from(digit)))
533 })
534 .ok_or(TypeParseError::InvalidTimestamp)
535}
536
537fn parse_u8(bytes: &[u8]) -> Result<u8, TypeParseError> {
538 bytes
539 .iter()
540 .try_fold(0_u8, |value, byte| {
541 byte.checked_sub(b'0')
542 .filter(|digit| *digit <= 9)
543 .and_then(|digit| value.checked_mul(10)?.checked_add(digit))
544 })
545 .ok_or(TypeParseError::InvalidTimestamp)
546}
547
548fn parse_fractional_nanoseconds(bytes: &[u8]) -> Result<u32, TypeParseError> {
549 let mut value = 0_u32;
550 for byte in bytes.iter().take(9) {
551 let digit = byte
552 .checked_sub(b'0')
553 .filter(|digit| *digit <= 9)
554 .ok_or(TypeParseError::InvalidTimestamp)?;
555 value = value
556 .checked_mul(10)
557 .and_then(|current| current.checked_add(u32::from(digit)))
558 .ok_or(TypeParseError::InvalidTimestamp)?;
559 }
560 for _ in bytes.len().min(9)..9 {
561 value = value
562 .checked_mul(10)
563 .ok_or(TypeParseError::InvalidTimestamp)?;
564 }
565 Ok(value)
566}
567
568fn parse_offset(bytes: &[u8]) -> Result<(i8, u8, u8), TypeParseError> {
569 match bytes {
570 [b'Z'] => Ok((1, 0, 0)),
571 [sign @ (b'+' | b'-'), hour0, hour1, b':', minute0, minute1] => Ok((
572 if *sign == b'+' { 1 } else { -1 },
573 parse_u8(&[*hour0, *hour1])?,
574 parse_u8(&[*minute0, *minute1])?,
575 )),
576 _ => Err(TypeParseError::InvalidTimestamp),
577 }
578}