1use std::{
5 fmt::{self, Display, Formatter},
6 ops::{Add, AddAssign, Sub, SubAssign},
7};
8
9use crate::{Date, date::SECONDS_PER_DAY};
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 fn try_from_u64(millis: u64) -> Option<Self> {
290 i64::try_from(millis).ok().map(Self)
291 }
292
293 #[must_use]
295 pub const fn from_micros(micros: i64) -> Self {
296 Self(micros.div_euclid(Self::MILLIS_PER_SEC))
297 }
298
299 #[must_use]
301 pub const fn from_nanos(nanos: i64) -> Self {
302 Self(nanos.div_euclid(1_000_000))
303 }
304
305 pub fn parse_rfc3339(input: &str) -> Result<Self, TimeParseError> {
312 let bytes = input.as_bytes();
313 if bytes.len() < 20
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 =
325 crate::date::two_digits(&bytes[11..13]).ok_or(TimeParseError::InvalidTimestamp)?;
326 let minute =
327 crate::date::two_digits(&bytes[14..16]).ok_or(TimeParseError::InvalidTimestamp)?;
328 let second =
329 crate::date::two_digits(&bytes[17..19]).ok_or(TimeParseError::InvalidTimestamp)?;
330
331 let mut cursor = 19;
332 let nanoseconds = if bytes.get(cursor) == Some(&b'.') {
333 cursor += 1;
334 let start = cursor;
335 while bytes.get(cursor).is_some_and(u8::is_ascii_digit) {
336 cursor += 1;
337 }
338 if cursor == start {
339 return Err(TimeParseError::InvalidTimestamp);
340 }
341
342 parse_fractional_nanoseconds(&bytes[start..cursor])?
343 } else {
344 0
345 };
346 let (sign, offset_hour, offset_minute) = parse_offset(&bytes[cursor..])?;
347 if hour > 23 || minute > 59 || second > 59 || offset_hour > 23 || offset_minute > 59 {
348 return Err(TimeParseError::InvalidTimestamp);
349 }
350 let local_seconds = i64::from(date.as_days_since_epoch()) * SECONDS_PER_DAY
354 + i64::from(hour) * 3_600
355 + i64::from(minute) * 60
356 + i64::from(second);
357 let offset_seconds =
358 i64::from(sign) * (i64::from(offset_hour) * 3_600 + i64::from(offset_minute) * 60);
359
360 Ok(Self(
361 (local_seconds - offset_seconds) * Self::MILLIS_PER_SEC
362 + i64::from(nanoseconds / 1_000_000),
363 ))
364 }
365
366 pub fn parse_flexible(input: &str) -> Result<Self, TimeParseError> {
372 input
373 .parse::<i64>()
374 .map(Self)
375 .or_else(|_| Self::parse_rfc3339(input))
376 }
377
378 #[must_use]
380 pub const fn as_millis(self) -> i64 {
381 self.0
382 }
383
384 #[must_use]
386 pub const fn as_secs(self) -> i64 {
387 self.0.div_euclid(Self::MILLIS_PER_SEC)
388 }
389
390 #[must_use]
392 pub fn utc_date(self) -> Option<Date> {
393 Date::try_from_i64(self.0.div_euclid(SECONDS_PER_DAY * Self::MILLIS_PER_SEC))
394 }
395
396 fn from_wide_millis_saturating(millis: i128) -> Self {
397 match i64::try_from(millis) {
398 Ok(millis) => Self(millis),
399 Err(_) if millis.is_negative() => Self::MIN,
400 Err(_) => Self::MAX,
401 }
402 }
403}
404
405impl Add<Duration> for Timestamp {
406 type Output = Self;
407
408 fn add(self, duration: Duration) -> Self::Output {
409 Self::from_wide_millis_saturating(i128::from(self.0) + i128::from(duration.as_millis()))
410 }
411}
412
413impl AddAssign<Duration> for Timestamp {
414 fn add_assign(&mut self, duration: Duration) {
415 *self = *self + duration;
416 }
417}
418
419impl Display for Timestamp {
420 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
421 Display::fmt(&self.0, formatter)
422 }
423}
424
425impl From<i64> for Timestamp {
426 fn from(value: i64) -> Self {
427 Self(value)
428 }
429}
430
431impl Sub<Duration> for Timestamp {
432 type Output = Self;
433
434 fn sub(self, duration: Duration) -> Self::Output {
435 Self::from_wide_millis_saturating(i128::from(self.0) - i128::from(duration.as_millis()))
436 }
437}
438
439impl Sub for Timestamp {
440 type Output = Duration;
441
442 fn sub(self, other: Self) -> Self::Output {
443 if self.0 <= other.0 {
444 return Duration::ZERO;
445 }
446
447 Duration::from_millis(
448 u64::try_from(i128::from(self.0) - i128::from(other.0)).unwrap_or(u64::MAX),
449 )
450 }
451}
452
453impl SubAssign<Duration> for Timestamp {
454 fn sub_assign(&mut self, duration: Duration) {
455 *self = *self - duration;
456 }
457}
458
459fn parse_fractional_nanoseconds(bytes: &[u8]) -> Result<u32, TimeParseError> {
460 let mut value = 0_u32;
461 for byte in bytes.iter().take(9) {
462 let digit = byte
463 .checked_sub(b'0')
464 .filter(|digit| *digit <= 9)
465 .ok_or(TimeParseError::InvalidTimestamp)?;
466 value = value
467 .checked_mul(10)
468 .and_then(|current| current.checked_add(u32::from(digit)))
469 .ok_or(TimeParseError::InvalidTimestamp)?;
470 }
471 for _ in bytes.len().min(9)..9 {
472 value = value
473 .checked_mul(10)
474 .ok_or(TimeParseError::InvalidTimestamp)?;
475 }
476
477 Ok(value)
478}
479
480fn parse_offset(bytes: &[u8]) -> Result<(i8, u8, u8), TimeParseError> {
481 match bytes {
482 [b'Z'] => Ok((1, 0, 0)),
483 [sign @ (b'+' | b'-'), hour0, hour1, b':', minute0, minute1] => Ok((
484 if *sign == b'+' { 1 } else { -1 },
485 crate::date::two_digits(&[*hour0, *hour1]).ok_or(TimeParseError::InvalidTimestamp)?,
486 crate::date::two_digits(&[*minute0, *minute1])
487 .ok_or(TimeParseError::InvalidTimestamp)?,
488 )),
489 _ => Err(TimeParseError::InvalidTimestamp),
490 }
491}
492
493#[derive(Clone, Copy, Debug, Eq, PartialEq)]
495pub enum TimeParseError {
496 InvalidDuration,
498 InvalidTimestamp,
500}
501impl Display for TimeParseError {
502 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
503 f.write_str(match self {
504 Self::InvalidDuration => "invalid millisecond duration",
505 Self::InvalidTimestamp => "invalid Unix-millisecond timestamp",
506 })
507 }
508}
509impl std::error::Error for TimeParseError {}