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 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    /// 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(minutes.saturating_mul(Self::MS_PER_MIN))
82    }
83
84    /// Construct from hours with saturation.
85    #[must_use]
86    pub const fn from_hours(hours: u64) -> Self {
87        Self(hours.saturating_mul(Self::MS_PER_HOUR))
88    }
89
90    /// Construct from days with saturation.
91    #[must_use]
92    pub const fn from_days(days: u64) -> Self {
93        Self(days.saturating_mul(Self::MS_PER_DAY))
94    }
95
96    /// Construct from weeks with saturation.
97    #[must_use]
98    pub const fn from_weeks(weeks: u64) -> Self {
99        Self(weeks.saturating_mul(Self::MS_PER_WEEK))
100    }
101
102    /// Return milliseconds.
103    #[must_use]
104    pub const fn as_millis(self) -> u64 {
105        self.0
106    }
107
108    /// Return whole seconds.
109    #[must_use]
110    pub const fn as_secs(self) -> u64 {
111        self.0 / Self::MS_PER_SEC
112    }
113
114    /// Return whole minutes.
115    #[must_use]
116    pub const fn as_minutes(self) -> u64 {
117        self.0 / Self::MS_PER_MIN
118    }
119
120    /// Return whole hours.
121    #[must_use]
122    pub const fn as_hours(self) -> u64 {
123        self.0 / Self::MS_PER_HOUR
124    }
125
126    /// Return whole days.
127    #[must_use]
128    pub const fn as_days(self) -> u64 {
129        self.0 / Self::MS_PER_DAY
130    }
131
132    /// Return whole weeks.
133    #[must_use]
134    pub const fn as_weeks(self) -> u64 {
135        self.0 / Self::MS_PER_WEEK
136    }
137
138    /// Parse integer milliseconds or `ms`, `s`, `m`, `h`, or `d` suffixes.
139    ///
140    /// # Errors
141    ///
142    /// Returns [`TimeParseError::InvalidDuration`] for malformed or overflowing
143    /// input.
144    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/// Signed Unix-millisecond timestamp, including instants before 1970.
207/// Sub-millisecond conversions floor; arithmetic operators saturate only after
208/// the complete wide operation.
209#[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    /// Current Unix time, truncated to whole milliseconds.
228    /// Uses IC execution time on Wasm and the system clock on native hosts.
229    #[must_use]
230    pub fn now() -> Self {
231        Self::EPOCH + Duration::from_nanos_truncating(crate::clock::time_ns())
232    }
233
234    /// Unix epoch.
235    pub const EPOCH: Self = Self(0);
236    /// Minimum timestamp.
237    pub const MIN: Self = Self(i64::MIN);
238    /// Maximum timestamp.
239    pub const MAX: Self = Self(i64::MAX);
240
241    const MILLIS_PER_SEC: i64 = 1_000;
242
243    /// Construct from seconds with saturation.
244    #[must_use]
245    pub const fn from_secs(seconds: i64) -> Self {
246        Self(seconds.saturating_mul(Self::MILLIS_PER_SEC))
247    }
248
249    /// Construct from milliseconds.
250    #[must_use]
251    pub const fn from_millis(millis: i64) -> Self {
252        Self(millis)
253    }
254
255    /// Convert unsigned milliseconds.
256    #[must_use]
257    pub fn try_from_u64(millis: u64) -> Option<Self> {
258        i64::try_from(millis).ok().map(Self)
259    }
260
261    /// Construct from microseconds, flooring to Unix milliseconds.
262    #[must_use]
263    pub const fn from_micros(micros: i64) -> Self {
264        Self(micros.div_euclid(Self::MILLIS_PER_SEC))
265    }
266
267    /// Construct from nanoseconds, flooring to Unix milliseconds.
268    #[must_use]
269    pub const fn from_nanos(nanos: i64) -> Self {
270        Self(nanos.div_euclid(1_000_000))
271    }
272
273    /// Parse strict RFC3339 text.
274    ///
275    /// # Errors
276    ///
277    /// Returns [`TimeParseError::InvalidTimestamp`] for malformed or
278    /// out-of-range input.
279    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        // Four-digit calendar years and a sub-day offset fit comfortably in i64
319        // milliseconds. The fractional contribution is nonnegative, preserving
320        // floor semantics even for instants before the Unix epoch.
321        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    /// Parse integer milliseconds or strict RFC3339 text.
335    ///
336    /// # Errors
337    ///
338    /// Returns a typed timestamp parse error.
339    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    /// Return Unix milliseconds.
347    #[must_use]
348    pub const fn as_millis(self) -> i64 {
349        self.0
350    }
351
352    /// Return whole Unix seconds.
353    #[must_use]
354    pub const fn as_secs(self) -> i64 {
355        self.0.div_euclid(Self::MILLIS_PER_SEC)
356    }
357
358    /// The UTC calendar day containing this instant, or `None` outside years 0000–9999.
359    #[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/// Invalid or out-of-range human-readable time input.
462#[derive(Clone, Copy, Debug, Eq, PartialEq)]
463pub enum TimeParseError {
464    /// Duration text or its scaled millisecond value was invalid.
465    InvalidDuration,
466    /// Timestamp text or its components were invalid.
467    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 {}