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 #[must_use]
262 pub fn now() -> Self {
263 Self::EPOCH + Duration::from_nanos_truncating(crate::clock::time_ns())
264 }
265
266 pub const EPOCH: Self = Self(0);
268 pub const MIN: Self = Self(i64::MIN);
270 pub const MAX: Self = Self(i64::MAX);
272
273 const MILLIS_PER_SEC: i64 = 1_000;
274
275 #[must_use]
277 pub const fn from_secs(seconds: i64) -> Self {
278 Self(seconds.saturating_mul(Self::MILLIS_PER_SEC))
279 }
280
281 #[must_use]
283 pub const fn from_millis(millis: i64) -> Self {
284 Self(millis)
285 }
286
287 #[must_use]
289 pub const fn try_from_i64(millis: i64) -> Option<Self> {
290 Some(Self(millis))
291 }
292
293 #[must_use]
295 pub fn try_from_u64(millis: u64) -> Option<Self> {
296 i64::try_from(millis).ok().map(Self)
297 }
298
299 #[must_use]
301 pub const fn from_micros(micros: i64) -> Self {
302 Self(micros.div_euclid(Self::MILLIS_PER_SEC))
303 }
304
305 #[must_use]
307 pub const fn from_nanos(nanos: i64) -> Self {
308 Self(nanos.div_euclid(1_000_000))
309 }
310
311 pub fn parse_rfc3339(input: &str) -> Result<Self, TimeParseError> {
318 let bytes = input.as_bytes();
319 if bytes.len() < 20
320 || bytes.get(4) != Some(&b'-')
321 || bytes.get(7) != Some(&b'-')
322 || bytes.get(10) != Some(&b'T')
323 || bytes.get(13) != Some(&b':')
324 || bytes.get(16) != Some(&b':')
325 {
326 return Err(TimeParseError::InvalidTimestamp);
327 }
328 let date = input
329 .get(..10)
330 .and_then(Date::parse)
331 .ok_or(TimeParseError::InvalidTimestamp)?;
332 let hour = parse_u8(&bytes[11..13])?;
333 let minute = parse_u8(&bytes[14..16])?;
334 let second = parse_u8(&bytes[17..19])?;
335
336 let mut cursor = 19;
337 let nanoseconds = if bytes.get(cursor) == Some(&b'.') {
338 cursor += 1;
339 let start = cursor;
340 while bytes.get(cursor).is_some_and(u8::is_ascii_digit) {
341 cursor += 1;
342 }
343 if cursor == start {
344 return Err(TimeParseError::InvalidTimestamp);
345 }
346
347 parse_fractional_nanoseconds(&bytes[start..cursor])?
348 } else {
349 0
350 };
351 let (sign, offset_hour, offset_minute) = parse_offset(&bytes[cursor..])?;
352 if hour > 23 || minute > 59 || second > 59 || offset_hour > 23 || offset_minute > 59 {
353 return Err(TimeParseError::InvalidTimestamp);
354 }
355 let local_seconds = i64::from(date.as_days_since_epoch()) * 86_400
359 + i64::from(hour) * 3_600
360 + i64::from(minute) * 60
361 + i64::from(second);
362 let offset_seconds =
363 i64::from(sign) * (i64::from(offset_hour) * 3_600 + i64::from(offset_minute) * 60);
364
365 Ok(Self(
366 (local_seconds - offset_seconds) * Self::MILLIS_PER_SEC
367 + i64::from(nanoseconds / 1_000_000),
368 ))
369 }
370
371 pub fn parse_flexible(input: &str) -> Result<Self, TimeParseError> {
377 input
378 .parse::<i64>()
379 .map(Self)
380 .or_else(|_| Self::parse_rfc3339(input))
381 }
382
383 #[must_use]
385 pub const fn as_millis(self) -> i64 {
386 self.0
387 }
388
389 #[must_use]
391 pub const fn as_secs(self) -> i64 {
392 self.0.div_euclid(Self::MILLIS_PER_SEC)
393 }
394
395 fn from_wide_millis_saturating(millis: i128) -> Self {
396 match i64::try_from(millis) {
397 Ok(millis) => Self(millis),
398 Err(_) if millis.is_negative() => Self::MIN,
399 Err(_) => Self::MAX,
400 }
401 }
402}
403
404impl Add<Duration> for Timestamp {
405 type Output = Self;
406
407 fn add(self, duration: Duration) -> Self::Output {
408 Self::from_wide_millis_saturating(i128::from(self.0) + i128::from(duration.as_millis()))
409 }
410}
411
412impl AddAssign<Duration> for Timestamp {
413 fn add_assign(&mut self, duration: Duration) {
414 *self = *self + duration;
415 }
416}
417
418impl Display for Timestamp {
419 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
420 Display::fmt(&self.0, formatter)
421 }
422}
423
424impl From<i64> for Timestamp {
425 fn from(value: i64) -> Self {
426 Self(value)
427 }
428}
429
430impl Sub<Duration> for Timestamp {
431 type Output = Self;
432
433 fn sub(self, duration: Duration) -> Self::Output {
434 Self::from_wide_millis_saturating(i128::from(self.0) - i128::from(duration.as_millis()))
435 }
436}
437
438impl Sub for Timestamp {
439 type Output = Duration;
440
441 fn sub(self, other: Self) -> Self::Output {
442 if self.0 <= other.0 {
443 return Duration::ZERO;
444 }
445
446 Duration::from_millis(
447 u64::try_from(i128::from(self.0) - i128::from(other.0)).unwrap_or(u64::MAX),
448 )
449 }
450}
451
452impl SubAssign<Duration> for Timestamp {
453 fn sub_assign(&mut self, duration: Duration) {
454 *self = *self - duration;
455 }
456}
457
458fn parse_u8(bytes: &[u8]) -> Result<u8, TimeParseError> {
459 bytes
460 .iter()
461 .try_fold(0_u8, |value, byte| {
462 byte.checked_sub(b'0')
463 .filter(|digit| *digit <= 9)
464 .and_then(|digit| value.checked_mul(10)?.checked_add(digit))
465 })
466 .ok_or(TimeParseError::InvalidTimestamp)
467}
468
469fn parse_fractional_nanoseconds(bytes: &[u8]) -> Result<u32, TimeParseError> {
470 let mut value = 0_u32;
471 for byte in bytes.iter().take(9) {
472 let digit = byte
473 .checked_sub(b'0')
474 .filter(|digit| *digit <= 9)
475 .ok_or(TimeParseError::InvalidTimestamp)?;
476 value = value
477 .checked_mul(10)
478 .and_then(|current| current.checked_add(u32::from(digit)))
479 .ok_or(TimeParseError::InvalidTimestamp)?;
480 }
481 for _ in bytes.len().min(9)..9 {
482 value = value
483 .checked_mul(10)
484 .ok_or(TimeParseError::InvalidTimestamp)?;
485 }
486
487 Ok(value)
488}
489
490fn parse_offset(bytes: &[u8]) -> Result<(i8, u8, u8), TimeParseError> {
491 match bytes {
492 [b'Z'] => Ok((1, 0, 0)),
493 [sign @ (b'+' | b'-'), hour0, hour1, b':', minute0, minute1] => Ok((
494 if *sign == b'+' { 1 } else { -1 },
495 parse_u8(&[*hour0, *hour1])?,
496 parse_u8(&[*minute0, *minute1])?,
497 )),
498 _ => Err(TimeParseError::InvalidTimestamp),
499 }
500}
501
502#[derive(Clone, Copy, Debug, Eq, PartialEq)]
504pub enum TimeParseError {
505 InvalidDuration,
507 InvalidTimestamp,
509}
510impl Display for TimeParseError {
511 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
512 f.write_str(match self {
513 Self::InvalidDuration => "invalid millisecond duration",
514 Self::InvalidTimestamp => "invalid Unix-millisecond timestamp",
515 })
516 }
517}
518impl std::error::Error for TimeParseError {}