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