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 MS_PER_MIN: u64 = 60 * Self::MS_PER_SEC;
40 const MS_PER_HOUR: u64 = 60 * Self::MS_PER_MIN;
41 const MS_PER_DAY: u64 = 24 * Self::MS_PER_HOUR;
42 const MS_PER_WEEK: u64 = 7 * Self::MS_PER_DAY;
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(minutes.saturating_mul(Self::MS_PER_MIN))
82 }
83
84 #[must_use]
86 pub const fn from_hours(hours: u64) -> Self {
87 Self(hours.saturating_mul(Self::MS_PER_HOUR))
88 }
89
90 #[must_use]
92 pub const fn from_days(days: u64) -> Self {
93 Self(days.saturating_mul(Self::MS_PER_DAY))
94 }
95
96 #[must_use]
98 pub const fn from_weeks(weeks: u64) -> Self {
99 Self(weeks.saturating_mul(Self::MS_PER_WEEK))
100 }
101
102 #[must_use]
104 pub const fn as_millis(self) -> u64 {
105 self.0
106 }
107
108 #[must_use]
110 pub const fn as_secs(self) -> u64 {
111 self.0 / Self::MS_PER_SEC
112 }
113
114 #[must_use]
116 pub const fn as_minutes(self) -> u64 {
117 self.0 / Self::MS_PER_MIN
118 }
119
120 #[must_use]
122 pub const fn as_hours(self) -> u64 {
123 self.0 / Self::MS_PER_HOUR
124 }
125
126 #[must_use]
128 pub const fn as_days(self) -> u64 {
129 self.0 / Self::MS_PER_DAY
130 }
131
132 #[must_use]
134 pub const fn as_weeks(self) -> u64 {
135 self.0 / Self::MS_PER_WEEK
136 }
137
138 pub fn parse_flexible(input: &str) -> Result<Self, TimeParseError> {
145 let (digits, multiplier) = if let Some(value) = input.strip_suffix("ms") {
146 (value, 1)
147 } else if let Some(value) = input.strip_suffix('s') {
148 (value, Self::MS_PER_SEC)
149 } else if let Some(value) = input.strip_suffix('m') {
150 (value, Self::MS_PER_MIN)
151 } else if let Some(value) = input.strip_suffix('h') {
152 (value, Self::MS_PER_HOUR)
153 } else if let Some(value) = input.strip_suffix('d') {
154 (value, Self::MS_PER_DAY)
155 } else {
156 (input, 1)
157 };
158 if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
159 return Err(TimeParseError::InvalidDuration);
160 }
161 let value = digits
162 .parse::<u64>()
163 .map_err(|_| TimeParseError::InvalidDuration)?;
164
165 value
166 .checked_mul(multiplier)
167 .map(Self)
168 .ok_or(TimeParseError::InvalidDuration)
169 }
170}
171
172impl Add for Duration {
173 type Output = Self;
174
175 fn add(self, other: Self) -> Self::Output {
176 Self(self.0.saturating_add(other.0))
177 }
178}
179
180impl AddAssign for Duration {
181 fn add_assign(&mut self, other: Self) {
182 self.0 = self.0.saturating_add(other.0);
183 }
184}
185
186impl From<u64> for Duration {
187 fn from(value: u64) -> Self {
188 Self(value)
189 }
190}
191
192impl Sub for Duration {
193 type Output = Self;
194
195 fn sub(self, other: Self) -> Self::Output {
196 Self(self.0.saturating_sub(other.0))
197 }
198}
199
200impl SubAssign for Duration {
201 fn sub_assign(&mut self, other: Self) {
202 self.0 = self.0.saturating_sub(other.0);
203 }
204}
205
206#[derive(
210 Clone,
211 Copy,
212 Debug,
213 Default,
214 Eq,
215 Hash,
216 Ord,
217 PartialEq,
218 PartialOrd,
219 serde::Serialize,
220 serde::Deserialize,
221)]
222#[serde(transparent)]
223#[repr(transparent)]
224pub struct Timestamp(i64);
225
226impl Timestamp {
227 #[must_use]
230 pub fn now() -> Self {
231 Self::EPOCH + Duration::from_nanos_truncating(crate::clock::time_ns())
232 }
233
234 pub const EPOCH: Self = Self(0);
236 pub const MIN: Self = Self(i64::MIN);
238 pub const MAX: Self = Self(i64::MAX);
240
241 const MILLIS_PER_SEC: i64 = 1_000;
242
243 #[must_use]
245 pub const fn from_secs(seconds: i64) -> Self {
246 Self(seconds.saturating_mul(Self::MILLIS_PER_SEC))
247 }
248
249 #[must_use]
251 pub const fn from_millis(millis: i64) -> Self {
252 Self(millis)
253 }
254
255 #[must_use]
257 pub fn try_from_u64(millis: u64) -> Option<Self> {
258 i64::try_from(millis).ok().map(Self)
259 }
260
261 #[must_use]
263 pub const fn from_micros(micros: i64) -> Self {
264 Self(micros.div_euclid(Self::MILLIS_PER_SEC))
265 }
266
267 #[must_use]
269 pub const fn from_nanos(nanos: i64) -> Self {
270 Self(nanos.div_euclid(1_000_000))
271 }
272
273 pub fn parse_rfc3339(input: &str) -> Result<Self, TimeParseError> {
280 let bytes = input.as_bytes();
281 if bytes.len() < 20
282 || bytes.get(10) != Some(&b'T')
283 || bytes.get(13) != Some(&b':')
284 || bytes.get(16) != Some(&b':')
285 {
286 return Err(TimeParseError::InvalidTimestamp);
287 }
288 let date = input
289 .get(..10)
290 .and_then(Date::parse)
291 .ok_or(TimeParseError::InvalidTimestamp)?;
292 let hour =
293 crate::date::two_digits(&bytes[11..13]).ok_or(TimeParseError::InvalidTimestamp)?;
294 let minute =
295 crate::date::two_digits(&bytes[14..16]).ok_or(TimeParseError::InvalidTimestamp)?;
296 let second =
297 crate::date::two_digits(&bytes[17..19]).ok_or(TimeParseError::InvalidTimestamp)?;
298
299 let mut cursor = 19;
300 let nanoseconds = if bytes.get(cursor) == Some(&b'.') {
301 cursor += 1;
302 let start = cursor;
303 while bytes.get(cursor).is_some_and(u8::is_ascii_digit) {
304 cursor += 1;
305 }
306 if cursor == start {
307 return Err(TimeParseError::InvalidTimestamp);
308 }
309
310 parse_fractional_nanoseconds(&bytes[start..cursor])?
311 } else {
312 0
313 };
314 let (sign, offset_hour, offset_minute) = parse_offset(&bytes[cursor..])?;
315 if hour > 23 || minute > 59 || second > 59 || offset_hour > 23 || offset_minute > 59 {
316 return Err(TimeParseError::InvalidTimestamp);
317 }
318 let local_seconds = i64::from(date.as_days_since_epoch()) * SECONDS_PER_DAY
322 + i64::from(hour) * 3_600
323 + i64::from(minute) * 60
324 + i64::from(second);
325 let offset_seconds =
326 i64::from(sign) * (i64::from(offset_hour) * 3_600 + i64::from(offset_minute) * 60);
327
328 Ok(Self(
329 (local_seconds - offset_seconds) * Self::MILLIS_PER_SEC
330 + i64::from(nanoseconds / 1_000_000),
331 ))
332 }
333
334 pub fn parse_flexible(input: &str) -> Result<Self, TimeParseError> {
340 input
341 .parse::<i64>()
342 .map(Self)
343 .or_else(|_| Self::parse_rfc3339(input))
344 }
345
346 #[must_use]
348 pub const fn as_millis(self) -> i64 {
349 self.0
350 }
351
352 #[must_use]
354 pub const fn as_secs(self) -> i64 {
355 self.0.div_euclid(Self::MILLIS_PER_SEC)
356 }
357
358 #[must_use]
360 pub fn utc_date(self) -> Option<Date> {
361 Date::try_from_i64(self.0.div_euclid(SECONDS_PER_DAY * Self::MILLIS_PER_SEC))
362 }
363
364 fn from_wide_millis_saturating(millis: i128) -> Self {
365 match i64::try_from(millis) {
366 Ok(millis) => Self(millis),
367 Err(_) if millis.is_negative() => Self::MIN,
368 Err(_) => Self::MAX,
369 }
370 }
371}
372
373impl Add<Duration> for Timestamp {
374 type Output = Self;
375
376 fn add(self, duration: Duration) -> Self::Output {
377 Self::from_wide_millis_saturating(i128::from(self.0) + i128::from(duration.as_millis()))
378 }
379}
380
381impl AddAssign<Duration> for Timestamp {
382 fn add_assign(&mut self, duration: Duration) {
383 *self = *self + duration;
384 }
385}
386
387impl Display for Timestamp {
388 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
389 Display::fmt(&self.0, formatter)
390 }
391}
392
393impl From<i64> for Timestamp {
394 fn from(value: i64) -> Self {
395 Self(value)
396 }
397}
398
399impl Sub<Duration> for Timestamp {
400 type Output = Self;
401
402 fn sub(self, duration: Duration) -> Self::Output {
403 Self::from_wide_millis_saturating(i128::from(self.0) - i128::from(duration.as_millis()))
404 }
405}
406
407impl Sub for Timestamp {
408 type Output = Duration;
409
410 fn sub(self, other: Self) -> Self::Output {
411 if self.0 <= other.0 {
412 return Duration::ZERO;
413 }
414
415 Duration::from_millis(
416 u64::try_from(i128::from(self.0) - i128::from(other.0)).unwrap_or(u64::MAX),
417 )
418 }
419}
420
421impl SubAssign<Duration> for Timestamp {
422 fn sub_assign(&mut self, duration: Duration) {
423 *self = *self - duration;
424 }
425}
426
427fn parse_fractional_nanoseconds(bytes: &[u8]) -> Result<u32, TimeParseError> {
428 let mut value = 0_u32;
429 for byte in bytes.iter().take(9) {
430 let digit = byte
431 .checked_sub(b'0')
432 .filter(|digit| *digit <= 9)
433 .ok_or(TimeParseError::InvalidTimestamp)?;
434 value = value
435 .checked_mul(10)
436 .and_then(|current| current.checked_add(u32::from(digit)))
437 .ok_or(TimeParseError::InvalidTimestamp)?;
438 }
439 for _ in bytes.len().min(9)..9 {
440 value = value
441 .checked_mul(10)
442 .ok_or(TimeParseError::InvalidTimestamp)?;
443 }
444
445 Ok(value)
446}
447
448fn parse_offset(bytes: &[u8]) -> Result<(i8, u8, u8), TimeParseError> {
449 match bytes {
450 [b'Z'] => Ok((1, 0, 0)),
451 [sign @ (b'+' | b'-'), hour0, hour1, b':', minute0, minute1] => Ok((
452 if *sign == b'+' { 1 } else { -1 },
453 crate::date::two_digits(&[*hour0, *hour1]).ok_or(TimeParseError::InvalidTimestamp)?,
454 crate::date::two_digits(&[*minute0, *minute1])
455 .ok_or(TimeParseError::InvalidTimestamp)?,
456 )),
457 _ => Err(TimeParseError::InvalidTimestamp),
458 }
459}
460
461#[derive(Clone, Copy, Debug, Eq, PartialEq)]
463pub enum TimeParseError {
464 InvalidDuration,
466 InvalidTimestamp,
468}
469impl Display for TimeParseError {
470 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
471 f.write_str(match self {
472 Self::InvalidDuration => "invalid millisecond duration",
473 Self::InvalidTimestamp => "invalid Unix-millisecond timestamp",
474 })
475 }
476}
477impl std::error::Error for TimeParseError {}