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 value
197 .checked_mul(multiplier)
198 .map(Self)
199 .ok_or(TimeParseError::InvalidDuration)
200 }
201}
202
203impl Add for Duration {
204 type Output = Self;
205
206 fn add(self, other: Self) -> Self::Output {
207 Self(self.0.saturating_add(other.0))
208 }
209}
210
211impl AddAssign for Duration {
212 fn add_assign(&mut self, other: Self) {
213 self.0 = self.0.saturating_add(other.0);
214 }
215}
216
217impl From<u64> for Duration {
218 fn from(value: u64) -> Self {
219 Self(value)
220 }
221}
222
223impl Sub for Duration {
224 type Output = Self;
225
226 fn sub(self, other: Self) -> Self::Output {
227 Self(self.0.saturating_sub(other.0))
228 }
229}
230
231impl SubAssign for Duration {
232 fn sub_assign(&mut self, other: Self) {
233 self.0 = self.0.saturating_sub(other.0);
234 }
235}
236
237#[derive(
241 Clone,
242 Copy,
243 Debug,
244 Default,
245 Eq,
246 Hash,
247 Ord,
248 PartialEq,
249 PartialOrd,
250 serde::Serialize,
251 serde::Deserialize,
252)]
253#[serde(transparent)]
254#[repr(transparent)]
255pub struct Timestamp(i64);
256
257impl Timestamp {
258 pub const EPOCH: Self = Self(0);
260 pub const MIN: Self = Self(i64::MIN);
262 pub const MAX: Self = Self(i64::MAX);
264
265 const MILLIS_PER_SEC: i64 = 1_000;
266
267 #[must_use]
269 pub const fn from_secs(seconds: i64) -> Self {
270 Self(seconds.saturating_mul(Self::MILLIS_PER_SEC))
271 }
272
273 #[must_use]
275 pub const fn from_millis(millis: i64) -> Self {
276 Self(millis)
277 }
278
279 #[must_use]
281 pub const fn try_from_i64(millis: i64) -> Option<Self> {
282 Some(Self(millis))
283 }
284
285 #[must_use]
287 pub fn try_from_u64(millis: u64) -> Option<Self> {
288 i64::try_from(millis).ok().map(Self)
289 }
290
291 #[must_use]
293 pub const fn from_micros(micros: i64) -> Self {
294 Self(micros.div_euclid(Self::MILLIS_PER_SEC))
295 }
296
297 #[must_use]
299 pub const fn from_nanos(nanos: i64) -> Self {
300 Self(nanos.div_euclid(1_000_000))
301 }
302
303 pub fn parse_rfc3339(input: &str) -> Result<Self, TimeParseError> {
310 let bytes = input.as_bytes();
311 if bytes.len() < 20
312 || bytes.get(4) != Some(&b'-')
313 || bytes.get(7) != Some(&b'-')
314 || bytes.get(10) != Some(&b'T')
315 || bytes.get(13) != Some(&b':')
316 || bytes.get(16) != Some(&b':')
317 {
318 return Err(TimeParseError::InvalidTimestamp);
319 }
320 let date = input
321 .get(..10)
322 .and_then(Date::parse)
323 .ok_or(TimeParseError::InvalidTimestamp)?;
324 let hour = parse_u8(&bytes[11..13])?;
325 let minute = parse_u8(&bytes[14..16])?;
326 let second = parse_u8(&bytes[17..19])?;
327
328 let mut cursor = 19;
329 let nanoseconds = if bytes.get(cursor) == Some(&b'.') {
330 cursor += 1;
331 let start = cursor;
332 while bytes.get(cursor).is_some_and(u8::is_ascii_digit) {
333 cursor += 1;
334 }
335 if cursor == start {
336 return Err(TimeParseError::InvalidTimestamp);
337 }
338 parse_fractional_nanoseconds(&bytes[start..cursor])?
339 } else {
340 0
341 };
342 let (sign, offset_hour, offset_minute) = parse_offset(&bytes[cursor..])?;
343 if hour > 23 || minute > 59 || second > 59 || offset_hour > 23 || offset_minute > 59 {
344 return Err(TimeParseError::InvalidTimestamp);
345 }
346 let local_seconds = i64::from(date.as_days_since_epoch()) * 86_400
350 + i64::from(hour) * 3_600
351 + i64::from(minute) * 60
352 + i64::from(second);
353 let offset_seconds =
354 i64::from(sign) * (i64::from(offset_hour) * 3_600 + i64::from(offset_minute) * 60);
355 Ok(Self(
356 (local_seconds - offset_seconds) * Self::MILLIS_PER_SEC
357 + i64::from(nanoseconds / 1_000_000),
358 ))
359 }
360
361 pub fn parse_flexible(input: &str) -> Result<Self, TimeParseError> {
367 input
368 .parse::<i64>()
369 .map(Self)
370 .or_else(|_| Self::parse_rfc3339(input))
371 }
372
373 #[must_use]
375 pub const fn as_millis(self) -> i64 {
376 self.0
377 }
378
379 #[must_use]
381 pub const fn as_secs(self) -> i64 {
382 self.0.div_euclid(Self::MILLIS_PER_SEC)
383 }
384
385 fn from_wide_millis_saturating(millis: i128) -> Self {
386 match i64::try_from(millis) {
387 Ok(millis) => Self(millis),
388 Err(_) if millis.is_negative() => Self::MIN,
389 Err(_) => Self::MAX,
390 }
391 }
392}
393
394impl Add<Duration> for Timestamp {
395 type Output = Self;
396
397 fn add(self, duration: Duration) -> Self::Output {
398 Self::from_wide_millis_saturating(i128::from(self.0) + i128::from(duration.as_millis()))
399 }
400}
401
402impl AddAssign<Duration> for Timestamp {
403 fn add_assign(&mut self, duration: Duration) {
404 *self = *self + duration;
405 }
406}
407
408impl Display for Timestamp {
409 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
410 Display::fmt(&self.0, formatter)
411 }
412}
413
414impl From<i64> for Timestamp {
415 fn from(value: i64) -> Self {
416 Self(value)
417 }
418}
419
420impl Sub<Duration> for Timestamp {
421 type Output = Self;
422
423 fn sub(self, duration: Duration) -> Self::Output {
424 Self::from_wide_millis_saturating(i128::from(self.0) - i128::from(duration.as_millis()))
425 }
426}
427
428impl Sub for Timestamp {
429 type Output = Duration;
430
431 fn sub(self, other: Self) -> Self::Output {
432 if self.0 <= other.0 {
433 return Duration::ZERO;
434 }
435 Duration::from_millis(
436 u64::try_from(i128::from(self.0) - i128::from(other.0)).unwrap_or(u64::MAX),
437 )
438 }
439}
440
441impl SubAssign<Duration> for Timestamp {
442 fn sub_assign(&mut self, duration: Duration) {
443 *self = *self - duration;
444 }
445}
446
447fn parse_u8(bytes: &[u8]) -> Result<u8, TimeParseError> {
448 bytes
449 .iter()
450 .try_fold(0_u8, |value, byte| {
451 byte.checked_sub(b'0')
452 .filter(|digit| *digit <= 9)
453 .and_then(|digit| value.checked_mul(10)?.checked_add(digit))
454 })
455 .ok_or(TimeParseError::InvalidTimestamp)
456}
457
458fn parse_fractional_nanoseconds(bytes: &[u8]) -> Result<u32, TimeParseError> {
459 let mut value = 0_u32;
460 for byte in bytes.iter().take(9) {
461 let digit = byte
462 .checked_sub(b'0')
463 .filter(|digit| *digit <= 9)
464 .ok_or(TimeParseError::InvalidTimestamp)?;
465 value = value
466 .checked_mul(10)
467 .and_then(|current| current.checked_add(u32::from(digit)))
468 .ok_or(TimeParseError::InvalidTimestamp)?;
469 }
470 for _ in bytes.len().min(9)..9 {
471 value = value
472 .checked_mul(10)
473 .ok_or(TimeParseError::InvalidTimestamp)?;
474 }
475 Ok(value)
476}
477
478fn parse_offset(bytes: &[u8]) -> Result<(i8, u8, u8), TimeParseError> {
479 match bytes {
480 [b'Z'] => Ok((1, 0, 0)),
481 [sign @ (b'+' | b'-'), hour0, hour1, b':', minute0, minute1] => Ok((
482 if *sign == b'+' { 1 } else { -1 },
483 parse_u8(&[*hour0, *hour1])?,
484 parse_u8(&[*minute0, *minute1])?,
485 )),
486 _ => Err(TimeParseError::InvalidTimestamp),
487 }
488}
489
490#[derive(Clone, Copy, Debug, Eq, PartialEq)]
492pub enum TimeParseError {
493 InvalidDuration,
495 InvalidTimestamp,
497}
498impl Display for TimeParseError {
499 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
500 f.write_str(match self {
501 Self::InvalidDuration => "invalid millisecond duration",
502 Self::InvalidTimestamp => "invalid Unix-millisecond timestamp",
503 })
504 }
505}
506impl std::error::Error for TimeParseError {}