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
43 #[must_use]
45 pub const fn from_millis(millis: u64) -> Self {
46 Self(millis)
47 }
48
49 #[must_use]
51 pub const fn try_from_i64(millis: i64) -> Option<Self> {
52 if millis < 0 {
53 None
54 } else {
55 Some(Self(millis.cast_unsigned()))
56 }
57 }
58
59 #[must_use]
61 pub const fn from_micros_truncating(micros: u64) -> Self {
62 Self(micros / Self::MS_PER_SEC)
63 }
64
65 #[must_use]
67 pub const fn from_nanos_truncating(nanos: u64) -> Self {
68 Self(nanos / 1_000_000)
69 }
70
71 #[must_use]
73 pub const fn from_secs(seconds: u64) -> Self {
74 Self(seconds.saturating_mul(Self::MS_PER_SEC))
75 }
76
77 #[must_use]
79 pub const fn as_millis(self) -> u64 {
80 self.0
81 }
82
83 #[must_use]
85 pub const fn as_secs(self) -> u64 {
86 self.0 / Self::MS_PER_SEC
87 }
88
89 pub fn parse_flexible(input: &str) -> Result<Self, TimeParseError> {
96 let (digits, multiplier) = if let Some(value) = input.strip_suffix("ms") {
97 (value, 1)
98 } else if let Some(value) = input.strip_suffix('s') {
99 (value, Self::MS_PER_SEC)
100 } else if let Some(value) = input.strip_suffix('m') {
101 (value, Self::MS_PER_MIN)
102 } else if let Some(value) = input.strip_suffix('h') {
103 (value, Self::MS_PER_HOUR)
104 } else if let Some(value) = input.strip_suffix('d') {
105 (value, Self::MS_PER_DAY)
106 } else {
107 (input, 1)
108 };
109 if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
110 return Err(TimeParseError::InvalidDuration);
111 }
112 let value = digits
113 .parse::<u64>()
114 .map_err(|_| TimeParseError::InvalidDuration)?;
115
116 value
117 .checked_mul(multiplier)
118 .map(Self)
119 .ok_or(TimeParseError::InvalidDuration)
120 }
121}
122
123impl Add for Duration {
124 type Output = Self;
125
126 fn add(self, other: Self) -> Self::Output {
127 Self(self.0.saturating_add(other.0))
128 }
129}
130
131impl AddAssign for Duration {
132 fn add_assign(&mut self, other: Self) {
133 self.0 = self.0.saturating_add(other.0);
134 }
135}
136
137impl From<u64> for Duration {
138 fn from(value: u64) -> Self {
139 Self(value)
140 }
141}
142
143impl Sub for Duration {
144 type Output = Self;
145
146 fn sub(self, other: Self) -> Self::Output {
147 Self(self.0.saturating_sub(other.0))
148 }
149}
150
151impl SubAssign for Duration {
152 fn sub_assign(&mut self, other: Self) {
153 self.0 = self.0.saturating_sub(other.0);
154 }
155}
156
157#[derive(
161 Clone,
162 Copy,
163 Debug,
164 Default,
165 Eq,
166 Hash,
167 Ord,
168 PartialEq,
169 PartialOrd,
170 serde::Serialize,
171 serde::Deserialize,
172)]
173#[serde(transparent)]
174#[repr(transparent)]
175pub struct Timestamp(i64);
176
177impl Timestamp {
178 #[must_use]
181 pub fn now() -> Self {
182 Self::EPOCH + Duration::from_nanos_truncating(crate::clock::time_ns())
183 }
184
185 pub const EPOCH: Self = Self(0);
187 pub const MIN: Self = Self(i64::MIN);
189 pub const MAX: Self = Self(i64::MAX);
191
192 const MILLIS_PER_SEC: i64 = 1_000;
193
194 #[must_use]
196 pub const fn from_secs(seconds: i64) -> Self {
197 Self(seconds.saturating_mul(Self::MILLIS_PER_SEC))
198 }
199
200 #[must_use]
202 pub const fn from_millis(millis: i64) -> Self {
203 Self(millis)
204 }
205
206 #[must_use]
208 pub fn try_from_u64(millis: u64) -> Option<Self> {
209 i64::try_from(millis).ok().map(Self)
210 }
211
212 #[must_use]
214 pub const fn from_micros(micros: i64) -> Self {
215 Self(micros.div_euclid(Self::MILLIS_PER_SEC))
216 }
217
218 #[must_use]
220 pub const fn from_nanos(nanos: i64) -> Self {
221 Self(nanos.div_euclid(1_000_000))
222 }
223
224 pub fn parse_rfc3339(input: &str) -> Result<Self, TimeParseError> {
231 let bytes = input.as_bytes();
232 if bytes.len() < 20
233 || bytes.get(10) != Some(&b'T')
234 || bytes.get(13) != Some(&b':')
235 || bytes.get(16) != Some(&b':')
236 {
237 return Err(TimeParseError::InvalidTimestamp);
238 }
239 let date = input
240 .get(..10)
241 .and_then(Date::parse)
242 .ok_or(TimeParseError::InvalidTimestamp)?;
243 let hour =
244 crate::date::two_digits(&bytes[11..13]).ok_or(TimeParseError::InvalidTimestamp)?;
245 let minute =
246 crate::date::two_digits(&bytes[14..16]).ok_or(TimeParseError::InvalidTimestamp)?;
247 let second =
248 crate::date::two_digits(&bytes[17..19]).ok_or(TimeParseError::InvalidTimestamp)?;
249
250 let mut cursor = 19;
251 let nanoseconds = if bytes.get(cursor) == Some(&b'.') {
252 cursor += 1;
253 let start = cursor;
254 while bytes.get(cursor).is_some_and(u8::is_ascii_digit) {
255 cursor += 1;
256 }
257 if cursor == start {
258 return Err(TimeParseError::InvalidTimestamp);
259 }
260
261 parse_fractional_nanoseconds(&bytes[start..cursor])?
262 } else {
263 0
264 };
265 let (sign, offset_hour, offset_minute) = parse_offset(&bytes[cursor..])?;
266 if hour > 23 || minute > 59 || second > 59 || offset_hour > 23 || offset_minute > 59 {
267 return Err(TimeParseError::InvalidTimestamp);
268 }
269 let local_seconds = i64::from(date.as_days_since_epoch()) * SECONDS_PER_DAY
273 + i64::from(hour) * 3_600
274 + i64::from(minute) * 60
275 + i64::from(second);
276 let offset_seconds =
277 i64::from(sign) * (i64::from(offset_hour) * 3_600 + i64::from(offset_minute) * 60);
278
279 Ok(Self(
280 (local_seconds - offset_seconds) * Self::MILLIS_PER_SEC
281 + i64::from(nanoseconds / 1_000_000),
282 ))
283 }
284
285 pub fn parse_flexible(input: &str) -> Result<Self, TimeParseError> {
291 input
292 .parse::<i64>()
293 .map(Self)
294 .or_else(|_| Self::parse_rfc3339(input))
295 }
296
297 #[must_use]
299 pub const fn as_millis(self) -> i64 {
300 self.0
301 }
302
303 #[must_use]
305 pub const fn as_secs(self) -> i64 {
306 self.0.div_euclid(Self::MILLIS_PER_SEC)
307 }
308
309 #[must_use]
311 pub fn utc_date(self) -> Option<Date> {
312 Date::try_from_i64(self.0.div_euclid(SECONDS_PER_DAY * Self::MILLIS_PER_SEC))
313 }
314
315 fn from_wide_millis_saturating(millis: i128) -> Self {
316 match i64::try_from(millis) {
317 Ok(millis) => Self(millis),
318 Err(_) if millis.is_negative() => Self::MIN,
319 Err(_) => Self::MAX,
320 }
321 }
322}
323
324impl Add<Duration> for Timestamp {
325 type Output = Self;
326
327 fn add(self, duration: Duration) -> Self::Output {
328 Self::from_wide_millis_saturating(i128::from(self.0) + i128::from(duration.as_millis()))
329 }
330}
331
332impl AddAssign<Duration> for Timestamp {
333 fn add_assign(&mut self, duration: Duration) {
334 *self = *self + duration;
335 }
336}
337
338impl Display for Timestamp {
339 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
340 Display::fmt(&self.0, formatter)
341 }
342}
343
344impl From<i64> for Timestamp {
345 fn from(value: i64) -> Self {
346 Self(value)
347 }
348}
349
350impl Sub<Duration> for Timestamp {
351 type Output = Self;
352
353 fn sub(self, duration: Duration) -> Self::Output {
354 Self::from_wide_millis_saturating(i128::from(self.0) - i128::from(duration.as_millis()))
355 }
356}
357
358impl Sub for Timestamp {
359 type Output = Duration;
360
361 fn sub(self, other: Self) -> Self::Output {
362 if self.0 <= other.0 {
363 return Duration::ZERO;
364 }
365
366 Duration::from_millis(
367 u64::try_from(i128::from(self.0) - i128::from(other.0)).unwrap_or(u64::MAX),
368 )
369 }
370}
371
372impl SubAssign<Duration> for Timestamp {
373 fn sub_assign(&mut self, duration: Duration) {
374 *self = *self - duration;
375 }
376}
377
378fn parse_fractional_nanoseconds(bytes: &[u8]) -> Result<u32, TimeParseError> {
379 let mut value = 0_u32;
380 for byte in bytes.iter().take(9) {
381 let digit = byte
382 .checked_sub(b'0')
383 .filter(|digit| *digit <= 9)
384 .ok_or(TimeParseError::InvalidTimestamp)?;
385 value = value
386 .checked_mul(10)
387 .and_then(|current| current.checked_add(u32::from(digit)))
388 .ok_or(TimeParseError::InvalidTimestamp)?;
389 }
390 for _ in bytes.len().min(9)..9 {
391 value = value
392 .checked_mul(10)
393 .ok_or(TimeParseError::InvalidTimestamp)?;
394 }
395
396 Ok(value)
397}
398
399fn parse_offset(bytes: &[u8]) -> Result<(i8, u8, u8), TimeParseError> {
400 match bytes {
401 [b'Z'] => Ok((1, 0, 0)),
402 [sign @ (b'+' | b'-'), hour0, hour1, b':', minute0, minute1] => Ok((
403 if *sign == b'+' { 1 } else { -1 },
404 crate::date::two_digits(&[*hour0, *hour1]).ok_or(TimeParseError::InvalidTimestamp)?,
405 crate::date::two_digits(&[*minute0, *minute1])
406 .ok_or(TimeParseError::InvalidTimestamp)?,
407 )),
408 _ => Err(TimeParseError::InvalidTimestamp),
409 }
410}
411
412#[derive(Clone, Copy, Debug, Eq, PartialEq)]
414pub enum TimeParseError {
415 InvalidDuration,
417 InvalidTimestamp,
419}
420impl Display for TimeParseError {
421 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
422 f.write_str(match self {
423 Self::InvalidDuration => "invalid millisecond duration",
424 Self::InvalidTimestamp => "invalid Unix-millisecond timestamp",
425 })
426 }
427}
428impl std::error::Error for TimeParseError {}