Skip to main content

s2_kit/types/
time.rs

1//! [`Timestamp`] and [`Duration`] — the two time types on the S2 wire.
2//!
3//! S2 writes instants as RFC 3339 date-times (`S2J` `format: date-time`) and spans as
4//! whole milliseconds (`S2J schemas/Duration`: "Duration in milliseconds", minimum 0).
5//! Both are modelled here rather than borrowed from a time crate, for three reasons
6//!:
7//!
8//! * a consumer should not have to name a third-party crate in its own manifest, and
9//!   keep its major version in step, to call this one — the complaint `hems` filed
10//!   against `s2energy`, whose public API is full of `chrono::DateTime<Utc>`;
11//! * the core is `no_std + alloc`, and a two-hundred-line parser is smaller than any
12//!   time crate;
13//! * the wire has exactly two shapes, and neither needs a calendar, a time zone
14//!   database or leap-second tables.
15//!
16//! Conversions to and from [`jiff`](crate::types::time), `time` and `chrono` live behind
17//! the features of those names, and each crate is re-exported so a caller can always
18//! name the same version this crate was built against.
19
20use core::fmt;
21use core::str::FromStr;
22
23use serde::{Deserialize, Deserializer, Serialize, Serializer};
24
25/// A span of time in whole milliseconds, as `S2J schemas/Duration` defines it.
26///
27/// The schema gives `minimum: 0`, so a duration is unsigned — S2 never expresses a
28/// negative span.
29///
30/// ```
31/// use s2_kit::types::Duration;
32///
33/// let d = Duration::from_millis(3_600_000);
34/// assert_eq!(d.as_secs_f64(), 3600.0);
35/// assert_eq!(serde_json::to_string(&d).unwrap(), "3600000");
36/// ```
37#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
38#[serde(transparent)]
39pub struct Duration(u64);
40
41impl Duration {
42    /// Zero.
43    pub const ZERO: Self = Self(0);
44
45    /// The longest span this type can hold: about 584 million years.
46    ///
47    /// Useful as "no deadline" in a comparison. Not useful as something to wait for —
48    /// converting it to a [`core::time::Duration`] and handing that to a timer is how a
49    /// sleep overflows an `Instant`.
50    pub const MAX: Self = Self(u64::MAX);
51
52    /// A duration of `millis` milliseconds.
53    #[must_use]
54    pub const fn from_millis(millis: u64) -> Self {
55        Self(millis)
56    }
57
58    /// A duration of `secs` seconds.
59    #[must_use]
60    pub const fn from_secs(secs: u64) -> Self {
61        Self(secs.saturating_mul(1_000))
62    }
63
64    /// The span in milliseconds.
65    #[must_use]
66    pub const fn as_millis(self) -> u64 {
67        self.0
68    }
69
70    /// The span in seconds, as a float — the unit S2 rates are expressed per.
71    #[must_use]
72    #[allow(clippy::cast_precision_loss)] // exact below 2^53 ms, which is 285 000 years
73    pub const fn as_secs_f64(self) -> f64 {
74        self.0 as f64 / 1_000.0
75    }
76
77    /// Whether the span is zero.
78    #[must_use]
79    pub const fn is_zero(self) -> bool {
80        self.0 == 0
81    }
82
83    /// Sum, or `None` on overflow.
84    #[must_use]
85    pub const fn checked_add(self, other: Self) -> Option<Self> {
86        match self.0.checked_add(other.0) {
87            Some(v) => Some(Self(v)),
88            None => None,
89        }
90    }
91
92    /// Difference, or `None` when `other` is longer.
93    #[must_use]
94    pub const fn checked_sub(self, other: Self) -> Option<Self> {
95        match self.0.checked_sub(other.0) {
96            Some(v) => Some(Self(v)),
97            None => None,
98        }
99    }
100}
101
102impl fmt::Debug for Duration {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        write!(f, "{}ms", self.0)
105    }
106}
107
108impl fmt::Display for Duration {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        write!(f, "{} ms", self.0)
111    }
112}
113
114impl From<Duration> for core::time::Duration {
115    fn from(d: Duration) -> Self {
116        Self::from_millis(d.0)
117    }
118}
119
120impl TryFrom<core::time::Duration> for Duration {
121    type Error = TimeOutOfRange;
122    fn try_from(d: core::time::Duration) -> Result<Self, Self::Error> {
123        u64::try_from(d.as_millis())
124            .map(Self)
125            .map_err(|_| TimeOutOfRange)
126    }
127}
128
129#[cfg(feature = "schemars")]
130impl schemars::JsonSchema for Duration {
131    fn schema_name() -> alloc::borrow::Cow<'static, str> {
132        "Duration".into()
133    }
134    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
135        schemars::json_schema!({ "type": "integer", "minimum": 0 })
136    }
137}
138
139/// A value could not be represented as a [`Timestamp`] or [`Duration`].
140#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
141#[error("the value is outside the range this time type can represent")]
142pub struct TimeOutOfRange;
143
144/// An instant in time, held as seconds and nanoseconds since the Unix epoch, UTC.
145///
146/// The wire form is RFC 3339. Parsing accepts any RFC 3339 spelling — `Z`, `z`, a
147/// numeric offset, `T` or `t` or a space separator, zero to nine fractional digits —
148/// and converts to UTC. Formatting always emits `YYYY-MM-DDTHH:MM:SS[.fff]Z` with the
149/// fewest of {0, 3, 6, 9} fractional digits that loses nothing, so re-encoding a
150/// message a proxy did not change is a no-op.
151///
152/// Seconds-plus-nanoseconds rather than a single nanosecond count because a peer may
153/// legitimately send a far-future instant — `S2J messages/FRBC.TimerStatus.finished_at`
154/// explicitly allows "an arbitrary DateTimeStamp in the past", and nothing bounds the
155/// future — and a 64-bit nanosecond count only reaches the year 2262.
156///
157/// ```
158/// use s2_kit::types::Timestamp;
159///
160/// let t: Timestamp = "2019-08-24T14:15:22Z".parse().unwrap();
161/// assert_eq!(t.to_string(), "2019-08-24T14:15:22Z");
162///
163/// // Offsets are normalised to UTC.
164/// let t: Timestamp = "2019-08-24T16:15:22+02:00".parse().unwrap();
165/// assert_eq!(t.to_string(), "2019-08-24T14:15:22Z");
166/// ```
167#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
168pub struct Timestamp {
169    secs: i64,
170    nanos: u32,
171}
172
173/// Why a string is not a valid RFC 3339 date-time.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
175pub enum InvalidTimestamp {
176    /// The overall shape is wrong (too short, missing separator, trailing characters).
177    #[error("not an RFC 3339 date-time")]
178    Malformed,
179    /// A field was out of range (month 13, hour 25, day 31 of February).
180    #[error("the {field} field of the date-time is out of range")]
181    FieldOutOfRange {
182        /// Which field.
183        field: &'static str,
184    },
185    /// The instant cannot be represented.
186    #[error("the date-time is outside the representable range")]
187    OutOfRange,
188}
189
190impl Timestamp {
191    /// 1970-01-01T00:00:00Z.
192    pub const UNIX_EPOCH: Self = Self { secs: 0, nanos: 0 };
193
194    /// The instant `secs` seconds and `nanos` nanoseconds after the Unix epoch.
195    ///
196    /// `nanos` is normalised into `0..1_000_000_000`.
197    #[must_use]
198    pub const fn from_unix(secs: i64, nanos: u32) -> Self {
199        let extra = (nanos / 1_000_000_000) as i64;
200        Self {
201            secs: secs.saturating_add(extra),
202            nanos: nanos % 1_000_000_000,
203        }
204    }
205
206    /// The instant `millis` milliseconds after the Unix epoch.
207    #[must_use]
208    pub const fn from_unix_millis(millis: i64) -> Self {
209        let secs = millis.div_euclid(1_000);
210        let rem = millis.rem_euclid(1_000);
211        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // rem is 0..999
212        Self {
213            secs,
214            nanos: (rem as u32) * 1_000_000,
215        }
216    }
217
218    /// Whole seconds since the Unix epoch (floor).
219    #[must_use]
220    pub const fn unix_secs(self) -> i64 {
221        self.secs
222    }
223
224    /// The sub-second part, in nanoseconds.
225    #[must_use]
226    pub const fn subsec_nanos(self) -> u32 {
227        self.nanos
228    }
229
230    /// Milliseconds since the Unix epoch (floor), or `None` if it does not fit.
231    #[must_use]
232    pub const fn unix_millis(self) -> Option<i64> {
233        match self.secs.checked_mul(1_000) {
234            Some(ms) => ms.checked_add((self.nanos / 1_000_000) as i64),
235            None => None,
236        }
237    }
238
239    /// The current instant.
240    ///
241    /// Provided for drivers, examples and applications. **Nothing in the protocol core
242    /// calls it**: every engine takes `now` as a parameter, which is what makes a
243    /// two-hour timer a microsecond-long unit test.
244    #[cfg(feature = "std")]
245    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
246    #[must_use]
247    pub fn now() -> Self {
248        let d = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH);
249        match d {
250            Ok(d) => {
251                let secs = i64::try_from(d.as_secs()).unwrap_or(i64::MAX);
252                Self::from_unix(secs, d.subsec_nanos())
253            }
254            // Before 1970. Only reachable on a machine whose clock is badly wrong.
255            Err(e) => {
256                let d = e.duration();
257                let secs = i64::try_from(d.as_secs()).unwrap_or(i64::MAX);
258                Self::from_unix(-secs, 0)
259            }
260        }
261    }
262
263    /// This instant plus `d`, or `None` on overflow.
264    #[must_use]
265    #[allow(clippy::cast_possible_wrap)] // a Duration of more than i64::MAX ms is 292 million years
266    pub const fn checked_add(self, d: Duration) -> Option<Self> {
267        let ms = d.as_millis();
268        let add_secs = (ms / 1_000) as i64;
269        let add_nanos = ((ms % 1_000) as u32) * 1_000_000;
270        let mut nanos = self.nanos + add_nanos;
271        let mut carry = 0i64;
272        if nanos >= 1_000_000_000 {
273            nanos -= 1_000_000_000;
274            carry = 1;
275        }
276        match self.secs.checked_add(add_secs) {
277            Some(s) => match s.checked_add(carry) {
278                Some(s) => Some(Self { secs: s, nanos }),
279                None => None,
280            },
281            None => None,
282        }
283    }
284
285    /// This instant minus `d`, or `None` on overflow.
286    #[must_use]
287    #[allow(clippy::cast_possible_wrap)] // as above
288    pub const fn checked_sub(self, d: Duration) -> Option<Self> {
289        let ms = d.as_millis();
290        let sub_secs = (ms / 1_000) as i64;
291        let sub_nanos = ((ms % 1_000) as u32) * 1_000_000;
292        let (nanos, borrow) = if self.nanos >= sub_nanos {
293            (self.nanos - sub_nanos, 0i64)
294        } else {
295            (self.nanos + 1_000_000_000 - sub_nanos, 1i64)
296        };
297        match self.secs.checked_sub(sub_secs) {
298            Some(s) => match s.checked_sub(borrow) {
299                Some(s) => Some(Self { secs: s, nanos }),
300                None => None,
301            },
302            None => None,
303        }
304    }
305
306    /// How long after `earlier` this instant is, or `None` when it is not after it.
307    ///
308    /// `None` also for a gap no [`Duration`] can hold. Every step is checked: a peer's
309    /// timestamp is data, and two instants far enough apart to overflow an `i64` of
310    /// seconds must not be an arithmetic panic in a driver that is answering one.
311    #[must_use]
312    #[allow(clippy::cast_sign_loss)] // `secs` is checked to be non-negative first
313    pub const fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
314        let Some(secs) = self.secs.checked_sub(earlier.secs) else {
315            return None;
316        };
317        let (secs, nanos) = if self.nanos >= earlier.nanos {
318            (secs, self.nanos - earlier.nanos)
319        } else {
320            let Some(borrowed) = secs.checked_sub(1) else {
321                return None;
322            };
323            (borrowed, self.nanos + 1_000_000_000 - earlier.nanos)
324        };
325        if secs < 0 {
326            return None;
327        }
328        match (secs as u64).checked_mul(1_000) {
329            Some(ms) => match ms.checked_add((nanos / 1_000_000) as u64) {
330                Some(total) => Some(Duration::from_millis(total)),
331                None => None,
332            },
333            None => None,
334        }
335    }
336
337    /// How long after `earlier` this instant is, or zero when it is not after it.
338    #[must_use]
339    pub const fn saturating_duration_since(self, earlier: Self) -> Duration {
340        match self.checked_duration_since(earlier) {
341            Some(d) => d,
342            None => Duration::ZERO,
343        }
344    }
345
346    /// Parse an RFC 3339 date-time.
347    pub fn parse(s: &str) -> Result<Self, InvalidTimestamp> {
348        parse_rfc3339(s)
349    }
350
351    /// The civil date and time in UTC: `(year, month, day, hour, minute, second)`.
352    #[must_use]
353    pub const fn to_civil_utc(self) -> (i64, u32, u32, u32, u32, u32) {
354        let days = self.secs.div_euclid(86_400);
355        let sod = self.secs.rem_euclid(86_400);
356        let (y, m, d) = civil_from_days(days);
357        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // sod is 0..86_399
358        (
359            y,
360            m,
361            d,
362            (sod / 3_600) as u32,
363            ((sod % 3_600) / 60) as u32,
364            (sod % 60) as u32,
365        )
366    }
367}
368
369impl fmt::Display for Timestamp {
370    #[allow(clippy::many_single_char_names)] // year, month, day, hour, minute, second
371    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
372        let (y, mo, d, h, mi, s) = self.to_civil_utc();
373        if (0..=9999).contains(&y) {
374            write!(f, "{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{s:02}")?;
375        } else {
376            // RFC 3339 has no spelling for these; emit an extended year rather than a
377            // wrong one, so a round trip through our own parser still fails loudly.
378            write!(f, "{y:+}-{mo:02}-{d:02}T{h:02}:{mi:02}:{s:02}")?;
379        }
380        let n = self.nanos;
381        if n != 0 {
382            if n.is_multiple_of(1_000_000) {
383                write!(f, ".{:03}", n / 1_000_000)?;
384            } else if n.is_multiple_of(1_000) {
385                write!(f, ".{:06}", n / 1_000)?;
386            } else {
387                write!(f, ".{n:09}")?;
388            }
389        }
390        f.write_str("Z")
391    }
392}
393
394impl fmt::Debug for Timestamp {
395    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396        write!(f, "Timestamp({self})")
397    }
398}
399
400impl FromStr for Timestamp {
401    type Err = InvalidTimestamp;
402    fn from_str(s: &str) -> Result<Self, Self::Err> {
403        parse_rfc3339(s)
404    }
405}
406
407impl Serialize for Timestamp {
408    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
409        use alloc::string::ToString;
410        serializer.serialize_str(&self.to_string())
411    }
412}
413
414impl<'de> Deserialize<'de> for Timestamp {
415    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
416        struct Visitor;
417        impl serde::de::Visitor<'_> for Visitor {
418            type Value = Timestamp;
419            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420                f.write_str("an RFC 3339 date-time")
421            }
422            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Timestamp, E> {
423                parse_rfc3339(v).map_err(E::custom)
424            }
425        }
426        deserializer.deserialize_str(Visitor)
427    }
428}
429
430#[cfg(feature = "schemars")]
431impl schemars::JsonSchema for Timestamp {
432    fn schema_name() -> alloc::borrow::Cow<'static, str> {
433        "DateTimeStamp".into()
434    }
435    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
436        schemars::json_schema!({ "type": "string", "format": "date-time" })
437    }
438}
439
440// ---------------------------------------------------------------------------
441// RFC 3339
442// ---------------------------------------------------------------------------
443
444fn digits(bytes: &[u8], from: usize, len: usize) -> Result<u64, InvalidTimestamp> {
445    let slice = bytes
446        .get(from..from + len)
447        .ok_or(InvalidTimestamp::Malformed)?;
448    let mut acc = 0u64;
449    for &b in slice {
450        if !b.is_ascii_digit() {
451            return Err(InvalidTimestamp::Malformed);
452        }
453        acc = acc * 10 + u64::from(b - b'0');
454    }
455    Ok(acc)
456}
457
458#[allow(
459    clippy::cast_possible_truncation,
460    clippy::cast_possible_wrap,
461    clippy::many_single_char_names
462)]
463fn parse_rfc3339(s: &str) -> Result<Timestamp, InvalidTimestamp> {
464    let b = s.as_bytes();
465    // The shortest legal form is `1970-01-01T00:00:00Z`: 20 bytes.
466    if b.len() < 20 {
467        return Err(InvalidTimestamp::Malformed);
468    }
469    let year = digits(b, 0, 4)? as i64;
470    if b.get(4) != Some(&b'-') {
471        return Err(InvalidTimestamp::Malformed);
472    }
473    let month = digits(b, 5, 2)? as u32;
474    if b.get(7) != Some(&b'-') {
475        return Err(InvalidTimestamp::Malformed);
476    }
477    let day = digits(b, 8, 2)? as u32;
478    match b.get(10) {
479        Some(&b'T' | &b't' | &b' ') => {}
480        _ => return Err(InvalidTimestamp::Malformed),
481    }
482    let hour = digits(b, 11, 2)? as u32;
483    if b.get(13) != Some(&b':') {
484        return Err(InvalidTimestamp::Malformed);
485    }
486    let minute = digits(b, 14, 2)? as u32;
487    if b.get(16) != Some(&b':') {
488        return Err(InvalidTimestamp::Malformed);
489    }
490    let second = digits(b, 17, 2)? as u32;
491
492    let mut i = 19;
493    let mut nanos = 0u32;
494    if b.get(i) == Some(&b'.') || b.get(i) == Some(&b',') {
495        i += 1;
496        let start = i;
497        while b.get(i).is_some_and(u8::is_ascii_digit) {
498            i += 1;
499        }
500        if i == start {
501            return Err(InvalidTimestamp::Malformed);
502        }
503        // Keep up to nine digits; anything finer than a nanosecond is truncated.
504        let mut scale = 100_000_000u32;
505        for &d in b.get(start..i).unwrap_or(&[]).iter().take(9) {
506            nanos += u32::from(d - b'0') * scale;
507            scale /= 10;
508        }
509    }
510
511    let offset_secs: i64 = match b.get(i) {
512        Some(&b'Z' | &b'z') => {
513            i += 1;
514            0
515        }
516        Some(&sign @ (b'+' | b'-')) => {
517            let oh = digits(b, i + 1, 2)? as i64;
518            if b.get(i + 3) != Some(&b':') {
519                return Err(InvalidTimestamp::Malformed);
520            }
521            let om = digits(b, i + 4, 2)? as i64;
522            if oh > 23 || om > 59 {
523                return Err(InvalidTimestamp::FieldOutOfRange { field: "offset" });
524            }
525            i += 6;
526            let magnitude = oh * 3_600 + om * 60;
527            if sign == b'-' { -magnitude } else { magnitude }
528        }
529        _ => return Err(InvalidTimestamp::Malformed),
530    };
531    if i != b.len() {
532        return Err(InvalidTimestamp::Malformed);
533    }
534
535    if !(1..=12).contains(&month) {
536        return Err(InvalidTimestamp::FieldOutOfRange { field: "month" });
537    }
538    if day < 1 || day > days_in_month(year, month) {
539        return Err(InvalidTimestamp::FieldOutOfRange { field: "day" });
540    }
541    if hour > 23 {
542        return Err(InvalidTimestamp::FieldOutOfRange { field: "hour" });
543    }
544    if minute > 59 {
545        return Err(InvalidTimestamp::FieldOutOfRange { field: "minute" });
546    }
547    // RFC 3339 permits `:60` for a leap second. Unix time has no room for one, so it
548    // collapses onto :59 — the same thing every Unix-time library does.
549    if second > 60 {
550        return Err(InvalidTimestamp::FieldOutOfRange { field: "second" });
551    }
552    let second = second.min(59);
553
554    let days = days_from_civil(year, month, day);
555    let secs = days
556        .checked_mul(86_400)
557        .and_then(|s| {
558            s.checked_add(i64::from(hour) * 3_600 + i64::from(minute) * 60 + i64::from(second))
559        })
560        .and_then(|s| s.checked_sub(offset_secs))
561        .ok_or(InvalidTimestamp::OutOfRange)?;
562    Ok(Timestamp { secs, nanos })
563}
564
565const fn is_leap(y: i64) -> bool {
566    (y % 4 == 0 && y % 100 != 0) || y % 400 == 0
567}
568
569const fn days_in_month(y: i64, m: u32) -> u32 {
570    match m {
571        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
572        4 | 6 | 9 | 11 => 30,
573        2 if is_leap(y) => 29,
574        2 => 28,
575        _ => 0,
576    }
577}
578
579/// Days since 1970-01-01 for a proleptic Gregorian date (Howard Hinnant's algorithm).
580///
581/// The single-character names are the algorithm's own, and renaming them would make it
582/// harder rather than easier to check against the published version.
583#[allow(clippy::many_single_char_names)]
584const fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
585    let y = if m <= 2 { y - 1 } else { y };
586    let era = if y >= 0 { y } else { y - 399 } / 400;
587    let yoe = y - era * 400; // [0, 399]
588    let mp = if m > 2 { m - 3 } else { m + 9 } as i64; // [0, 11]
589    let doy = (153 * mp + 2) / 5 + d as i64 - 1; // [0, 365]
590    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
591    era * 146_097 + doe - 719_468
592}
593
594/// The inverse of [`days_from_civil`].
595#[allow(
596    clippy::many_single_char_names,
597    clippy::cast_possible_truncation,
598    clippy::cast_sign_loss
599)]
600const fn civil_from_days(z: i64) -> (i64, u32, u32) {
601    let z = z + 719_468;
602    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
603    let doe = z - era * 146_097; // [0, 146096]
604    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
605    let y = yoe + era * 400;
606    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
607    let mp = (5 * doy + 2) / 153; // [0, 11]
608    let d = (doy - (153 * mp + 2) / 5 + 1) as u32; // [1, 31]
609    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; // [1, 12]
610    (if m <= 2 { y + 1 } else { y }, m, d)
611}
612
613// ---------------------------------------------------------------------------
614// Conversions to the time crates people already use
615// ---------------------------------------------------------------------------
616
617#[cfg(feature = "jiff")]
618#[cfg_attr(docsrs, doc(cfg(feature = "jiff")))]
619mod jiff_conv {
620    use super::{TimeOutOfRange, Timestamp};
621
622    impl From<Timestamp> for jiff::Timestamp {
623        fn from(t: Timestamp) -> Self {
624            #[allow(clippy::cast_possible_wrap)]
625            Self::new(t.unix_secs(), t.subsec_nanos() as i32).unwrap_or(Self::UNIX_EPOCH)
626        }
627    }
628
629    impl TryFrom<jiff::Timestamp> for Timestamp {
630        type Error = TimeOutOfRange;
631        fn try_from(t: jiff::Timestamp) -> Result<Self, Self::Error> {
632            let nanos = u32::try_from(t.subsec_nanosecond()).map_err(|_| TimeOutOfRange)?;
633            Ok(Self::from_unix(t.as_second(), nanos))
634        }
635    }
636}
637
638#[cfg(feature = "time")]
639#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
640mod time_conv {
641    use super::{TimeOutOfRange, Timestamp};
642
643    impl TryFrom<Timestamp> for time::OffsetDateTime {
644        type Error = TimeOutOfRange;
645        fn try_from(t: Timestamp) -> Result<Self, Self::Error> {
646            let nanos = i128::from(t.unix_secs()) * 1_000_000_000 + i128::from(t.subsec_nanos());
647            Self::from_unix_timestamp_nanos(nanos).map_err(|_| TimeOutOfRange)
648        }
649    }
650
651    impl From<time::OffsetDateTime> for Timestamp {
652        fn from(t: time::OffsetDateTime) -> Self {
653            Self::from_unix(t.unix_timestamp(), t.nanosecond())
654        }
655    }
656}
657
658#[cfg(feature = "chrono")]
659#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
660mod chrono_conv {
661    use super::{TimeOutOfRange, Timestamp};
662
663    impl TryFrom<Timestamp> for chrono::DateTime<chrono::Utc> {
664        type Error = TimeOutOfRange;
665        fn try_from(t: Timestamp) -> Result<Self, Self::Error> {
666            Self::from_timestamp(t.unix_secs(), t.subsec_nanos()).ok_or(TimeOutOfRange)
667        }
668    }
669
670    impl From<chrono::DateTime<chrono::Utc>> for Timestamp {
671        fn from(t: chrono::DateTime<chrono::Utc>) -> Self {
672            Self::from_unix(t.timestamp(), t.timestamp_subsec_nanos().min(999_999_999))
673        }
674    }
675}
676
677#[cfg(test)]
678mod tests {
679    use super::*;
680    use alloc::string::ToString;
681
682    #[test]
683    fn every_arithmetic_operation_is_total_at_the_extremes() {
684        // A peer's timestamp is data, and `Timestamp` is a public constructor, so the
685        // extremes are reachable without anything being wrong. None of them may panic:
686        // an overflow in a driver answering a peer is a crash, and in a debug build an
687        // unchecked `i64` subtraction is one.
688        let hi = Timestamp::from_unix(i64::MAX, 999_999_999);
689        let lo = Timestamp::from_unix(i64::MIN, 0);
690
691        assert_eq!(
692            hi.checked_duration_since(lo),
693            None,
694            "gap overflows i64 secs"
695        );
696        assert_eq!(lo.checked_duration_since(hi), None, "not after");
697        assert_eq!(hi.saturating_duration_since(lo), Duration::ZERO);
698        assert_eq!(lo.saturating_duration_since(hi), Duration::ZERO);
699
700        // The borrow path: `self.nanos < earlier.nanos` costs a second, and at the floor
701        // there is no second to spend.
702        let floor = Timestamp::from_unix(i64::MIN, 0);
703        let just_above = Timestamp::from_unix(i64::MIN, 500);
704        assert_eq!(floor.checked_duration_since(just_above), None);
705
706        assert_eq!(hi.checked_add(Duration::from_millis(1)), None);
707        assert_eq!(lo.checked_sub(Duration::from_millis(1_000)), None);
708
709        // And the ordinary case still answers.
710        let a = Timestamp::from_unix(1_000, 0);
711        let b = Timestamp::from_unix(1_002, 500_000_000);
712        assert_eq!(
713            b.checked_duration_since(a),
714            Some(Duration::from_millis(2_500))
715        );
716    }
717
718    #[test]
719    fn parses_every_timestamp_in_the_official_examples() {
720        // Straight from docs `learn/examples/{ev,heat-pump,pv,nocontrol}`.
721        for s in [
722            "2019-08-24T14:15:22Z",
723            "2024-08-24T14:15:22Z",
724            "2024-08-24T15:00:00Z",
725            "2024-12-25T14:15:22Z",
726            "2024-08-24T14:00:00Z",
727        ] {
728            let t = Timestamp::parse(s).unwrap();
729            assert_eq!(t.to_string(), s, "{s} should round-trip");
730        }
731    }
732
733    #[test]
734    fn accepts_the_rfc3339_spellings_a_peer_may_use() {
735        let canonical = Timestamp::parse("2019-08-24T14:15:22Z").unwrap();
736        for s in [
737            "2019-08-24t14:15:22z",
738            "2019-08-24 14:15:22Z",
739            "2019-08-24T14:15:22+00:00",
740            "2019-08-24T16:15:22+02:00",
741            "2019-08-24T11:15:22-03:00",
742            "2019-08-24T14:15:22.000Z",
743            "2019-08-24T14:15:22.000000000Z",
744        ] {
745            assert_eq!(Timestamp::parse(s).unwrap(), canonical, "{s}");
746        }
747    }
748
749    #[test]
750    fn fractional_digits_are_preserved_and_minimised() {
751        for (input, expected) in [
752            ("2019-08-24T14:15:22.5Z", "2019-08-24T14:15:22.500Z"),
753            ("2019-08-24T14:15:22.123Z", "2019-08-24T14:15:22.123Z"),
754            ("2019-08-24T14:15:22.123456Z", "2019-08-24T14:15:22.123456Z"),
755            (
756                "2019-08-24T14:15:22.123456789Z",
757                "2019-08-24T14:15:22.123456789Z",
758            ),
759            // Finer than a nanosecond is truncated, not rounded.
760            (
761                "2019-08-24T14:15:22.1234567891Z",
762                "2019-08-24T14:15:22.123456789Z",
763            ),
764            ("2019-08-24T14:15:22.000Z", "2019-08-24T14:15:22Z"),
765        ] {
766            assert_eq!(Timestamp::parse(input).unwrap().to_string(), expected);
767        }
768    }
769
770    #[test]
771    fn rejects_what_is_not_a_date_time() {
772        for s in [
773            "",
774            "2019-08-24",
775            "2019-08-24T14:15:22",       // no offset
776            "2019-13-24T14:15:22Z",      // month 13
777            "2019-02-30T14:15:22Z",      // February 30
778            "2019-08-24T25:15:22Z",      // hour 25
779            "2019-08-24T14:60:22Z",      // minute 60
780            "2019-08-24T14:15:61Z",      // second 61
781            "2019-08-24T14:15:22Zjunk",  // trailing
782            "2019-08-24T14:15:22.Z",     // empty fraction
783            "2019-08-24T14:15:22+0200",  // offset without colon
784            "2019-08-24T14:15:22+24:00", // offset out of range
785        ] {
786            assert!(Timestamp::parse(s).is_err(), "{s:?} should be rejected");
787        }
788    }
789
790    #[test]
791    fn leap_second_collapses_onto_fifty_nine() {
792        // RFC 3339 allows it; Unix time has no room for it.
793        let t = Timestamp::parse("2016-12-31T23:59:60Z").unwrap();
794        assert_eq!(t.to_string(), "2016-12-31T23:59:59Z");
795    }
796
797    #[test]
798    fn far_dates_survive_because_the_representation_is_not_nanoseconds() {
799        // A peer may send a timer that finishes in the year 3000; a nanosecond count
800        // would overflow in 2262 and this must be a warning rather than a parse failure.
801        let t = Timestamp::parse("3000-01-01T00:00:00Z").unwrap();
802        assert_eq!(t.to_string(), "3000-01-01T00:00:00Z");
803        let t = Timestamp::parse("1900-01-01T00:00:00Z").unwrap();
804        assert_eq!(t.to_string(), "1900-01-01T00:00:00Z");
805        let t = Timestamp::parse("0001-01-01T00:00:00Z").unwrap();
806        assert_eq!(t.to_string(), "0001-01-01T00:00:00Z");
807        let t = Timestamp::parse("9999-12-31T23:59:59Z").unwrap();
808        assert_eq!(t.to_string(), "9999-12-31T23:59:59Z");
809    }
810
811    #[test]
812    fn civil_conversions_are_inverse_over_four_centuries() {
813        // Every day from 1800 to 2200, there and back.
814        let mut days = days_from_civil(1800, 1, 1);
815        let end = days_from_civil(2200, 1, 1);
816        while days < end {
817            let (y, m, d) = civil_from_days(days);
818            assert_eq!(days_from_civil(y, m, d), days, "{y}-{m}-{d}");
819            days += 1;
820        }
821    }
822
823    #[test]
824    fn arithmetic_is_checked() {
825        let t = Timestamp::parse("2019-08-24T14:15:22Z").unwrap();
826        let hour = Duration::from_secs(3_600);
827        assert_eq!(
828            t.checked_add(hour).unwrap().to_string(),
829            "2019-08-24T15:15:22Z"
830        );
831        assert_eq!(
832            t.checked_sub(hour).unwrap().to_string(),
833            "2019-08-24T13:15:22Z"
834        );
835        assert_eq!(
836            t.checked_add(hour).unwrap().checked_duration_since(t),
837            Some(hour)
838        );
839        assert_eq!(t.checked_duration_since(t.checked_add(hour).unwrap()), None);
840        assert_eq!(
841            t.saturating_duration_since(t.checked_add(hour).unwrap()),
842            Duration::ZERO
843        );
844    }
845
846    #[test]
847    fn sub_second_arithmetic_carries() {
848        let t = Timestamp::parse("2019-08-24T14:15:22.900Z").unwrap();
849        assert_eq!(
850            t.checked_add(Duration::from_millis(200))
851                .unwrap()
852                .to_string(),
853            "2019-08-24T14:15:23.100Z"
854        );
855        let t = Timestamp::parse("2019-08-24T14:15:22.100Z").unwrap();
856        assert_eq!(
857            t.checked_sub(Duration::from_millis(200))
858                .unwrap()
859                .to_string(),
860            "2019-08-24T14:15:21.900Z"
861        );
862    }
863
864    #[test]
865    fn ordering_is_chronological() {
866        let a = Timestamp::parse("2019-08-24T14:15:22Z").unwrap();
867        let b = Timestamp::parse("2019-08-24T14:15:22.001Z").unwrap();
868        let c = Timestamp::parse("2019-08-24T14:15:23Z").unwrap();
869        assert!(a < b && b < c);
870    }
871
872    #[test]
873    fn json_is_a_bare_string() {
874        let t = Timestamp::parse("2019-08-24T14:15:22Z").unwrap();
875        assert_eq!(
876            serde_json::to_string(&t).unwrap(),
877            "\"2019-08-24T14:15:22Z\""
878        );
879        assert_eq!(
880            serde_json::from_str::<Timestamp>("\"2019-08-24T14:15:22Z\"").unwrap(),
881            t
882        );
883        assert!(serde_json::from_str::<Timestamp>("\"nope\"").is_err());
884    }
885
886    #[test]
887    fn duration_is_milliseconds_on_the_wire() {
888        let d = Duration::from_millis(3_600_000);
889        assert_eq!(serde_json::to_string(&d).unwrap(), "3600000");
890        assert_eq!(
891            serde_json::from_str::<Duration>("0").unwrap(),
892            Duration::ZERO
893        );
894        // The schema says minimum 0, and the type is unsigned, so a negative is refused.
895        assert!(serde_json::from_str::<Duration>("-1").is_err());
896    }
897
898    #[test]
899    fn size_is_what_we_promised() {
900        assert_eq!(core::mem::size_of::<Timestamp>(), 16);
901        assert_eq!(core::mem::size_of::<Duration>(), 8);
902    }
903}