Skip to main content

lean_ctx_time/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Time for LeanCTX: UTC instants, signed durations and their text formats.
3//!
4//! A thin layer over [`jiff`]. LeanCTX stores timestamps in state files,
5//! signs them into receipts and sends them over its wire contracts, so this
6//! crate keeps every format LeanCTX has always written byte for byte:
7//!
8//! - serde and `Debug`: RFC 3339 in UTC with `Z` and 0, 3, 6 or 9
9//!   fractional digits (`2026-11-17T10:00:00Z`, `…00.250Z`);
10//! - [`UtcDateTime::to_rfc3339`]: the same with `+00:00`;
11//! - [`UtcDateTime::to_rfc3339_opts`]: a fixed precision, truncated;
12//! - `Display`: `2026-11-17 10:00:00 UTC`;
13//! - [`UtcDateTime::format`]: strftime (see [`mod@format`] for the specifiers);
14//! - [`Duration`]'s `Display`: ISO 8601 (`PT90S`, `-PT0.5S`, `P0D`).
15//!
16//! Parsing accepts what LeanCTX has always accepted: strict RFC 3339 in
17//! [`UtcDateTime::parse_from_rfc3339`], and the relaxed form (spaces before
18//! the offset, `UTC`, offsets without a colon) in `FromStr` and serde.
19
20#![forbid(unsafe_code)]
21
22pub mod format;
23mod parse;
24
25use std::fmt;
26use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
27use std::str::FromStr;
28
29pub use jiff;
30use jiff::civil;
31use jiff::tz::TimeZone;
32use jiff::{SignedDuration, Timestamp};
33
34pub use parse::ParseError;
35
36/// A calendar date without a time zone (chrono's `NaiveDate`).
37pub use jiff::civil::Date;
38/// A date and wall-clock time without a time zone (chrono's `NaiveDateTime`).
39pub use jiff::civil::DateTime as CivilDateTime;
40/// A wall-clock time without a date or time zone (chrono's `NaiveTime`).
41pub use jiff::civil::Time;
42
43/// Parses a calendar date with a strftime pattern.
44///
45/// Matches chrono's `NaiveDate::parse_from_str` for every unsigned year
46/// (a differential test compared 17.7 million inputs); a leading `+` or `-`
47/// on the year is rejected, where chrono accepted some signed forms.
48pub fn parse_date(s: &str, fmt: &str) -> Result<Date, ParseError> {
49    if s.starts_with(['+', '-']) {
50        return Err(ParseError::invalid());
51    }
52    Date::strptime(fmt, s).map_err(|_| ParseError::invalid())
53}
54
55/// Parses a date and wall-clock time with a strftime pattern, like
56/// [`parse_date`]. A leap second (`:60`) reads as `:59`.
57pub fn parse_civil_datetime(s: &str, fmt: &str) -> Result<CivilDateTime, ParseError> {
58    if s.starts_with(['+', '-']) {
59        return Err(ParseError::invalid());
60    }
61    CivilDateTime::strptime(fmt, s).map_err(|_| ParseError::invalid())
62}
63
64/// `dt` read in UTC; `None` only in the first and last day of jiff's range.
65#[must_use]
66pub fn utc_from_civil(dt: CivilDateTime) -> Option<UtcDateTime> {
67    dt.to_zoned(TimeZone::UTC)
68        .ok()
69        .map(|z| UtcDateTime(z.timestamp()))
70}
71
72/// `dt` read as wall-clock time in the system time zone. A repeated hour
73/// (DST fold) takes the earlier instant; a skipped hour (DST gap) reads `dt`
74/// as UTC, at most one DST shift off. `None` only at jiff's range edges.
75#[must_use]
76pub fn utc_from_local_civil(dt: CivilDateTime) -> Option<UtcDateTime> {
77    use jiff::tz::AmbiguousOffset;
78    let offset = match TimeZone::system().to_ambiguous_timestamp(dt).offset() {
79        AmbiguousOffset::Unambiguous { offset } | AmbiguousOffset::Fold { before: offset, .. } => {
80            offset
81        }
82        AmbiguousOffset::Gap { .. } => return utc_from_civil(dt),
83    };
84    offset.to_timestamp(dt).ok().map(UtcDateTime)
85}
86
87/// Whole days from `earlier` to `later` (negative when `later` is earlier),
88/// like chrono's `(later - earlier).num_days()`.
89#[must_use]
90pub fn days_between(earlier: Date, later: Date) -> i64 {
91    i64::from((later - earlier).get_days())
92}
93
94// chrono let `NaiveDate`/`NaiveDateTime` take a `TimeDelta` with `+`/`-`
95// (whole days for a date, fraction dropped); keep that and its overflow panic.
96macro_rules! civil_ops {
97    ($t:ty) => {
98        impl Add<Duration> for $t {
99            type Output = $t;
100            fn add(self, d: Duration) -> $t {
101                self.checked_add(d.0).expect(concat!(
102                    "`",
103                    stringify!($t),
104                    " + Duration` overflowed"
105                ))
106            }
107        }
108        impl Sub<Duration> for $t {
109            type Output = $t;
110            fn sub(self, d: Duration) -> $t {
111                self.checked_sub(d.0).expect(concat!(
112                    "`",
113                    stringify!($t),
114                    " - Duration` overflowed"
115                ))
116            }
117        }
118    };
119}
120civil_ops!(Date);
121civil_ops!(CivilDateTime);
122
123const NANOS_PER_SEC: i128 = 1_000_000_000;
124
125/// How many fractional digits [`UtcDateTime::to_rfc3339_opts`] writes.
126#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
127pub enum SecondsFormat {
128    /// No fraction.
129    Secs,
130    /// Three digits.
131    Millis,
132    /// Six digits.
133    Micros,
134    /// Nine digits.
135    Nanos,
136    /// The fewest of 0, 3, 6 or 9 digits that keep the value exact.
137    AutoSi,
138}
139
140/// The value is outside the range the target type can hold.
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
142pub struct OutOfRangeError;
143
144impl fmt::Display for OutOfRangeError {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        f.write_str("out of range")
147    }
148}
149
150impl std::error::Error for OutOfRangeError {}
151
152// ---------------------------------------------------------------------------
153// UtcDateTime
154// ---------------------------------------------------------------------------
155
156/// An instant in UTC with nanosecond precision.
157#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
158pub struct UtcDateTime(Timestamp);
159
160impl Default for UtcDateTime {
161    /// The Unix epoch.
162    fn default() -> Self {
163        Self::UNIX_EPOCH
164    }
165}
166
167impl UtcDateTime {
168    /// 1970-01-01T00:00:00Z.
169    pub const UNIX_EPOCH: Self = Self(Timestamp::UNIX_EPOCH);
170
171    /// The current time from the system clock.
172    #[must_use]
173    pub fn now() -> Self {
174        Self(Timestamp::now())
175    }
176
177    /// A UTC calendar date and time; `None` when a field is out of range.
178    #[must_use]
179    pub fn with_ymd_and_hms(
180        year: i32,
181        month: u32,
182        day: u32,
183        hour: u32,
184        minute: u32,
185        second: u32,
186    ) -> Option<Self> {
187        let date = civil::Date::new(
188            i16::try_from(year).ok()?,
189            i8::try_from(month).ok()?,
190            i8::try_from(day).ok()?,
191        )
192        .ok()?;
193        let time = civil::Time::new(
194            i8::try_from(hour).ok()?,
195            i8::try_from(minute).ok()?,
196            i8::try_from(second).ok()?,
197            0,
198        )
199        .ok()?;
200        date.to_datetime(time)
201            .to_zoned(TimeZone::UTC)
202            .ok()
203            .map(|z| Self(z.timestamp()))
204    }
205
206    /// Wraps a jiff timestamp.
207    #[must_use]
208    pub const fn from_jiff(ts: Timestamp) -> Self {
209        Self(ts)
210    }
211
212    /// The jiff timestamp underneath.
213    #[must_use]
214    pub const fn as_jiff(self) -> Timestamp {
215        self.0
216    }
217
218    /// From whole seconds since the epoch plus a nanosecond part below one
219    /// second. `None` outside jiff's range (years -9999 to 9999).
220    #[must_use]
221    pub fn from_timestamp(secs: i64, nanos: u32) -> Option<Self> {
222        if nanos >= 1_000_000_000 {
223            return None;
224        }
225        Self::from_nanos_i128(i128::from(secs) * NANOS_PER_SEC + i128::from(nanos))
226    }
227
228    /// From milliseconds since the epoch.
229    #[must_use]
230    pub fn from_timestamp_millis(millis: i64) -> Option<Self> {
231        Self::from_nanos_i128(i128::from(millis) * 1_000_000)
232    }
233
234    /// From microseconds since the epoch.
235    #[must_use]
236    pub fn from_timestamp_micros(micros: i64) -> Option<Self> {
237        Self::from_nanos_i128(i128::from(micros) * 1_000)
238    }
239
240    /// From nanoseconds since the epoch. Every `i64` is in range.
241    #[must_use]
242    pub fn from_timestamp_nanos(nanos: i64) -> Self {
243        Self::from_nanos_i128(i128::from(nanos)).expect("every i64 nanosecond count is in range")
244    }
245
246    fn from_nanos_i128(nanos: i128) -> Option<Self> {
247        Timestamp::from_nanosecond(nanos).ok().map(Self)
248    }
249
250    fn nanos_i128(self) -> i128 {
251        self.0.as_nanosecond()
252    }
253
254    /// Whole seconds since the epoch, rounded towards negative infinity.
255    #[must_use]
256    pub fn timestamp(self) -> i64 {
257        to_i64(self.nanos_i128().div_euclid(NANOS_PER_SEC))
258    }
259
260    /// Milliseconds since the epoch, rounded towards negative infinity.
261    #[must_use]
262    pub fn timestamp_millis(self) -> i64 {
263        to_i64(self.nanos_i128().div_euclid(1_000_000))
264    }
265
266    /// Microseconds since the epoch, rounded towards negative infinity.
267    #[must_use]
268    pub fn timestamp_micros(self) -> i64 {
269        to_i64(self.nanos_i128().div_euclid(1_000))
270    }
271
272    /// Nanoseconds since the epoch, `None` past the `i64` range (year 2262).
273    #[must_use]
274    pub fn timestamp_nanos_opt(self) -> Option<i64> {
275        i64::try_from(self.nanos_i128()).ok()
276    }
277
278    /// The nanoseconds past [`UtcDateTime::timestamp`], `0..1_000_000_000`.
279    #[must_use]
280    pub fn timestamp_subsec_nanos(self) -> u32 {
281        u32::try_from(self.nanos_i128().rem_euclid(NANOS_PER_SEC)).expect("below one second")
282    }
283
284    /// The milliseconds past [`UtcDateTime::timestamp`], `0..1000`.
285    #[must_use]
286    pub fn timestamp_subsec_millis(self) -> u32 {
287        self.timestamp_subsec_nanos() / 1_000_000
288    }
289
290    /// The microseconds past [`UtcDateTime::timestamp`], `0..1_000_000`.
291    #[must_use]
292    pub fn timestamp_subsec_micros(self) -> u32 {
293        self.timestamp_subsec_nanos() / 1_000
294    }
295
296    /// Strict RFC 3339 (`2026-11-17T10:00:00Z`, `…00.5+01:00`), converted to
297    /// UTC. `T`, `t` or a space separates date and time; seconds are
298    /// required; the offset is `Z`, `z` or `±hh:mm`.
299    pub fn parse_from_rfc3339(s: &str) -> Result<Self, ParseError> {
300        parse::rfc3339(s, parse::Mode::Strict).map(|p| p.utc)
301    }
302
303    /// Parses `s` with a strftime pattern that includes an offset (`%z`,
304    /// `%:z`) or an instant (`%s`), converted to UTC.
305    pub fn parse_from_str(s: &str, fmt: &str) -> Result<Self, ParseError> {
306        Timestamp::strptime(fmt, s)
307            .map(Self)
308            .map_err(|_| ParseError::invalid())
309    }
310
311    /// RFC 3339 with `+00:00` and 0, 3, 6 or 9 fractional digits.
312    #[must_use]
313    pub fn to_rfc3339(self) -> String {
314        self.to_rfc3339_opts(SecondsFormat::AutoSi, false)
315    }
316
317    /// RFC 3339 with the given precision (truncated, never rounded); `use_z`
318    /// writes `Z` instead of `+00:00`.
319    #[must_use]
320    pub fn to_rfc3339_opts(self, secform: SecondsFormat, use_z: bool) -> String {
321        let mut out = String::with_capacity(32);
322        let parts = format::Parts::utc(self);
323        format::write_rfc3339(
324            &mut out,
325            &parts,
326            secform,
327            if use_z { "Z" } else { "+00:00" },
328        );
329        out
330    }
331
332    /// strftime; see [`mod@format`] for the supported specifiers.
333    #[must_use]
334    pub fn format(self, fmt: &str) -> format::Formatted<'_> {
335        format::Formatted::new(format::Parts::utc(self), fmt)
336    }
337
338    /// The UTC calendar date.
339    #[must_use]
340    pub fn date_naive(self) -> civil::Date {
341        self.civil().date()
342    }
343
344    /// The UTC calendar date and wall time.
345    #[must_use]
346    pub fn naive_utc(self) -> civil::DateTime {
347        self.civil()
348    }
349
350    fn civil(self) -> civil::DateTime {
351        TimeZone::UTC.to_datetime(self.0)
352    }
353
354    /// The year in UTC.
355    #[must_use]
356    pub fn year(self) -> i32 {
357        i32::from(self.civil().year())
358    }
359
360    /// The month in UTC, `1..=12`.
361    #[must_use]
362    pub fn month(self) -> u32 {
363        u32::try_from(self.civil().month()).expect("month is positive")
364    }
365
366    /// The day of the month in UTC, `1..=31`.
367    #[must_use]
368    pub fn day(self) -> u32 {
369        u32::try_from(self.civil().day()).expect("day is positive")
370    }
371
372    /// The hour in UTC, `0..=23`.
373    #[must_use]
374    pub fn hour(self) -> u32 {
375        u32::try_from(self.civil().hour()).expect("hour is not negative")
376    }
377
378    /// The minute in UTC, `0..=59`.
379    #[must_use]
380    pub fn minute(self) -> u32 {
381        u32::try_from(self.civil().minute()).expect("minute is not negative")
382    }
383
384    /// The second in UTC, `0..=59`.
385    #[must_use]
386    pub fn second(self) -> u32 {
387        u32::try_from(self.civil().second()).expect("second is not negative")
388    }
389
390    /// The day of the year in UTC, `1..=366`.
391    #[must_use]
392    pub fn ordinal(self) -> u32 {
393        u32::try_from(self.civil().day_of_year()).expect("day of year is positive")
394    }
395
396    /// Monday = 0 … Sunday = 6, in UTC.
397    #[must_use]
398    pub fn weekday_from_monday(self) -> u32 {
399        u32::try_from(self.civil().weekday().to_monday_zero_offset()).expect("0..=6")
400    }
401
402    /// The same instant in the system time zone.
403    #[must_use]
404    pub fn to_local(self) -> LocalDateTime {
405        LocalDateTime(self.0.to_zoned(TimeZone::system()))
406    }
407
408    /// The same instant with offset `+00:00`.
409    #[must_use]
410    pub const fn fixed_offset(self) -> OffsetDateTime {
411        OffsetDateTime {
412            utc: self,
413            offset_secs: 0,
414        }
415    }
416
417    /// The same instant shown `secs` east of UTC; `None` unless
418    /// `|secs| < 86_400` (chrono's `FixedOffset::east_opt` range).
419    #[must_use]
420    pub fn with_offset_seconds(self, secs: i32) -> Option<OffsetDateTime> {
421        (-86_399..=86_399)
422            .contains(&secs)
423            .then_some(OffsetDateTime {
424                utc: self,
425                offset_secs: secs,
426            })
427    }
428
429    /// Rounded down to a whole multiple of `span` since the Unix epoch, like
430    /// chrono's `DurationRound::duration_trunc`: an error for a span that is
431    /// not positive or longer than the time since the epoch.
432    pub fn duration_trunc(self, span: Duration) -> Result<Self, OutOfRangeError> {
433        let span = span.0.as_nanos();
434        let stamp = self.nanos_i128();
435        if span <= 0 || span > stamp.abs() {
436            return Err(OutOfRangeError);
437        }
438        Self::from_nanos_i128(stamp - stamp.rem_euclid(span)).ok_or(OutOfRangeError)
439    }
440
441    /// The same second with the fraction set to `nano`; `None` for
442    /// `nano >= 1_000_000_000` (chrono's leap-second range is not kept).
443    #[must_use]
444    pub fn with_nanosecond(self, nano: u32) -> Option<Self> {
445        if i128::from(nano) >= NANOS_PER_SEC {
446            return None;
447        }
448        let secs = i128::from(self.timestamp());
449        Self::from_nanos_i128(secs * NANOS_PER_SEC + i128::from(nano))
450    }
451
452    /// Itself: the counterpart of [`OffsetDateTime::to_utc`] and
453    /// [`LocalDateTime::to_utc`], so code generic over the source reads alike.
454    #[must_use]
455    pub const fn to_utc(self) -> Self {
456        self
457    }
458
459    /// `self - other`.
460    #[must_use]
461    pub fn signed_duration_since(self, other: impl Into<UtcDateTime>) -> Duration {
462        Duration::from_nanos_i128(self.nanos_i128() - other.into().nanos_i128())
463            .expect("the difference of two instants fits a duration")
464    }
465
466    /// `self + d`, `None` outside the representable range.
467    #[must_use]
468    pub fn checked_add_signed(self, d: Duration) -> Option<Self> {
469        self.0.checked_add(d.0).ok().map(Self)
470    }
471
472    /// `self - d`, `None` outside the representable range.
473    #[must_use]
474    pub fn checked_sub_signed(self, d: Duration) -> Option<Self> {
475        self.0.checked_sub(d.0).ok().map(Self)
476    }
477
478    /// The instant truncated to whole seconds (towards the past).
479    #[must_use]
480    pub fn trunc_subsecs_to_secs(self) -> Self {
481        Self::from_nanos_i128(self.nanos_i128() - self.nanos_i128().rem_euclid(NANOS_PER_SEC))
482            .expect("truncation stays in range")
483    }
484
485    /// The instant as a `SystemTime`.
486    #[must_use]
487    pub fn to_system_time(self) -> std::time::SystemTime {
488        std::time::SystemTime::from(self.0)
489    }
490}
491
492fn to_i64(v: i128) -> i64 {
493    i64::try_from(v).expect("jiff's range fits i64 at this resolution")
494}
495
496impl From<std::time::SystemTime> for UtcDateTime {
497    /// Panics outside jiff's range (years -9999 to 9999), as chrono's
498    /// conversion does outside its own.
499    fn from(t: std::time::SystemTime) -> Self {
500        Self(Timestamp::try_from(t).expect("system time within years -9999..=9999"))
501    }
502}
503
504impl From<UtcDateTime> for std::time::SystemTime {
505    fn from(t: UtcDateTime) -> Self {
506        t.to_system_time()
507    }
508}
509
510impl From<Timestamp> for UtcDateTime {
511    fn from(ts: Timestamp) -> Self {
512        Self(ts)
513    }
514}
515
516impl From<UtcDateTime> for Timestamp {
517    fn from(t: UtcDateTime) -> Self {
518        t.0
519    }
520}
521
522impl fmt::Debug for UtcDateTime {
523    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524        f.write_str(&self.to_rfc3339_opts(SecondsFormat::AutoSi, true))
525    }
526}
527
528impl fmt::Display for UtcDateTime {
529    /// `2026-11-17 10:00:00 UTC`, with 3, 6 or 9 fractional digits when the
530    /// instant has them.
531    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532        let mut out = String::with_capacity(32);
533        format::write_display(&mut out, &format::Parts::utc(*self));
534        f.pad(&out)
535    }
536}
537
538impl FromStr for UtcDateTime {
539    type Err = ParseError;
540
541    /// Relaxed RFC 3339: what serde accepts.
542    fn from_str(s: &str) -> Result<Self, ParseError> {
543        parse::rfc3339(s, parse::Mode::Relaxed).map(|p| p.utc)
544    }
545}
546
547impl serde::Serialize for UtcDateTime {
548    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
549        serializer.collect_str(&format_args!("{self:?}"))
550    }
551}
552
553impl<'de> serde::Deserialize<'de> for UtcDateTime {
554    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
555        struct Visitor;
556        impl serde::de::Visitor<'_> for Visitor {
557            type Value = UtcDateTime;
558            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
559                f.write_str("an RFC 3339 date and time string")
560            }
561            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<UtcDateTime, E> {
562                v.parse().map_err(E::custom)
563            }
564        }
565        deserializer.deserialize_str(Visitor)
566    }
567}
568
569/// The schema schemars' `chrono04` feature gave `DateTime<Utc>`, so MCP
570/// tool schemas stay byte for byte the same.
571#[cfg(feature = "schemars")]
572impl schemars::JsonSchema for UtcDateTime {
573    fn inline_schema() -> bool {
574        true
575    }
576
577    fn schema_name() -> std::borrow::Cow<'static, str> {
578        "DateTime".into()
579    }
580
581    fn schema_id() -> std::borrow::Cow<'static, str> {
582        "chrono::DateTime".into()
583    }
584
585    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
586        schemars::json_schema!({
587            "type": "string",
588            "format": "date-time"
589        })
590    }
591}
592
593impl Add<Duration> for UtcDateTime {
594    type Output = Self;
595    fn add(self, d: Duration) -> Self {
596        self.checked_add_signed(d)
597            .expect("`UtcDateTime + Duration` overflowed")
598    }
599}
600
601impl Sub<Duration> for UtcDateTime {
602    type Output = Self;
603    fn sub(self, d: Duration) -> Self {
604        self.checked_sub_signed(d)
605            .expect("`UtcDateTime - Duration` overflowed")
606    }
607}
608
609impl AddAssign<Duration> for UtcDateTime {
610    fn add_assign(&mut self, d: Duration) {
611        *self = *self + d;
612    }
613}
614
615impl SubAssign<Duration> for UtcDateTime {
616    fn sub_assign(&mut self, d: Duration) {
617        *self = *self - d;
618    }
619}
620
621impl Add<std::time::Duration> for UtcDateTime {
622    type Output = Self;
623    fn add(self, d: std::time::Duration) -> Self {
624        self + Duration::from_std(d).expect("std duration within range")
625    }
626}
627
628impl Sub<std::time::Duration> for UtcDateTime {
629    type Output = Self;
630    fn sub(self, d: std::time::Duration) -> Self {
631        self - Duration::from_std(d).expect("std duration within range")
632    }
633}
634
635impl Sub for UtcDateTime {
636    type Output = Duration;
637    fn sub(self, other: Self) -> Duration {
638        self.signed_duration_since(other)
639    }
640}
641
642// ---------------------------------------------------------------------------
643// OffsetDateTime: an instant with the UTC offset it was written in
644// ---------------------------------------------------------------------------
645
646/// An instant together with a fixed UTC offset, as parsed from RFC 3339.
647///
648/// Equality, ordering and hashing look at the instant only, as chrono's
649/// `DateTime<FixedOffset>` did: `11:00+01:00 == 10:00Z`.
650#[derive(Clone, Copy)]
651pub struct OffsetDateTime {
652    utc: UtcDateTime,
653    offset_secs: i32,
654}
655
656impl OffsetDateTime {
657    /// Strict RFC 3339, keeping the offset.
658    pub fn parse_from_rfc3339(s: &str) -> Result<Self, ParseError> {
659        parse::rfc3339(s, parse::Mode::Strict).map(|p| Self {
660            utc: p.utc,
661            offset_secs: p.offset_secs,
662        })
663    }
664
665    /// The instant in UTC.
666    #[must_use]
667    pub const fn to_utc(self) -> UtcDateTime {
668        self.utc
669    }
670
671    /// Seconds east of UTC.
672    #[must_use]
673    pub const fn offset_seconds(self) -> i32 {
674        self.offset_secs
675    }
676
677    /// Unix seconds.
678    #[must_use]
679    pub fn timestamp(self) -> i64 {
680        self.utc.timestamp()
681    }
682
683    /// Unix milliseconds.
684    #[must_use]
685    pub fn timestamp_millis(self) -> i64 {
686        self.utc.timestamp_millis()
687    }
688
689    /// `self - other` as a signed duration.
690    #[must_use]
691    pub fn signed_duration_since(self, other: impl Into<UtcDateTime>) -> Duration {
692        self.utc.signed_duration_since(other)
693    }
694
695    /// `self + d` in the same offset, `None` outside the range.
696    #[must_use]
697    pub fn checked_add_signed(self, d: Duration) -> Option<Self> {
698        self.utc
699            .checked_add_signed(d)
700            .map(|utc| Self { utc, ..self })
701    }
702
703    /// `self - d` in the same offset, `None` outside the range.
704    #[must_use]
705    pub fn checked_sub_signed(self, d: Duration) -> Option<Self> {
706        self.utc
707            .checked_sub_signed(d)
708            .map(|utc| Self { utc, ..self })
709    }
710
711    /// RFC 3339 in the original offset (`+00:00` for UTC).
712    #[must_use]
713    pub fn to_rfc3339(self) -> String {
714        self.to_rfc3339_opts(SecondsFormat::AutoSi, false)
715    }
716
717    /// RFC 3339 in the original offset with the given precision; `use_z`
718    /// writes `Z` for a zero offset, like chrono.
719    #[must_use]
720    pub fn to_rfc3339_opts(self, secform: SecondsFormat, use_z: bool) -> String {
721        let mut out = String::with_capacity(32);
722        let parts = format::Parts::with_offset(self.utc, self.offset_secs, None);
723        let offset = if use_z && self.offset_secs == 0 {
724            "Z".to_owned()
725        } else {
726            format::offset_colon(self.offset_secs)
727        };
728        format::write_rfc3339(&mut out, &parts, secform, &offset);
729        out
730    }
731
732    /// The nanoseconds past [`OffsetDateTime::timestamp`].
733    #[must_use]
734    pub fn timestamp_subsec_nanos(self) -> u32 {
735        self.utc.timestamp_subsec_nanos()
736    }
737
738    /// The same instant in the system time zone.
739    #[must_use]
740    pub fn to_local(self) -> LocalDateTime {
741        self.utc.to_local()
742    }
743
744    /// strftime in the original offset.
745    #[must_use]
746    pub fn format(self, fmt: &str) -> format::Formatted<'_> {
747        format::Formatted::new(
748            format::Parts::with_offset(self.utc, self.offset_secs, None),
749            fmt,
750        )
751    }
752}
753
754impl From<OffsetDateTime> for UtcDateTime {
755    fn from(t: OffsetDateTime) -> Self {
756        t.utc
757    }
758}
759
760impl PartialEq for OffsetDateTime {
761    fn eq(&self, other: &Self) -> bool {
762        self.utc == other.utc
763    }
764}
765
766impl Eq for OffsetDateTime {}
767
768impl std::hash::Hash for OffsetDateTime {
769    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
770        self.utc.hash(state);
771    }
772}
773
774impl PartialEq<UtcDateTime> for OffsetDateTime {
775    fn eq(&self, other: &UtcDateTime) -> bool {
776        self.utc == *other
777    }
778}
779
780impl PartialEq<OffsetDateTime> for UtcDateTime {
781    fn eq(&self, other: &OffsetDateTime) -> bool {
782        *self == other.utc
783    }
784}
785
786impl PartialOrd<UtcDateTime> for OffsetDateTime {
787    fn partial_cmp(&self, other: &UtcDateTime) -> Option<std::cmp::Ordering> {
788        Some(self.utc.cmp(other))
789    }
790}
791
792impl PartialOrd<OffsetDateTime> for UtcDateTime {
793    fn partial_cmp(&self, other: &OffsetDateTime) -> Option<std::cmp::Ordering> {
794        Some(self.cmp(&other.utc))
795    }
796}
797
798impl Sub for OffsetDateTime {
799    type Output = Duration;
800    fn sub(self, other: Self) -> Duration {
801        self.utc.signed_duration_since(other)
802    }
803}
804
805impl Sub<UtcDateTime> for OffsetDateTime {
806    type Output = Duration;
807    fn sub(self, other: UtcDateTime) -> Duration {
808        self.utc.signed_duration_since(other)
809    }
810}
811
812impl Sub<OffsetDateTime> for UtcDateTime {
813    type Output = Duration;
814    fn sub(self, other: OffsetDateTime) -> Duration {
815        self.signed_duration_since(other)
816    }
817}
818
819impl Add<Duration> for OffsetDateTime {
820    type Output = Self;
821    fn add(self, d: Duration) -> Self {
822        self.checked_add_signed(d)
823            .expect("`OffsetDateTime + Duration` overflowed")
824    }
825}
826
827impl Sub<Duration> for OffsetDateTime {
828    type Output = Self;
829    fn sub(self, d: Duration) -> Self {
830        self.checked_sub_signed(d)
831            .expect("`OffsetDateTime - Duration` overflowed")
832    }
833}
834
835impl Ord for OffsetDateTime {
836    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
837        self.utc.cmp(&other.utc)
838    }
839}
840
841impl PartialOrd for OffsetDateTime {
842    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
843        Some(self.cmp(other))
844    }
845}
846
847impl fmt::Debug for OffsetDateTime {
848    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849        f.write_str(&self.to_rfc3339())
850    }
851}
852
853impl fmt::Display for OffsetDateTime {
854    /// `2026-11-17 11:00:00 +01:00`.
855    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
856        let s = self.format("%Y-%m-%d %H:%M:%S%.f %:z").to_string();
857        f.pad(&s)
858    }
859}
860
861// ---------------------------------------------------------------------------
862// LocalDateTime: the system time zone, for display
863// ---------------------------------------------------------------------------
864
865/// An instant in the system time zone, for text shown to people.
866#[derive(Clone, PartialEq, Eq)]
867pub struct LocalDateTime(jiff::Zoned);
868
869impl LocalDateTime {
870    /// The current time in the system time zone.
871    #[must_use]
872    pub fn now() -> Self {
873        Self(jiff::Zoned::now())
874    }
875
876    /// The instant in UTC.
877    #[must_use]
878    pub fn to_utc(&self) -> UtcDateTime {
879        UtcDateTime(self.0.timestamp())
880    }
881
882    /// Seconds east of UTC at this instant.
883    #[must_use]
884    pub fn offset_seconds(&self) -> i32 {
885        self.0.offset().seconds()
886    }
887
888    /// The local calendar date.
889    #[must_use]
890    pub fn date_naive(&self) -> civil::Date {
891        self.0.date()
892    }
893
894    /// The local calendar date and wall time.
895    #[must_use]
896    pub fn naive_local(&self) -> civil::DateTime {
897        self.0.datetime()
898    }
899
900    /// The local hour, `0..=23`.
901    #[must_use]
902    pub fn hour(&self) -> u32 {
903        u32::try_from(self.0.hour()).expect("hour is not negative")
904    }
905
906    /// RFC 3339 in the local offset.
907    #[must_use]
908    pub fn to_rfc3339(&self) -> String {
909        let mut out = String::with_capacity(32);
910        let parts = self.parts();
911        let offset = format::offset_colon(self.offset_seconds());
912        format::write_rfc3339(&mut out, &parts, SecondsFormat::AutoSi, &offset);
913        out
914    }
915
916    /// strftime in the local zone; `%Z` writes the offset (`+01:00`).
917    #[must_use]
918    pub fn format<'a>(&self, fmt: &'a str) -> format::Formatted<'a> {
919        format::Formatted::new(self.parts(), fmt)
920    }
921
922    fn parts(&self) -> format::Parts {
923        format::Parts::with_offset(self.to_utc(), self.offset_seconds(), None)
924    }
925
926    /// The jiff value underneath.
927    #[must_use]
928    pub fn as_jiff(&self) -> &jiff::Zoned {
929        &self.0
930    }
931}
932
933impl fmt::Debug for LocalDateTime {
934    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
935        f.write_str(&self.to_rfc3339())
936    }
937}
938
939impl fmt::Display for LocalDateTime {
940    /// `2026-11-17 11:00:00 +01:00`.
941    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
942        let s = self.format("%Y-%m-%d %H:%M:%S%.f %:z").to_string();
943        f.pad(&s)
944    }
945}
946
947// ---------------------------------------------------------------------------
948// Duration
949// ---------------------------------------------------------------------------
950
951/// A signed span of time with nanosecond precision.
952#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
953pub struct Duration(SignedDuration);
954
955macro_rules! ctor {
956    ($(#[$doc:meta])* $name:ident, $try_name:ident, $nanos:expr) => {
957        $(#[$doc])*
958        /// Panics when the span does not fit.
959        #[must_use]
960        pub const fn $name(n: i64) -> Self {
961            match Self::$try_name(n) {
962                Some(d) => d,
963                None => panic!(concat!("Duration::", stringify!($name), " out of bounds")),
964            }
965        }
966
967        $(#[$doc])*
968        /// `None` when the span does not fit.
969        #[must_use]
970        #[allow(clippy::cast_lossless)] // `i128::from` is not const
971        pub const fn $try_name(n: i64) -> Option<Self> {
972            Self::from_nanos_i128(n as i128 * $nanos)
973        }
974    };
975}
976
977impl Duration {
978    /// Zero.
979    pub const ZERO: Self = Self(SignedDuration::ZERO);
980
981    /// Zero.
982    #[must_use]
983    pub const fn zero() -> Self {
984        Self::ZERO
985    }
986
987    ctor!(
988        /// `n` weeks.
989        weeks,
990        try_weeks,
991        7 * 86_400 * NANOS_PER_SEC
992    );
993    ctor!(
994        /// `n` days of 24 hours.
995        days,
996        try_days,
997        86_400 * NANOS_PER_SEC
998    );
999    ctor!(
1000        /// `n` hours.
1001        hours,
1002        try_hours,
1003        3_600 * NANOS_PER_SEC
1004    );
1005    ctor!(
1006        /// `n` minutes.
1007        minutes,
1008        try_minutes,
1009        60 * NANOS_PER_SEC
1010    );
1011    ctor!(
1012        /// `n` seconds.
1013        seconds,
1014        try_seconds,
1015        NANOS_PER_SEC
1016    );
1017    ctor!(
1018        /// `n` milliseconds.
1019        milliseconds,
1020        try_milliseconds,
1021        1_000_000
1022    );
1023    ctor!(
1024        /// `n` microseconds.
1025        microseconds,
1026        try_microseconds,
1027        1_000
1028    );
1029
1030    /// `n` nanoseconds.
1031    #[must_use]
1032    pub fn nanoseconds(n: i64) -> Self {
1033        Self(SignedDuration::from_nanos(n))
1034    }
1035
1036    /// The largest span: `i64::MAX` milliseconds, the range LeanCTX's
1037    /// durations have always had; the smallest is its negation.
1038    pub const MAX: Self = Self(SignedDuration::new(
1039        i64::MAX / 1_000,
1040        (i64::MAX % 1_000) as i32 * 1_000_000,
1041    ));
1042    /// The smallest span: `-i64::MAX` milliseconds.
1043    pub const MIN: Self = Self(SignedDuration::new(
1044        -(i64::MAX / 1_000),
1045        -((i64::MAX % 1_000) as i32 * 1_000_000),
1046    ));
1047
1048    // const so that chrono's `const X: TimeDelta = TimeDelta::days(1)` keeps compiling.
1049    #[allow(clippy::cast_possible_truncation)]
1050    const fn from_nanos_i128(nanos: i128) -> Option<Self> {
1051        const LIMIT: i128 = i64::MAX as i128 * 1_000_000;
1052        if nanos < -LIMIT || nanos > LIMIT {
1053            return None;
1054        }
1055        // Both casts are lossless after the bound check above.
1056        let secs = (nanos / NANOS_PER_SEC) as i64;
1057        let sub = (nanos % NANOS_PER_SEC) as i32;
1058        Some(Self(SignedDuration::new(secs, sub)))
1059    }
1060
1061    fn nanos_i128(self) -> i128 {
1062        self.0.as_nanos()
1063    }
1064
1065    /// Whole weeks, truncated towards zero.
1066    #[must_use]
1067    pub fn num_weeks(self) -> i64 {
1068        self.num_days() / 7
1069    }
1070
1071    /// Whole days, truncated towards zero.
1072    #[must_use]
1073    pub fn num_days(self) -> i64 {
1074        self.num_seconds() / 86_400
1075    }
1076
1077    /// Whole hours, truncated towards zero.
1078    #[must_use]
1079    pub fn num_hours(self) -> i64 {
1080        self.num_seconds() / 3_600
1081    }
1082
1083    /// Whole minutes, truncated towards zero.
1084    #[must_use]
1085    pub fn num_minutes(self) -> i64 {
1086        self.num_seconds() / 60
1087    }
1088
1089    /// Whole seconds, truncated towards zero.
1090    #[must_use]
1091    pub fn num_seconds(self) -> i64 {
1092        self.0.as_secs()
1093    }
1094
1095    /// Whole milliseconds, truncated towards zero.
1096    #[must_use]
1097    pub fn num_milliseconds(self) -> i64 {
1098        i64::try_from(self.nanos_i128() / 1_000_000)
1099            .expect("milliseconds of an i64-second span fit i64")
1100    }
1101
1102    /// Whole microseconds, truncated towards zero; `None` past `i64`.
1103    #[must_use]
1104    pub fn num_microseconds(self) -> Option<i64> {
1105        i64::try_from(self.nanos_i128() / 1_000).ok()
1106    }
1107
1108    /// Nanoseconds; `None` past `i64`.
1109    #[must_use]
1110    pub fn num_nanoseconds(self) -> Option<i64> {
1111        i64::try_from(self.nanos_i128()).ok()
1112    }
1113
1114    /// The nanoseconds past [`Duration::num_seconds`], with its sign.
1115    #[must_use]
1116    pub fn subsec_nanos(self) -> i32 {
1117        self.0.subsec_nanos()
1118    }
1119
1120    /// Whole seconds as `f64`, with the fraction.
1121    #[must_use]
1122    pub fn as_seconds_f64(self) -> f64 {
1123        self.0.as_secs_f64()
1124    }
1125
1126    /// Zero?
1127    #[must_use]
1128    pub fn is_zero(self) -> bool {
1129        self.0.is_zero()
1130    }
1131
1132    /// Below zero?
1133    #[must_use]
1134    pub fn is_negative(self) -> bool {
1135        self.0.is_negative()
1136    }
1137
1138    /// The absolute value.
1139    #[must_use]
1140    pub fn abs(self) -> Self {
1141        Self(self.0.abs())
1142    }
1143
1144    /// `self + rhs`, `None` outside [`Duration::MIN`]..=[`Duration::MAX`].
1145    #[must_use]
1146    pub fn checked_add(&self, rhs: &Self) -> Option<Self> {
1147        Self::from_nanos_i128(self.nanos_i128() + rhs.nanos_i128())
1148    }
1149
1150    /// `self - rhs`, `None` outside [`Duration::MIN`]..=[`Duration::MAX`].
1151    #[must_use]
1152    pub fn checked_sub(&self, rhs: &Self) -> Option<Self> {
1153        Self::from_nanos_i128(self.nanos_i128() - rhs.nanos_i128())
1154    }
1155
1156    /// From a std duration; `Err` past [`Duration::MAX`].
1157    pub fn from_std(d: std::time::Duration) -> Result<Self, OutOfRangeError> {
1158        Self::from_nanos_i128(i128::try_from(d.as_nanos()).map_err(|_| OutOfRangeError)?)
1159            .ok_or(OutOfRangeError)
1160    }
1161
1162    /// To a std duration; `Err` when negative.
1163    pub fn to_std(self) -> Result<std::time::Duration, OutOfRangeError> {
1164        std::time::Duration::try_from(self.0).map_err(|_| OutOfRangeError)
1165    }
1166
1167    /// Wraps a jiff signed duration.
1168    #[must_use]
1169    pub const fn from_jiff(d: SignedDuration) -> Self {
1170        Self(d)
1171    }
1172
1173    /// The jiff signed duration underneath.
1174    #[must_use]
1175    pub const fn as_jiff(self) -> SignedDuration {
1176        self.0
1177    }
1178}
1179
1180impl Add for Duration {
1181    type Output = Self;
1182    fn add(self, rhs: Self) -> Self {
1183        self.checked_add(&rhs)
1184            .expect("`Duration + Duration` overflowed")
1185    }
1186}
1187
1188impl Sub for Duration {
1189    type Output = Self;
1190    fn sub(self, rhs: Self) -> Self {
1191        self.checked_sub(&rhs)
1192            .expect("`Duration - Duration` overflowed")
1193    }
1194}
1195
1196impl AddAssign for Duration {
1197    fn add_assign(&mut self, rhs: Self) {
1198        *self = *self + rhs;
1199    }
1200}
1201
1202impl SubAssign for Duration {
1203    fn sub_assign(&mut self, rhs: Self) {
1204        *self = *self - rhs;
1205    }
1206}
1207
1208impl Neg for Duration {
1209    type Output = Self;
1210    fn neg(self) -> Self {
1211        Self(-self.0)
1212    }
1213}
1214
1215impl Mul<i32> for Duration {
1216    type Output = Self;
1217    fn mul(self, rhs: i32) -> Self {
1218        Self::from_nanos_i128(self.nanos_i128() * i128::from(rhs))
1219            .expect("`Duration * i32` overflowed")
1220    }
1221}
1222
1223impl Div<i32> for Duration {
1224    type Output = Self;
1225    fn div(self, rhs: i32) -> Self {
1226        assert!(rhs != 0, "`Duration / i32` divided by zero");
1227        // chrono's two-step division (whole seconds, then the nanosecond
1228        // part with the carried remainder), so results agree to the
1229        // nanosecond, including its truncation.
1230        let total = self.nanos_i128();
1231        let (secs, nanos) = (
1232            total.div_euclid(NANOS_PER_SEC),
1233            total.rem_euclid(NANOS_PER_SEC),
1234        );
1235        let rhs = i128::from(rhs);
1236        let mut q_secs = secs / rhs;
1237        let carry = secs % rhs;
1238        let mut q_nanos = nanos / rhs + carry * NANOS_PER_SEC / rhs;
1239        if q_nanos < 0 {
1240            q_secs -= 1;
1241            q_nanos += NANOS_PER_SEC;
1242        } else if q_nanos >= NANOS_PER_SEC {
1243            q_secs += 1;
1244            q_nanos -= NANOS_PER_SEC;
1245        }
1246        Self::from_nanos_i128(q_secs * NANOS_PER_SEC + q_nanos).expect("a quotient stays in range")
1247    }
1248}
1249
1250impl std::iter::Sum for Duration {
1251    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
1252        iter.fold(Self::ZERO, Add::add)
1253    }
1254}
1255
1256impl<'a> std::iter::Sum<&'a Duration> for Duration {
1257    fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
1258        iter.copied().sum()
1259    }
1260}
1261
1262impl fmt::Debug for Duration {
1263    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1264        fmt::Display::fmt(self, f)
1265    }
1266}
1267
1268impl fmt::Display for Duration {
1269    /// ISO 8601 in seconds: `PT90S`, `PT0.25S`, `-PT1.5S`, `P0D` for zero.
1270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1271        let nanos = self.nanos_i128();
1272        let sign = if nanos < 0 { "-" } else { "" };
1273        let abs = nanos.unsigned_abs();
1274        if abs == 0 {
1275            return f.write_str("P0D");
1276        }
1277        let secs = abs / 1_000_000_000;
1278        let mut frac = abs % 1_000_000_000;
1279        write!(f, "{sign}PT{secs}")?;
1280        if frac > 0 {
1281            let mut width = 9usize;
1282            while frac.is_multiple_of(10) {
1283                frac /= 10;
1284                width -= 1;
1285            }
1286            write!(f, ".{frac:0width$}")?;
1287        }
1288        f.write_str("S")
1289    }
1290}
1291
1292#[cfg(test)]
1293#[allow(clippy::unwrap_used)]
1294mod tests;