Skip to main content

ic_db/
time.rs

1//! Millisecond value semantics adapted from frozen IcyDB 6d421e3.
2//! No clock, managed-field policy or transport serialization.
3
4use std::{
5    fmt::{self, Display, Formatter},
6    ops::{Add, AddAssign, Sub, SubAssign},
7};
8
9use crate::Date;
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(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
14#[repr(transparent)]
15pub struct Duration(u64);
16
17impl Duration {
18    /// Zero milliseconds.
19    pub const ZERO: Self = Self(0);
20    /// Minimum duration.
21    pub const MIN: Self = Self(u64::MIN);
22    /// Maximum duration.
23    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    /// Construct from milliseconds.
32    #[must_use]
33    pub const fn from_millis(millis: u64) -> Self {
34        Self(millis)
35    }
36
37    /// Convert nonnegative signed milliseconds.
38    #[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    /// Construct from microseconds, truncating sub-millisecond precision.
48    #[must_use]
49    pub const fn from_micros_truncating(micros: u64) -> Self {
50        Self(micros / Self::MS_PER_SEC)
51    }
52
53    /// Construct from nanoseconds, truncating sub-millisecond precision.
54    #[must_use]
55    pub const fn from_nanos_truncating(nanos: u64) -> Self {
56        Self(nanos / 1_000_000)
57    }
58
59    /// Construct from seconds with saturation.
60    #[must_use]
61    pub const fn from_secs(seconds: u64) -> Self {
62        Self(seconds.saturating_mul(Self::MS_PER_SEC))
63    }
64
65    /// Construct from minutes with saturation.
66    #[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    /// Construct from hours with saturation.
76    #[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    /// Construct from days with saturation.
87    #[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    /// Construct from weeks with saturation.
98    #[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    /// Return milliseconds.
111    #[must_use]
112    pub const fn as_millis(self) -> u64 {
113        self.0
114    }
115
116    /// Return whole seconds.
117    #[must_use]
118    pub const fn as_secs(self) -> u64 {
119        self.0 / Self::MS_PER_SEC
120    }
121
122    /// Return whole minutes.
123    #[must_use]
124    pub const fn as_minutes(self) -> u64 {
125        self.0 / (Self::SECS_PER_MIN * Self::MS_PER_SEC)
126    }
127
128    /// Return whole hours.
129    #[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    /// Return whole days.
135    #[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    /// Return whole weeks.
141    #[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    /// Parse integer milliseconds or `ms`, `s`, `m`, `h`, or `d` suffixes.
152    ///
153    /// # Errors
154    ///
155    /// Returns [`TimeParseError::InvalidDuration`] for malformed or overflowing
156    /// input.
157    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/// Signed Unix-millisecond timestamp, including instants before 1970.
225/// Sub-millisecond conversions floor; arithmetic operators saturate only after
226/// the complete wide operation. This value never reads the clock.
227#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
228#[repr(transparent)]
229pub struct Timestamp(i64);
230
231impl Timestamp {
232    /// Unix epoch.
233    pub const EPOCH: Self = Self(0);
234    /// Minimum timestamp.
235    pub const MIN: Self = Self(i64::MIN);
236    /// Maximum timestamp.
237    pub const MAX: Self = Self(i64::MAX);
238
239    const MILLIS_PER_SEC: i64 = 1_000;
240
241    /// Construct from seconds with saturation.
242    #[must_use]
243    pub const fn from_secs(seconds: i64) -> Self {
244        Self(seconds.saturating_mul(Self::MILLIS_PER_SEC))
245    }
246
247    /// Construct from milliseconds.
248    #[must_use]
249    pub const fn from_millis(millis: i64) -> Self {
250        Self(millis)
251    }
252
253    /// Convert signed milliseconds.
254    #[must_use]
255    pub const fn try_from_i64(millis: i64) -> Option<Self> {
256        Some(Self(millis))
257    }
258
259    /// Convert unsigned milliseconds.
260    #[must_use]
261    pub fn try_from_u64(millis: u64) -> Option<Self> {
262        i64::try_from(millis).ok().map(Self)
263    }
264
265    /// Construct from microseconds, flooring to Unix milliseconds.
266    #[must_use]
267    pub const fn from_micros(micros: i64) -> Self {
268        Self(micros.div_euclid(Self::MILLIS_PER_SEC))
269    }
270
271    /// Construct from nanoseconds, flooring to Unix milliseconds.
272    #[must_use]
273    pub const fn from_nanos(nanos: i64) -> Self {
274        Self(nanos.div_euclid(1_000_000))
275    }
276
277    /// Parse strict RFC3339 text.
278    ///
279    /// # Errors
280    ///
281    /// Returns [`TimeParseError::InvalidTimestamp`] for malformed or
282    /// out-of-range input.
283    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        // Four-digit calendar years and a sub-day offset fit comfortably in i64
321        // milliseconds. The fractional contribution is nonnegative, preserving
322        // floor semantics even for instants before the Unix epoch.
323        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    /// Parse integer milliseconds or strict RFC3339 text.
336    ///
337    /// # Errors
338    ///
339    /// Returns a typed timestamp parse error.
340    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    /// Return Unix milliseconds.
348    #[must_use]
349    pub const fn as_millis(self) -> i64 {
350        self.0
351    }
352
353    /// Return whole Unix seconds.
354    #[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/// Invalid or out-of-range human-readable time input.
465#[derive(Clone, Copy, Debug, Eq, PartialEq)]
466pub enum TimeParseError {
467    /// Duration text or its scaled millisecond value was invalid.
468    InvalidDuration,
469    /// Timestamp text or its components were invalid.
470    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 {}