1use std::{
5 fmt::{self, Display, Formatter},
6 ops::{Add, AddAssign, Sub, SubAssign},
7};
8
9use crate::Date;
10
11#[derive(
14 Clone,
15 Copy,
16 Debug,
17 Default,
18 Eq,
19 Hash,
20 Ord,
21 PartialEq,
22 PartialOrd,
23 serde::Serialize,
24 serde::Deserialize,
25)]
26#[serde(transparent)]
27#[repr(transparent)]
28pub struct Duration(u64);
29
30impl Duration {
31 pub const ZERO: Self = Self(0);
33 pub const MIN: Self = Self(u64::MIN);
35 pub const MAX: Self = Self(u64::MAX);
37
38 const MS_PER_SEC: u64 = 1_000;
39 const SECS_PER_MIN: u64 = 60;
40 const MINS_PER_HOUR: u64 = 60;
41 const HOURS_PER_DAY: u64 = 24;
42 const DAYS_PER_WEEK: u64 = 7;
43
44 #[must_use]
46 pub const fn from_millis(millis: u64) -> Self {
47 Self(millis)
48 }
49
50 #[must_use]
52 pub const fn try_from_i64(millis: i64) -> Option<Self> {
53 if millis < 0 {
54 None
55 } else {
56 Some(Self(millis.cast_unsigned()))
57 }
58 }
59
60 #[must_use]
62 pub const fn from_micros_truncating(micros: u64) -> Self {
63 Self(micros / Self::MS_PER_SEC)
64 }
65
66 #[must_use]
68 pub const fn from_nanos_truncating(nanos: u64) -> Self {
69 Self(nanos / 1_000_000)
70 }
71
72 #[must_use]
74 pub const fn from_secs(seconds: u64) -> Self {
75 Self(seconds.saturating_mul(Self::MS_PER_SEC))
76 }
77
78 #[must_use]
80 pub const fn from_minutes(minutes: u64) -> Self {
81 Self(
82 minutes
83 .saturating_mul(Self::SECS_PER_MIN)
84 .saturating_mul(Self::MS_PER_SEC),
85 )
86 }
87
88 #[must_use]
90 pub const fn from_hours(hours: u64) -> Self {
91 Self(
92 hours
93 .saturating_mul(Self::MINS_PER_HOUR)
94 .saturating_mul(Self::SECS_PER_MIN)
95 .saturating_mul(Self::MS_PER_SEC),
96 )
97 }
98
99 #[must_use]
101 pub const fn from_days(days: u64) -> Self {
102 Self(
103 days.saturating_mul(Self::HOURS_PER_DAY)
104 .saturating_mul(Self::MINS_PER_HOUR)
105 .saturating_mul(Self::SECS_PER_MIN)
106 .saturating_mul(Self::MS_PER_SEC),
107 )
108 }
109
110 #[must_use]
112 pub const fn from_weeks(weeks: u64) -> Self {
113 Self(
114 weeks
115 .saturating_mul(Self::DAYS_PER_WEEK)
116 .saturating_mul(Self::HOURS_PER_DAY)
117 .saturating_mul(Self::MINS_PER_HOUR)
118 .saturating_mul(Self::SECS_PER_MIN)
119 .saturating_mul(Self::MS_PER_SEC),
120 )
121 }
122
123 #[must_use]
125 pub const fn as_millis(self) -> u64 {
126 self.0
127 }
128
129 #[must_use]
131 pub const fn as_secs(self) -> u64 {
132 self.0 / Self::MS_PER_SEC
133 }
134
135 #[must_use]
137 pub const fn as_minutes(self) -> u64 {
138 self.0 / (Self::SECS_PER_MIN * Self::MS_PER_SEC)
139 }
140
141 #[must_use]
143 pub const fn as_hours(self) -> u64 {
144 self.0 / (Self::MINS_PER_HOUR * Self::SECS_PER_MIN * Self::MS_PER_SEC)
145 }
146
147 #[must_use]
149 pub const fn as_days(self) -> u64 {
150 self.0 / (Self::HOURS_PER_DAY * Self::MINS_PER_HOUR * Self::SECS_PER_MIN * Self::MS_PER_SEC)
151 }
152
153 #[must_use]
155 pub const fn as_weeks(self) -> u64 {
156 self.0
157 / (Self::DAYS_PER_WEEK
158 * Self::HOURS_PER_DAY
159 * Self::MINS_PER_HOUR
160 * Self::SECS_PER_MIN
161 * Self::MS_PER_SEC)
162 }
163
164 pub fn parse_flexible(input: &str) -> Result<Self, TimeParseError> {
171 let (digits, multiplier) = if let Some(value) = input.strip_suffix("ms") {
172 (value, 1)
173 } else if let Some(value) = input.strip_suffix('s') {
174 (value, Self::MS_PER_SEC)
175 } else if let Some(value) = input.strip_suffix('m') {
176 (value, Self::SECS_PER_MIN * Self::MS_PER_SEC)
177 } else if let Some(value) = input.strip_suffix('h') {
178 (
179 value,
180 Self::MINS_PER_HOUR * Self::SECS_PER_MIN * Self::MS_PER_SEC,
181 )
182 } else if let Some(value) = input.strip_suffix('d') {
183 (
184 value,
185 Self::HOURS_PER_DAY * Self::MINS_PER_HOUR * Self::SECS_PER_MIN * Self::MS_PER_SEC,
186 )
187 } else {
188 (input, 1)
189 };
190 if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
191 return Err(TimeParseError::InvalidDuration);
192 }
193 let value = digits
194 .parse::<u64>()
195 .map_err(|_| TimeParseError::InvalidDuration)?;
196
197 value
198 .checked_mul(multiplier)
199 .map(Self)
200 .ok_or(TimeParseError::InvalidDuration)
201 }
202}
203
204impl Add for Duration {
205 type Output = Self;
206
207 fn add(self, other: Self) -> Self::Output {
208 Self(self.0.saturating_add(other.0))
209 }
210}
211
212impl AddAssign for Duration {
213 fn add_assign(&mut self, other: Self) {
214 self.0 = self.0.saturating_add(other.0);
215 }
216}
217
218impl From<u64> for Duration {
219 fn from(value: u64) -> Self {
220 Self(value)
221 }
222}
223
224impl Sub for Duration {
225 type Output = Self;
226
227 fn sub(self, other: Self) -> Self::Output {
228 Self(self.0.saturating_sub(other.0))
229 }
230}
231
232impl SubAssign for Duration {
233 fn sub_assign(&mut self, other: Self) {
234 self.0 = self.0.saturating_sub(other.0);
235 }
236}
237
238#[derive(
242 Clone,
243 Copy,
244 Debug,
245 Default,
246 Eq,
247 Hash,
248 Ord,
249 PartialEq,
250 PartialOrd,
251 serde::Serialize,
252 serde::Deserialize,
253)]
254#[serde(transparent)]
255#[repr(transparent)]
256pub struct Timestamp(i64);
257
258impl Timestamp {
259 pub const EPOCH: Self = Self(0);
261 pub const MIN: Self = Self(i64::MIN);
263 pub const MAX: Self = Self(i64::MAX);
265
266 const MILLIS_PER_SEC: i64 = 1_000;
267
268 #[must_use]
270 pub const fn from_secs(seconds: i64) -> Self {
271 Self(seconds.saturating_mul(Self::MILLIS_PER_SEC))
272 }
273
274 #[must_use]
276 pub const fn from_millis(millis: i64) -> Self {
277 Self(millis)
278 }
279
280 #[must_use]
282 pub const fn try_from_i64(millis: i64) -> Option<Self> {
283 Some(Self(millis))
284 }
285
286 #[must_use]
288 pub fn try_from_u64(millis: u64) -> Option<Self> {
289 i64::try_from(millis).ok().map(Self)
290 }
291
292 #[must_use]
294 pub const fn from_micros(micros: i64) -> Self {
295 Self(micros.div_euclid(Self::MILLIS_PER_SEC))
296 }
297
298 #[must_use]
300 pub const fn from_nanos(nanos: i64) -> Self {
301 Self(nanos.div_euclid(1_000_000))
302 }
303
304 pub fn parse_rfc3339(input: &str) -> Result<Self, TimeParseError> {
311 let bytes = input.as_bytes();
312 if bytes.len() < 20
313 || bytes.get(4) != Some(&b'-')
314 || bytes.get(7) != Some(&b'-')
315 || bytes.get(10) != Some(&b'T')
316 || bytes.get(13) != Some(&b':')
317 || bytes.get(16) != Some(&b':')
318 {
319 return Err(TimeParseError::InvalidTimestamp);
320 }
321 let date = input
322 .get(..10)
323 .and_then(Date::parse)
324 .ok_or(TimeParseError::InvalidTimestamp)?;
325 let hour = parse_u8(&bytes[11..13])?;
326 let minute = parse_u8(&bytes[14..16])?;
327 let second = parse_u8(&bytes[17..19])?;
328
329 let mut cursor = 19;
330 let nanoseconds = if bytes.get(cursor) == Some(&b'.') {
331 cursor += 1;
332 let start = cursor;
333 while bytes.get(cursor).is_some_and(u8::is_ascii_digit) {
334 cursor += 1;
335 }
336 if cursor == start {
337 return Err(TimeParseError::InvalidTimestamp);
338 }
339
340 parse_fractional_nanoseconds(&bytes[start..cursor])?
341 } else {
342 0
343 };
344 let (sign, offset_hour, offset_minute) = parse_offset(&bytes[cursor..])?;
345 if hour > 23 || minute > 59 || second > 59 || offset_hour > 23 || offset_minute > 59 {
346 return Err(TimeParseError::InvalidTimestamp);
347 }
348 let local_seconds = i64::from(date.as_days_since_epoch()) * 86_400
352 + i64::from(hour) * 3_600
353 + i64::from(minute) * 60
354 + i64::from(second);
355 let offset_seconds =
356 i64::from(sign) * (i64::from(offset_hour) * 3_600 + i64::from(offset_minute) * 60);
357
358 Ok(Self(
359 (local_seconds - offset_seconds) * Self::MILLIS_PER_SEC
360 + i64::from(nanoseconds / 1_000_000),
361 ))
362 }
363
364 pub fn parse_flexible(input: &str) -> Result<Self, TimeParseError> {
370 input
371 .parse::<i64>()
372 .map(Self)
373 .or_else(|_| Self::parse_rfc3339(input))
374 }
375
376 #[must_use]
378 pub const fn as_millis(self) -> i64 {
379 self.0
380 }
381
382 #[must_use]
384 pub const fn as_secs(self) -> i64 {
385 self.0.div_euclid(Self::MILLIS_PER_SEC)
386 }
387
388 fn from_wide_millis_saturating(millis: i128) -> Self {
389 match i64::try_from(millis) {
390 Ok(millis) => Self(millis),
391 Err(_) if millis.is_negative() => Self::MIN,
392 Err(_) => Self::MAX,
393 }
394 }
395}
396
397impl Add<Duration> for Timestamp {
398 type Output = Self;
399
400 fn add(self, duration: Duration) -> Self::Output {
401 Self::from_wide_millis_saturating(i128::from(self.0) + i128::from(duration.as_millis()))
402 }
403}
404
405impl AddAssign<Duration> for Timestamp {
406 fn add_assign(&mut self, duration: Duration) {
407 *self = *self + duration;
408 }
409}
410
411impl Display for Timestamp {
412 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
413 Display::fmt(&self.0, formatter)
414 }
415}
416
417impl From<i64> for Timestamp {
418 fn from(value: i64) -> Self {
419 Self(value)
420 }
421}
422
423impl Sub<Duration> for Timestamp {
424 type Output = Self;
425
426 fn sub(self, duration: Duration) -> Self::Output {
427 Self::from_wide_millis_saturating(i128::from(self.0) - i128::from(duration.as_millis()))
428 }
429}
430
431impl Sub for Timestamp {
432 type Output = Duration;
433
434 fn sub(self, other: Self) -> Self::Output {
435 if self.0 <= other.0 {
436 return Duration::ZERO;
437 }
438
439 Duration::from_millis(
440 u64::try_from(i128::from(self.0) - i128::from(other.0)).unwrap_or(u64::MAX),
441 )
442 }
443}
444
445impl SubAssign<Duration> for Timestamp {
446 fn sub_assign(&mut self, duration: Duration) {
447 *self = *self - duration;
448 }
449}
450
451fn parse_u8(bytes: &[u8]) -> Result<u8, TimeParseError> {
452 bytes
453 .iter()
454 .try_fold(0_u8, |value, byte| {
455 byte.checked_sub(b'0')
456 .filter(|digit| *digit <= 9)
457 .and_then(|digit| value.checked_mul(10)?.checked_add(digit))
458 })
459 .ok_or(TimeParseError::InvalidTimestamp)
460}
461
462fn parse_fractional_nanoseconds(bytes: &[u8]) -> Result<u32, TimeParseError> {
463 let mut value = 0_u32;
464 for byte in bytes.iter().take(9) {
465 let digit = byte
466 .checked_sub(b'0')
467 .filter(|digit| *digit <= 9)
468 .ok_or(TimeParseError::InvalidTimestamp)?;
469 value = value
470 .checked_mul(10)
471 .and_then(|current| current.checked_add(u32::from(digit)))
472 .ok_or(TimeParseError::InvalidTimestamp)?;
473 }
474 for _ in bytes.len().min(9)..9 {
475 value = value
476 .checked_mul(10)
477 .ok_or(TimeParseError::InvalidTimestamp)?;
478 }
479
480 Ok(value)
481}
482
483fn parse_offset(bytes: &[u8]) -> Result<(i8, u8, u8), TimeParseError> {
484 match bytes {
485 [b'Z'] => Ok((1, 0, 0)),
486 [sign @ (b'+' | b'-'), hour0, hour1, b':', minute0, minute1] => Ok((
487 if *sign == b'+' { 1 } else { -1 },
488 parse_u8(&[*hour0, *hour1])?,
489 parse_u8(&[*minute0, *minute1])?,
490 )),
491 _ => Err(TimeParseError::InvalidTimestamp),
492 }
493}
494
495#[derive(Clone, Copy, Debug, Eq, PartialEq)]
497pub enum TimeParseError {
498 InvalidDuration,
500 InvalidTimestamp,
502}
503impl Display for TimeParseError {
504 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
505 f.write_str(match self {
506 Self::InvalidDuration => "invalid millisecond duration",
507 Self::InvalidTimestamp => "invalid Unix-millisecond timestamp",
508 })
509 }
510}
511impl std::error::Error for TimeParseError {}