Skip to main content

icydb_schema/
time_atoms.rs

1//! Canonical millisecond-native time atoms.
2
3use std::{
4    fmt::{self, Display, Formatter},
5    ops::{Add, AddAssign, Sub, SubAssign},
6};
7
8use crate::TypeParseError;
9use candid::CandidType;
10use serde::{Deserialize, Deserializer, Serialize};
11use time::{Date as TimeDate, Month, PrimitiveDateTime, Time as TimeOfDay, UtcOffset};
12
13#[cfg(test)]
14mod tests;
15
16/// Canonical millisecond duration.
17#[derive(CandidType, Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
18#[repr(transparent)]
19pub struct Duration(u64);
20
21impl Duration {
22    /// Zero milliseconds.
23    pub const ZERO: Self = Self(0);
24    /// Minimum duration.
25    pub const MIN: Self = Self(u64::MIN);
26    /// Maximum duration.
27    pub const MAX: Self = Self(u64::MAX);
28
29    const MS_PER_SEC: u64 = 1_000;
30    const SECS_PER_MIN: u64 = 60;
31    const MINS_PER_HOUR: u64 = 60;
32    const HOURS_PER_DAY: u64 = 24;
33    const DAYS_PER_WEEK: u64 = 7;
34
35    /// Construct from milliseconds.
36    #[must_use]
37    pub const fn from_millis(millis: u64) -> Self {
38        Self(millis)
39    }
40
41    /// Convert nonnegative signed milliseconds.
42    #[must_use]
43    pub const fn try_from_i64(millis: i64) -> Option<Self> {
44        if millis < 0 {
45            None
46        } else {
47            Some(Self(millis.cast_unsigned()))
48        }
49    }
50
51    /// Construct from microseconds, truncating sub-millisecond precision.
52    #[must_use]
53    pub const fn from_micros_truncating(micros: u64) -> Self {
54        Self(micros / Self::MS_PER_SEC)
55    }
56
57    /// Construct from nanoseconds, truncating sub-millisecond precision.
58    #[must_use]
59    pub const fn from_nanos_truncating(nanos: u64) -> Self {
60        Self(nanos / 1_000_000)
61    }
62
63    /// Construct from seconds with saturation.
64    #[must_use]
65    pub const fn from_secs(seconds: u64) -> Self {
66        Self(seconds.saturating_mul(Self::MS_PER_SEC))
67    }
68
69    /// Construct from minutes with saturation.
70    #[must_use]
71    pub const fn from_minutes(minutes: u64) -> Self {
72        Self(
73            minutes
74                .saturating_mul(Self::SECS_PER_MIN)
75                .saturating_mul(Self::MS_PER_SEC),
76        )
77    }
78
79    /// Construct from hours with saturation.
80    #[must_use]
81    pub const fn from_hours(hours: u64) -> Self {
82        Self(
83            hours
84                .saturating_mul(Self::MINS_PER_HOUR)
85                .saturating_mul(Self::SECS_PER_MIN)
86                .saturating_mul(Self::MS_PER_SEC),
87        )
88    }
89
90    /// Construct from days with saturation.
91    #[must_use]
92    pub const fn from_days(days: u64) -> Self {
93        Self(
94            days.saturating_mul(Self::HOURS_PER_DAY)
95                .saturating_mul(Self::MINS_PER_HOUR)
96                .saturating_mul(Self::SECS_PER_MIN)
97                .saturating_mul(Self::MS_PER_SEC),
98        )
99    }
100
101    /// Construct from weeks with saturation.
102    #[must_use]
103    pub const fn from_weeks(weeks: u64) -> Self {
104        Self(
105            weeks
106                .saturating_mul(Self::DAYS_PER_WEEK)
107                .saturating_mul(Self::HOURS_PER_DAY)
108                .saturating_mul(Self::MINS_PER_HOUR)
109                .saturating_mul(Self::SECS_PER_MIN)
110                .saturating_mul(Self::MS_PER_SEC),
111        )
112    }
113
114    /// Return milliseconds.
115    #[must_use]
116    pub const fn as_millis(self) -> u64 {
117        self.0
118    }
119
120    /// Return whole seconds.
121    #[must_use]
122    pub const fn as_secs(self) -> u64 {
123        self.0 / Self::MS_PER_SEC
124    }
125
126    /// Return whole minutes.
127    #[must_use]
128    pub const fn as_minutes(self) -> u64 {
129        self.0 / (Self::SECS_PER_MIN * Self::MS_PER_SEC)
130    }
131
132    /// Return whole hours.
133    #[must_use]
134    pub const fn as_hours(self) -> u64 {
135        self.0 / (Self::MINS_PER_HOUR * Self::SECS_PER_MIN * Self::MS_PER_SEC)
136    }
137
138    /// Return whole days.
139    #[must_use]
140    pub const fn as_days(self) -> u64 {
141        self.0 / (Self::HOURS_PER_DAY * Self::MINS_PER_HOUR * Self::SECS_PER_MIN * Self::MS_PER_SEC)
142    }
143
144    /// Return whole weeks.
145    #[must_use]
146    pub const fn as_weeks(self) -> u64 {
147        self.0
148            / (Self::DAYS_PER_WEEK
149                * Self::HOURS_PER_DAY
150                * Self::MINS_PER_HOUR
151                * Self::SECS_PER_MIN
152                * Self::MS_PER_SEC)
153    }
154
155    /// Parse integer milliseconds or `ms`, `s`, `m`, `h`, or `d` suffixes.
156    ///
157    /// # Errors
158    ///
159    /// Returns [`TypeParseError::InvalidDuration`] for malformed or overflowing
160    /// input.
161    pub fn parse_flexible(input: &str) -> Result<Self, TypeParseError> {
162        let (digits, multiplier) = if let Some(value) = input.strip_suffix("ms") {
163            (value, 1)
164        } else if let Some(value) = input.strip_suffix('s') {
165            (value, Self::MS_PER_SEC)
166        } else if let Some(value) = input.strip_suffix('m') {
167            (value, Self::SECS_PER_MIN * Self::MS_PER_SEC)
168        } else if let Some(value) = input.strip_suffix('h') {
169            (
170                value,
171                Self::MINS_PER_HOUR * Self::SECS_PER_MIN * Self::MS_PER_SEC,
172            )
173        } else if let Some(value) = input.strip_suffix('d') {
174            (
175                value,
176                Self::HOURS_PER_DAY * Self::MINS_PER_HOUR * Self::SECS_PER_MIN * Self::MS_PER_SEC,
177            )
178        } else {
179            (input, 1)
180        };
181        if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
182            return Err(TypeParseError::InvalidDuration);
183        }
184        let value = digits
185            .parse::<u64>()
186            .map_err(|_| TypeParseError::InvalidDuration)?;
187        value
188            .checked_mul(multiplier)
189            .map(Self)
190            .ok_or(TypeParseError::InvalidDuration)
191    }
192}
193
194impl Add for Duration {
195    type Output = Self;
196
197    fn add(self, other: Self) -> Self::Output {
198        Self(self.0.saturating_add(other.0))
199    }
200}
201
202impl AddAssign for Duration {
203    fn add_assign(&mut self, other: Self) {
204        self.0 = self.0.saturating_add(other.0);
205    }
206}
207
208impl<'de> Deserialize<'de> for Duration {
209    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
210    where
211        D: Deserializer<'de>,
212    {
213        struct DurationVisitor;
214
215        impl serde::de::Visitor<'_> for DurationVisitor {
216            type Value = Duration;
217
218            fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
219                formatter.write_str("milliseconds or duration string")
220            }
221
222            fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
223            where
224                E: serde::de::Error,
225            {
226                Duration::try_from_i64(value)
227                    .ok_or_else(|| E::custom("duration must be non-negative"))
228            }
229
230            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
231                Ok(Duration::from_millis(value))
232            }
233
234            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
235            where
236                E: serde::de::Error,
237            {
238                Duration::parse_flexible(value).map_err(E::custom)
239            }
240        }
241
242        deserializer.deserialize_any(DurationVisitor)
243    }
244}
245
246impl From<u64> for Duration {
247    fn from(value: u64) -> Self {
248        Self(value)
249    }
250}
251
252impl Serialize for Duration {
253    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
254    where
255        S: serde::Serializer,
256    {
257        serializer.serialize_u64(self.0)
258    }
259}
260
261impl Sub for Duration {
262    type Output = Self;
263
264    fn sub(self, other: Self) -> Self::Output {
265        Self(self.0.saturating_sub(other.0))
266    }
267}
268
269impl SubAssign for Duration {
270    fn sub_assign(&mut self, other: Self) {
271        self.0 = self.0.saturating_sub(other.0);
272    }
273}
274
275/// Canonical Unix-millisecond timestamp.
276#[derive(CandidType, Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
277#[repr(transparent)]
278pub struct Timestamp(i64);
279
280impl Timestamp {
281    /// Unix epoch.
282    pub const EPOCH: Self = Self(0);
283    /// Minimum timestamp.
284    pub const MIN: Self = Self(i64::MIN);
285    /// Maximum timestamp.
286    pub const MAX: Self = Self(i64::MAX);
287
288    const MILLIS_PER_SEC: i64 = 1_000;
289
290    /// Construct from seconds with saturation.
291    #[must_use]
292    pub const fn from_secs(seconds: i64) -> Self {
293        Self(seconds.saturating_mul(Self::MILLIS_PER_SEC))
294    }
295
296    /// Construct from milliseconds.
297    #[must_use]
298    pub const fn from_millis(millis: i64) -> Self {
299        Self(millis)
300    }
301
302    /// Convert signed milliseconds.
303    #[must_use]
304    pub const fn try_from_i64(millis: i64) -> Option<Self> {
305        Some(Self(millis))
306    }
307
308    /// Convert unsigned milliseconds.
309    #[must_use]
310    pub fn try_from_u64(millis: u64) -> Option<Self> {
311        i64::try_from(millis).ok().map(Self)
312    }
313
314    /// Construct from microseconds, flooring to Unix milliseconds.
315    #[must_use]
316    pub const fn from_micros(micros: i64) -> Self {
317        Self(micros.div_euclid(Self::MILLIS_PER_SEC))
318    }
319
320    /// Construct from nanoseconds, flooring to Unix milliseconds.
321    #[must_use]
322    pub const fn from_nanos(nanos: i64) -> Self {
323        Self(nanos.div_euclid(1_000_000))
324    }
325
326    /// Parse strict RFC3339 text.
327    ///
328    /// # Errors
329    ///
330    /// Returns [`TypeParseError::InvalidTimestamp`] for malformed or
331    /// out-of-range input.
332    pub fn parse_rfc3339(input: &str) -> Result<Self, TypeParseError> {
333        let bytes = input.as_bytes();
334        if bytes.len() < 20
335            || bytes.get(4) != Some(&b'-')
336            || bytes.get(7) != Some(&b'-')
337            || bytes.get(10) != Some(&b'T')
338            || bytes.get(13) != Some(&b':')
339            || bytes.get(16) != Some(&b':')
340        {
341            return Err(TypeParseError::InvalidTimestamp);
342        }
343        let year = parse_i32(&bytes[0..4])?;
344        let month = Month::try_from(parse_u8(&bytes[5..7])?)
345            .map_err(|_| TypeParseError::InvalidTimestamp)?;
346        let day = parse_u8(&bytes[8..10])?;
347        let hour = parse_u8(&bytes[11..13])?;
348        let minute = parse_u8(&bytes[14..16])?;
349        let second = parse_u8(&bytes[17..19])?;
350
351        let mut cursor = 19;
352        let nanoseconds = if bytes.get(cursor) == Some(&b'.') {
353            cursor += 1;
354            let start = cursor;
355            while bytes.get(cursor).is_some_and(u8::is_ascii_digit) {
356                cursor += 1;
357            }
358            if cursor == start {
359                return Err(TypeParseError::InvalidTimestamp);
360            }
361            parse_fractional_nanoseconds(&bytes[start..cursor])?
362        } else {
363            0
364        };
365        let (sign, offset_hour, offset_minute) = parse_offset(&bytes[cursor..])?;
366        let date = TimeDate::from_calendar_date(year, month, day)
367            .map_err(|_| TypeParseError::InvalidTimestamp)?;
368        let time = TimeOfDay::from_hms_nano(hour, minute, second, nanoseconds)
369            .map_err(|_| TypeParseError::InvalidTimestamp)?;
370        let offset = UtcOffset::from_hms(
371            sign * i8::try_from(offset_hour).unwrap_or(i8::MAX),
372            sign * i8::try_from(offset_minute).unwrap_or(i8::MAX),
373            0,
374        )
375        .map_err(|_| TypeParseError::InvalidTimestamp)?;
376        let millis = PrimitiveDateTime::new(date, time)
377            .assume_offset(offset)
378            .unix_timestamp_nanos()
379            .div_euclid(1_000_000);
380        i64::try_from(millis)
381            .map(Self)
382            .map_err(|_| TypeParseError::InvalidTimestamp)
383    }
384
385    /// Parse integer milliseconds or strict RFC3339 text.
386    ///
387    /// # Errors
388    ///
389    /// Returns a typed timestamp parse error.
390    pub fn parse_flexible(input: &str) -> Result<Self, TypeParseError> {
391        input
392            .parse::<i64>()
393            .map(Self)
394            .or_else(|_| Self::parse_rfc3339(input))
395    }
396
397    /// Return Unix milliseconds.
398    #[must_use]
399    pub const fn as_millis(self) -> i64 {
400        self.0
401    }
402
403    /// Return whole Unix seconds.
404    #[must_use]
405    pub const fn as_secs(self) -> i64 {
406        self.0.div_euclid(Self::MILLIS_PER_SEC)
407    }
408
409    fn from_wide_millis_saturating(millis: i128) -> Self {
410        match i64::try_from(millis) {
411            Ok(millis) => Self(millis),
412            Err(_) if millis.is_negative() => Self::MIN,
413            Err(_) => Self::MAX,
414        }
415    }
416}
417
418impl Add<Duration> for Timestamp {
419    type Output = Self;
420
421    fn add(self, duration: Duration) -> Self::Output {
422        Self::from_wide_millis_saturating(i128::from(self.0) + i128::from(duration.as_millis()))
423    }
424}
425
426impl AddAssign<Duration> for Timestamp {
427    fn add_assign(&mut self, duration: Duration) {
428        *self = *self + duration;
429    }
430}
431
432impl<'de> Deserialize<'de> for Timestamp {
433    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
434    where
435        D: Deserializer<'de>,
436    {
437        struct TimestampVisitor;
438
439        impl serde::de::Visitor<'_> for TimestampVisitor {
440            type Value = Timestamp;
441
442            fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
443                formatter.write_str("unix millis or RFC3339 timestamp")
444            }
445
446            fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> {
447                Ok(Timestamp::from_millis(value))
448            }
449
450            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
451            where
452                E: serde::de::Error,
453            {
454                Timestamp::try_from_u64(value)
455                    .ok_or_else(|| E::custom("unix millis exceeds i64 timestamp range"))
456            }
457
458            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
459            where
460                E: serde::de::Error,
461            {
462                Timestamp::parse_flexible(value).map_err(E::custom)
463            }
464        }
465
466        deserializer.deserialize_any(TimestampVisitor)
467    }
468}
469
470impl Display for Timestamp {
471    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
472        Display::fmt(&self.0, formatter)
473    }
474}
475
476impl From<i64> for Timestamp {
477    fn from(value: i64) -> Self {
478        Self(value)
479    }
480}
481
482impl Serialize for Timestamp {
483    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
484    where
485        S: serde::Serializer,
486    {
487        serializer.serialize_i64(self.0)
488    }
489}
490
491impl Sub<Duration> for Timestamp {
492    type Output = Self;
493
494    fn sub(self, duration: Duration) -> Self::Output {
495        Self::from_wide_millis_saturating(i128::from(self.0) - i128::from(duration.as_millis()))
496    }
497}
498
499impl Sub for Timestamp {
500    type Output = Duration;
501
502    fn sub(self, other: Self) -> Self::Output {
503        if self.0 <= other.0 {
504            return Duration::ZERO;
505        }
506        Duration::from_millis(
507            u64::try_from(i128::from(self.0) - i128::from(other.0)).unwrap_or(u64::MAX),
508        )
509    }
510}
511
512impl SubAssign<Duration> for Timestamp {
513    fn sub_assign(&mut self, duration: Duration) {
514        *self = *self - duration;
515    }
516}
517
518fn parse_i32(bytes: &[u8]) -> Result<i32, TypeParseError> {
519    bytes
520        .iter()
521        .try_fold(0_i32, |value, byte| {
522            byte.checked_sub(b'0')
523                .filter(|digit| *digit <= 9)
524                .and_then(|digit| value.checked_mul(10)?.checked_add(i32::from(digit)))
525        })
526        .ok_or(TypeParseError::InvalidTimestamp)
527}
528
529fn parse_u8(bytes: &[u8]) -> Result<u8, TypeParseError> {
530    bytes
531        .iter()
532        .try_fold(0_u8, |value, byte| {
533            byte.checked_sub(b'0')
534                .filter(|digit| *digit <= 9)
535                .and_then(|digit| value.checked_mul(10)?.checked_add(digit))
536        })
537        .ok_or(TypeParseError::InvalidTimestamp)
538}
539
540fn parse_fractional_nanoseconds(bytes: &[u8]) -> Result<u32, TypeParseError> {
541    let mut value = 0_u32;
542    for byte in bytes.iter().take(9) {
543        let digit = byte
544            .checked_sub(b'0')
545            .filter(|digit| *digit <= 9)
546            .ok_or(TypeParseError::InvalidTimestamp)?;
547        value = value
548            .checked_mul(10)
549            .and_then(|current| current.checked_add(u32::from(digit)))
550            .ok_or(TypeParseError::InvalidTimestamp)?;
551    }
552    for _ in bytes.len().min(9)..9 {
553        value = value
554            .checked_mul(10)
555            .ok_or(TypeParseError::InvalidTimestamp)?;
556    }
557    Ok(value)
558}
559
560fn parse_offset(bytes: &[u8]) -> Result<(i8, u8, u8), TypeParseError> {
561    match bytes {
562        [b'Z'] => Ok((1, 0, 0)),
563        [sign @ (b'+' | b'-'), hour0, hour1, b':', minute0, minute1] => Ok((
564            if *sign == b'+' { 1 } else { -1 },
565            parse_u8(&[*hour0, *hour1])?,
566            parse_u8(&[*minute0, *minute1])?,
567        )),
568        _ => Err(TypeParseError::InvalidTimestamp),
569    }
570}