Skip to main content

ic_db/
time.rs

1//! Millisecond value semantics adapted from frozen IcyDB 6d421e3.
2//! Serde carries the underlying millisecond counts.
3
4use std::{
5    fmt::{self, Display, Formatter},
6    ops::{Add, AddAssign, Sub, SubAssign},
7};
8
9use crate::{Date, date::SECONDS_PER_DAY};
10
11/// Nonnegative millisecond duration. Constructors from larger units and arithmetic
12/// operators saturate; text parsing refuses overflow. No clock or timer is owned.
13#[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    /// Zero milliseconds.
32    pub const ZERO: Self = Self(0);
33    /// Minimum duration.
34    pub const MIN: Self = Self(u64::MIN);
35    /// Maximum duration.
36    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    /// Construct from milliseconds.
45    #[must_use]
46    pub const fn from_millis(millis: u64) -> Self {
47        Self(millis)
48    }
49
50    /// Convert nonnegative signed milliseconds.
51    #[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    /// Construct from microseconds, truncating sub-millisecond precision.
61    #[must_use]
62    pub const fn from_micros_truncating(micros: u64) -> Self {
63        Self(micros / Self::MS_PER_SEC)
64    }
65
66    /// Construct from nanoseconds, truncating sub-millisecond precision.
67    #[must_use]
68    pub const fn from_nanos_truncating(nanos: u64) -> Self {
69        Self(nanos / 1_000_000)
70    }
71
72    /// Construct from seconds with saturation.
73    #[must_use]
74    pub const fn from_secs(seconds: u64) -> Self {
75        Self(seconds.saturating_mul(Self::MS_PER_SEC))
76    }
77
78    /// Construct from minutes with saturation.
79    #[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    /// Construct from hours with saturation.
89    #[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    /// Construct from days with saturation.
100    #[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    /// Construct from weeks with saturation.
111    #[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    /// Return milliseconds.
124    #[must_use]
125    pub const fn as_millis(self) -> u64 {
126        self.0
127    }
128
129    /// Return whole seconds.
130    #[must_use]
131    pub const fn as_secs(self) -> u64 {
132        self.0 / Self::MS_PER_SEC
133    }
134
135    /// Return whole minutes.
136    #[must_use]
137    pub const fn as_minutes(self) -> u64 {
138        self.0 / (Self::SECS_PER_MIN * Self::MS_PER_SEC)
139    }
140
141    /// Return whole hours.
142    #[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    /// Return whole days.
148    #[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    /// Return whole weeks.
154    #[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    /// Parse integer milliseconds or `ms`, `s`, `m`, `h`, or `d` suffixes.
165    ///
166    /// # Errors
167    ///
168    /// Returns [`TimeParseError::InvalidDuration`] for malformed or overflowing
169    /// input.
170    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/// Signed Unix-millisecond timestamp, including instants before 1970.
239/// Sub-millisecond conversions floor; arithmetic operators saturate only after
240/// the complete wide operation.
241#[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    /// Current Unix time, truncated to whole milliseconds.
260    /// Uses IC execution time on Wasm and the system clock on native hosts.
261    #[must_use]
262    pub fn now() -> Self {
263        Self::EPOCH + Duration::from_nanos_truncating(crate::clock::time_ns())
264    }
265
266    /// Unix epoch.
267    pub const EPOCH: Self = Self(0);
268    /// Minimum timestamp.
269    pub const MIN: Self = Self(i64::MIN);
270    /// Maximum timestamp.
271    pub const MAX: Self = Self(i64::MAX);
272
273    const MILLIS_PER_SEC: i64 = 1_000;
274
275    /// Construct from seconds with saturation.
276    #[must_use]
277    pub const fn from_secs(seconds: i64) -> Self {
278        Self(seconds.saturating_mul(Self::MILLIS_PER_SEC))
279    }
280
281    /// Construct from milliseconds.
282    #[must_use]
283    pub const fn from_millis(millis: i64) -> Self {
284        Self(millis)
285    }
286
287    /// Convert unsigned milliseconds.
288    #[must_use]
289    pub fn try_from_u64(millis: u64) -> Option<Self> {
290        i64::try_from(millis).ok().map(Self)
291    }
292
293    /// Construct from microseconds, flooring to Unix milliseconds.
294    #[must_use]
295    pub const fn from_micros(micros: i64) -> Self {
296        Self(micros.div_euclid(Self::MILLIS_PER_SEC))
297    }
298
299    /// Construct from nanoseconds, flooring to Unix milliseconds.
300    #[must_use]
301    pub const fn from_nanos(nanos: i64) -> Self {
302        Self(nanos.div_euclid(1_000_000))
303    }
304
305    /// Parse strict RFC3339 text.
306    ///
307    /// # Errors
308    ///
309    /// Returns [`TimeParseError::InvalidTimestamp`] for malformed or
310    /// out-of-range input.
311    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        // Four-digit calendar years and a sub-day offset fit comfortably in i64
351        // milliseconds. The fractional contribution is nonnegative, preserving
352        // floor semantics even for instants before the Unix epoch.
353        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    /// Parse integer milliseconds or strict RFC3339 text.
367    ///
368    /// # Errors
369    ///
370    /// Returns a typed timestamp parse error.
371    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    /// Return Unix milliseconds.
379    #[must_use]
380    pub const fn as_millis(self) -> i64 {
381        self.0
382    }
383
384    /// Return whole Unix seconds.
385    #[must_use]
386    pub const fn as_secs(self) -> i64 {
387        self.0.div_euclid(Self::MILLIS_PER_SEC)
388    }
389
390    /// The UTC calendar day containing this instant, or `None` outside years 0000–9999.
391    #[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/// Invalid or out-of-range human-readable time input.
494#[derive(Clone, Copy, Debug, Eq, PartialEq)]
495pub enum TimeParseError {
496    /// Duration text or its scaled millisecond value was invalid.
497    InvalidDuration,
498    /// Timestamp text or its components were invalid.
499    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 {}