Skip to main content

domainforge_core/
timefmt.rs

1//! Exact RFC 3339 formatting, parsing and serde adapters on top of the `time`
2//! crate.
3//!
4//! DomainForge used to depend on `chrono` (RUSTSEC-2026-0543: unmaintained).
5//! Several timestamps are signed, digested or placed on the wire, so the
6//! replacement has to reproduce chrono's bytes exactly: `time`'s own defaults
7//! (`Z` instead of `+00:00`, trimmed fractions, tuple serde) differ from every
8//! format chrono produced. Everything that formats or parses a timestamp or a
9//! duration therefore goes through this module.
10//!
11//! | function                  | chrono equivalent                              | example                          |
12//! |---------------------------|------------------------------------------------|----------------------------------|
13//! | [`to_rfc3339`]            | `DateTime<Utc>::to_rfc3339()`                  | `2024-01-02T03:04:05.5+00:00`    |
14//! | [`to_rfc3339_z`]          | `to_rfc3339_opts(AutoSi, true)` and serde      | `2024-01-02T03:04:05.500Z`       |
15//! | [`to_rfc3339_micros_z`]   | `to_rfc3339_opts(Micros, true)`                | `2024-01-02T03:04:05.500000Z`    |
16//! | [`to_rfc3339_millis_z`]   | `to_rfc3339_opts(Millis, true)`                | `2024-01-02T03:04:05.500Z`       |
17//! | [`to_rfc3339_secs_z`]     | `to_rfc3339_opts(Secs, true)`                  | `2024-01-02T03:04:05Z`           |
18//! | [`parse_rfc3339`]         | `DateTime::parse_from_rfc3339`                 |                                  |
19//! | [`parse_relaxed`]         | `str::parse::<DateTime<Utc>>` (serde input)    |                                  |
20//!
21//! The fraction of the "AutoSi" formats is 0, 3, 6 or 9 digits, whichever is
22//! the shortest that is exact. Years outside `0..=9999` are written with an
23//! explicit sign and at least four digits (`+10000`, `-0001`), as chrono does.
24//!
25//! # The one thing `time` cannot represent
26//!
27//! chrono keeps leap seconds (`23:59:60`) as an out-of-range nanosecond.
28//! `time` has no such value. [`parse_rfc3339`] still accepts a `:60` second
29//! (so comparisons keep working) and folds it into the last nanosecond of
30//! second 59, which orders it after every earlier instant and before the next
31//! second, as chrono did. Anything that *stores* a parsed value
32//! ([`parse_rfc3339_exact`], [`parse_relaxed`], the serde adapters) rejects it
33//! with [`ParseError::LeapSecond`] instead of silently emitting different
34//! bytes.
35
36use std::fmt;
37use time::{Date, Month, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset};
38
39/// chrono's `NaiveDate` range: `-262143-01-01 ..= +262142-12-31`.
40const MIN_YEAR: i32 = -262_143;
41const MAX_YEAR: i32 = 262_142;
42
43/// Why a timestamp failed to parse. The `Display` text of every variant but
44/// [`ParseError::LeapSecond`] is identical to chrono's `ParseError`, because
45/// those messages reach users through policy and CLI errors.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum ParseError {
48    /// A field is outside its range (month 13, hour 24, offset +24:00, ...).
49    OutOfRange,
50    /// Fields that cannot describe one instant.
51    Impossible,
52    /// Too little information to build an instant.
53    NotEnough,
54    /// An unexpected character.
55    Invalid,
56    /// The input ended early.
57    TooShort,
58    /// Characters remain after a complete timestamp.
59    TooLong,
60    /// A `:60` leap second, which `time` cannot represent.
61    LeapSecond,
62}
63
64impl fmt::Display for ParseError {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.write_str(match self {
67            Self::OutOfRange => "input is out of range",
68            Self::Impossible => "no possible date and time matching input",
69            Self::NotEnough => "input is not enough for unique date and time",
70            Self::Invalid => "input contains invalid characters",
71            Self::TooShort => "premature end of input",
72            Self::TooLong => "trailing input",
73            Self::LeapSecond => "leap seconds (:60) are not representable",
74        })
75    }
76}
77
78impl std::error::Error for ParseError {}
79
80type PResult<T> = Result<T, ParseError>;
81
82// ---------------------------------------------------------------------------
83// Clock
84// ---------------------------------------------------------------------------
85
86/// The current instant in UTC.
87pub fn now() -> OffsetDateTime {
88    OffsetDateTime::now_utc()
89}
90
91/// `Utc::now().to_rfc3339()`
92pub fn now_rfc3339() -> String {
93    to_rfc3339(now())
94}
95
96/// `Utc::now().to_rfc3339_opts(SecondsFormat::Micros, true)`
97pub fn now_micros_z() -> String {
98    to_rfc3339_micros_z(now())
99}
100
101/// `DateTime::from_timestamp(secs, 0)`: `None` outside chrono's range.
102pub fn from_unix_timestamp(secs: i64) -> Option<OffsetDateTime> {
103    let dt = OffsetDateTime::from_unix_timestamp(secs).ok()?;
104    year_in_range(dt.year()).then_some(dt)
105}
106
107fn year_in_range(year: i32) -> bool {
108    (MIN_YEAR..=MAX_YEAR).contains(&year)
109}
110
111// ---------------------------------------------------------------------------
112// Formatting
113// ---------------------------------------------------------------------------
114
115#[derive(Clone, Copy)]
116enum Fraction {
117    Auto,
118    Millis,
119    Micros,
120    Secs,
121}
122
123/// `DateTime<Utc>::to_rfc3339()`: `+00:00`, AutoSi fraction.
124pub fn to_rfc3339(dt: OffsetDateTime) -> String {
125    format_utc(dt, Fraction::Auto, false)
126}
127
128/// `to_rfc3339_opts(AutoSi, true)`; also chrono's serde output.
129pub fn to_rfc3339_z(dt: OffsetDateTime) -> String {
130    format_utc(dt, Fraction::Auto, true)
131}
132
133/// `to_rfc3339_opts(Micros, true)`: always six fraction digits.
134pub fn to_rfc3339_micros_z(dt: OffsetDateTime) -> String {
135    format_utc(dt, Fraction::Micros, true)
136}
137
138/// `to_rfc3339_opts(Millis, true)`: always three fraction digits.
139pub fn to_rfc3339_millis_z(dt: OffsetDateTime) -> String {
140    format_utc(dt, Fraction::Millis, true)
141}
142
143/// `to_rfc3339_opts(Secs, true)`: no fraction.
144pub fn to_rfc3339_secs_z(dt: OffsetDateTime) -> String {
145    format_utc(dt, Fraction::Secs, true)
146}
147
148fn format_utc(dt: OffsetDateTime, fraction: Fraction, zulu: bool) -> String {
149    let dt = dt.to_offset(UtcOffset::UTC);
150    let year = dt.year();
151    let nanos = dt.nanosecond();
152    let mut out = String::with_capacity(35);
153    if (0..=9999).contains(&year) {
154        out.push_str(&format!("{year:04}"));
155    } else {
156        out.push_str(&format!("{year:+05}"));
157    }
158    out.push_str(&format!(
159        "-{:02}-{:02}T{:02}:{:02}:{:02}",
160        u8::from(dt.month()),
161        dt.day(),
162        dt.hour(),
163        dt.minute(),
164        dt.second()
165    ));
166    match fraction {
167        Fraction::Auto => {
168            if nanos == 0 {
169            } else if nanos.is_multiple_of(1_000_000) {
170                out.push_str(&format!(".{:03}", nanos / 1_000_000));
171            } else if nanos.is_multiple_of(1_000) {
172                out.push_str(&format!(".{:06}", nanos / 1_000));
173            } else {
174                out.push_str(&format!(".{nanos:09}"));
175            }
176        }
177        Fraction::Millis => out.push_str(&format!(".{:03}", nanos / 1_000_000)),
178        Fraction::Micros => out.push_str(&format!(".{:06}", nanos / 1_000)),
179        Fraction::Secs => {}
180    }
181    out.push_str(if zulu { "Z" } else { "+00:00" });
182    out
183}
184
185// ---------------------------------------------------------------------------
186// Scanning (a port of chrono's `format::scan`, enough for RFC 3339)
187// ---------------------------------------------------------------------------
188
189/// Non-negative number of `min..=max` digits; more than `max` digits are left
190/// in the remainder.
191fn number(s: &str, min: usize, max: usize) -> PResult<(&str, i64)> {
192    let bytes = s.as_bytes();
193    if bytes.len() < min {
194        return Err(ParseError::TooShort);
195    }
196    let mut n = 0i64;
197    for (i, &c) in bytes.iter().take(max).enumerate() {
198        if !c.is_ascii_digit() {
199            if i < min {
200                return Err(ParseError::Invalid);
201            }
202            return Ok((&s[i..], n));
203        }
204        n = n
205            .checked_mul(10)
206            .and_then(|n| n.checked_add(i64::from(c - b'0')))
207            .ok_or(ParseError::OutOfRange)?;
208    }
209    Ok((&s[max.min(bytes.len())..], n))
210}
211
212/// Fractional seconds (at least one digit) as nanoseconds; digits past the
213/// ninth are skipped.
214fn nanosecond(s: &str) -> PResult<(&str, u32)> {
215    let orig = s.len();
216    let (s, v) = number(s, 1, 9)?;
217    let consumed = orig - s.len();
218    let v = u32::try_from(v).map_err(|_| ParseError::OutOfRange)?;
219    let v = v * 10u32.pow(9 - consumed as u32);
220    Ok((s.trim_start_matches(|c: char| c.is_ascii_digit()), v))
221}
222
223fn char(s: &str, c1: u8) -> PResult<&str> {
224    match s.as_bytes().first() {
225        Some(&c) if c == c1 => Ok(&s[1..]),
226        Some(_) => Err(ParseError::Invalid),
227        None => Err(ParseError::TooShort),
228    }
229}
230
231fn colon(s: &str) -> PResult<&str> {
232    char(s, b':')
233}
234
235fn colon_or_space(s: &str) -> PResult<&str> {
236    Ok(s.trim_start_matches(|c: char| c == ':' || c.is_whitespace()))
237}
238
239/// `Z`/`z` or `+hh<sep>mm` (also `-` and U+2212). Returns seconds east.
240fn timezone_offset(mut s: &str, consume_colon: fn(&str) -> PResult<&str>) -> PResult<(&str, i32)> {
241    if let Some(&b'Z' | &b'z') = s.as_bytes().first() {
242        return Ok((&s[1..], 0));
243    }
244    let digits = |s: &str| -> PResult<(u8, u8)> {
245        let b = s.as_bytes();
246        if b.len() < 2 {
247            Err(ParseError::TooShort)
248        } else {
249            Ok((b[0], b[1]))
250        }
251    };
252    let negative = match s.chars().next() {
253        Some('+') => {
254            s = &s[1..];
255            false
256        }
257        Some('-') => {
258            s = &s[1..];
259            true
260        }
261        Some('\u{2212}') => {
262            s = &s['\u{2212}'.len_utf8()..];
263            true
264        }
265        Some(_) => return Err(ParseError::Invalid),
266        None => return Err(ParseError::TooShort),
267    };
268    let hours = match digits(s)? {
269        (h1 @ b'0'..=b'9', h2 @ b'0'..=b'9') => i32::from((h1 - b'0') * 10 + (h2 - b'0')),
270        _ => return Err(ParseError::Invalid),
271    };
272    s = &s[2..];
273    s = consume_colon(s)?;
274    let minutes = if let Ok(ds) = digits(s) {
275        match ds {
276            (m1 @ b'0'..=b'5', m2 @ b'0'..=b'9') => i32::from((m1 - b'0') * 10 + (m2 - b'0')),
277            (b'6'..=b'9', b'0'..=b'9') => return Err(ParseError::OutOfRange),
278            _ => return Err(ParseError::Invalid),
279        }
280    } else {
281        return Err(ParseError::TooShort);
282    };
283    s = match s.len() {
284        len if len >= 2 => &s[2..],
285        0 => s,
286        _ => return Err(ParseError::TooShort),
287    };
288    let seconds = hours * 3600 + minutes * 60;
289    Ok((s, if negative { -seconds } else { seconds }))
290}
291
292// ---------------------------------------------------------------------------
293// Building an instant
294// ---------------------------------------------------------------------------
295
296struct Fields {
297    year: i32,
298    month: u32,
299    day: u32,
300    hour: u32,
301    minute: u32,
302    /// 0..=60
303    second: u32,
304    nano: u32,
305    offset_secs: i32,
306}
307
308/// Returns the instant (carrying its offset) and whether the input was a
309/// `:60` leap second (folded into the last nanosecond of second 59).
310fn build(f: &Fields) -> PResult<(OffsetDateTime, bool)> {
311    if !year_in_range(f.year) {
312        return Err(ParseError::OutOfRange);
313    }
314    let month = u8::try_from(f.month)
315        .ok()
316        .and_then(|m| Month::try_from(m).ok())
317        .ok_or(ParseError::OutOfRange)?;
318    let date =
319        Date::from_calendar_date(f.year, month, f.day as u8).map_err(|_| ParseError::OutOfRange)?;
320    let leap = f.second == 60;
321    // A leap second sorts after every fraction of second 59 and before the next
322    // second, as in chrono; the closest `time` value is the last nanosecond of
323    // second 59.
324    let (second, nano) = if leap {
325        (59, 999_999_999)
326    } else {
327        (f.second, f.nano)
328    };
329    let time = Time::from_hms_nano(f.hour as u8, f.minute as u8, second as u8, nano)
330        .map_err(|_| ParseError::OutOfRange)?;
331    // chrono rejects offsets of a day or more; `time` allows up to 25:59:59
332    if f.offset_secs.abs() >= 86_400 {
333        return Err(ParseError::OutOfRange);
334    }
335    let offset =
336        UtcOffset::from_whole_seconds(f.offset_secs).map_err(|_| ParseError::OutOfRange)?;
337    let dt = PrimitiveDateTime::new(date, time).assume_offset(offset);
338    // the UTC instant must also fit chrono's range
339    dt.checked_to_offset(UtcOffset::UTC)
340        .filter(|u| year_in_range(u.year()))
341        .ok_or(ParseError::Impossible)?;
342    Ok((dt, leap))
343}
344
345// ---------------------------------------------------------------------------
346// Parsing
347// ---------------------------------------------------------------------------
348
349fn digit(bytes: &[u8], index: usize) -> PResult<u32> {
350    if bytes[index].is_ascii_digit() {
351        Ok(u32::from(bytes[index] - b'0'))
352    } else {
353        Err(ParseError::Invalid)
354    }
355}
356
357fn parse_strict_fields(mut s: &str) -> PResult<Fields> {
358    let bytes = s.as_bytes();
359    if bytes.len() < 19 {
360        return Err(ParseError::TooShort);
361    }
362    let year =
363        digit(bytes, 0)? * 1000 + digit(bytes, 1)? * 100 + digit(bytes, 2)? * 10 + digit(bytes, 3)?;
364    if bytes.get(4) != Some(&b'-') {
365        return Err(ParseError::Invalid);
366    }
367    let month = digit(bytes, 5)? * 10 + digit(bytes, 6)?;
368    if bytes.get(7) != Some(&b'-') {
369        return Err(ParseError::Invalid);
370    }
371    let day = digit(bytes, 8)? * 10 + digit(bytes, 9)?;
372    // the date must exist before the rest is looked at (chrono's order)
373    let month_enum = u8::try_from(month)
374        .ok()
375        .and_then(|m| Month::try_from(m).ok())
376        .ok_or(ParseError::OutOfRange)?;
377    Date::from_calendar_date(year as i32, month_enum, day as u8)
378        .map_err(|_| ParseError::OutOfRange)?;
379    if !matches!(bytes.get(10), Some(&b't' | &b'T' | &b' ')) {
380        return Err(ParseError::Invalid);
381    }
382    let hour = digit(bytes, 11)? * 10 + digit(bytes, 12)?;
383    if bytes.get(13) != Some(&b':') {
384        return Err(ParseError::Invalid);
385    }
386    let minute = digit(bytes, 14)? * 10 + digit(bytes, 15)?;
387    if bytes.get(16) != Some(&b':') {
388        return Err(ParseError::Invalid);
389    }
390    let second = digit(bytes, 17)? * 10 + digit(bytes, 18)?;
391    let nano = if bytes.get(19) == Some(&b'.') {
392        let (rest, nano) = nanosecond(&s[20..])?;
393        s = rest;
394        nano
395    } else {
396        s = &s[19..];
397        0
398    };
399    if hour >= 24 || minute >= 60 || second > 60 {
400        return Err(ParseError::OutOfRange);
401    }
402    let (rest, offset_secs) = timezone_offset(s, colon)?;
403    if !rest.is_empty() {
404        return Err(ParseError::TooLong);
405    }
406    Ok(Fields {
407        year: year as i32,
408        month,
409        day,
410        hour,
411        minute,
412        second,
413        nano,
414        offset_secs,
415    })
416}
417
418/// `DateTime::parse_from_rfc3339`: strict RFC 3339 (`T`, `t` or a space between
419/// date and time, `Z`/`z`/`±hh:mm`, any number of fraction digits). The result
420/// keeps the input's offset; instants compare and order correctly regardless.
421///
422/// A `:60` leap second is accepted and folded into the last nanosecond of
423/// second 59 (see the module docs); use [`parse_rfc3339_exact`] where the value will be stored.
424pub fn parse_rfc3339(s: &str) -> Result<OffsetDateTime, ParseError> {
425    build(&parse_strict_fields(s)?).map(|(dt, _)| dt)
426}
427
428/// [`parse_rfc3339`], but rejects a leap second with [`ParseError::LeapSecond`].
429pub fn parse_rfc3339_exact(s: &str) -> Result<OffsetDateTime, ParseError> {
430    match build(&parse_strict_fields(s)?)? {
431        (_, true) => Err(ParseError::LeapSecond),
432        (dt, false) => Ok(dt),
433    }
434}
435
436/// Relaxed RFC 3339, exactly what chrono's `FromStr`/serde accepted: values
437/// need no zero padding, years outside `0..=9999` take a sign, whitespace may
438/// separate components, `UTC` is a valid zone, and the offset colon may be a
439/// space or missing. Returns the instant in UTC. A leap second is rejected.
440pub fn parse_relaxed(s: &str) -> Result<OffsetDateTime, ParseError> {
441    let fields = parse_relaxed_fields(s)?;
442    match build(&fields)? {
443        (_, true) => Err(ParseError::LeapSecond),
444        (dt, false) => Ok(dt.to_offset(UtcOffset::UTC)),
445    }
446}
447
448fn signed_or_width(s: &str, width: usize) -> PResult<(&str, i64)> {
449    if let Some(rest) = s.strip_prefix('-') {
450        let (rest, v) = number(rest, 1, usize::MAX)?;
451        Ok((rest, 0i64.checked_sub(v).ok_or(ParseError::OutOfRange)?))
452    } else if let Some(rest) = s.strip_prefix('+') {
453        number(rest, 1, usize::MAX)
454    } else {
455        number(s, 1, width)
456    }
457}
458
459fn parse_relaxed_fields(s: &str) -> PResult<Fields> {
460    let literal = |s: &str, lit: &str| -> PResult<()> {
461        if s.len() < lit.len() {
462            return Err(ParseError::TooShort);
463        }
464        if !s.starts_with(lit) {
465            return Err(ParseError::Invalid);
466        }
467        Ok(())
468    };
469    // year
470    let s = s.trim_start();
471    let (s, year) = signed_or_width(s, 4)?;
472    let year = i32::try_from(year).map_err(|_| ParseError::OutOfRange)?;
473    let s = s.trim_start();
474    literal(s, "-")?;
475    let s = &s[1..];
476    // month
477    let s = s.trim_start();
478    let (s, month) = number(s, 1, 2)?;
479    if !(1..=12).contains(&month) {
480        return Err(ParseError::OutOfRange);
481    }
482    let s = s.trim_start();
483    literal(s, "-")?;
484    let s = &s[1..];
485    // day
486    let s = s.trim_start();
487    let (s, day) = number(s, 1, 2)?;
488    if !(1..=31).contains(&day) {
489        return Err(ParseError::OutOfRange);
490    }
491    // separator
492    let s = match s.as_bytes().first() {
493        Some(&b't' | &b'T' | &b' ') => &s[1..],
494        Some(_) => return Err(ParseError::Invalid),
495        None => return Err(ParseError::TooShort),
496    };
497    // hour
498    let s = s.trim_start();
499    let (s, hour) = number(s, 1, 2)?;
500    if !(0..=23).contains(&hour) {
501        return Err(ParseError::OutOfRange);
502    }
503    let s = s.trim_start();
504    literal(s, ":")?;
505    let s = &s[1..];
506    // minute
507    let s = s.trim_start();
508    let (s, minute) = number(s, 1, 2)?;
509    if !(0..=59).contains(&minute) {
510        return Err(ParseError::OutOfRange);
511    }
512    let s = s.trim_start();
513    literal(s, ":")?;
514    let s = &s[1..];
515    // second
516    let s = s.trim_start();
517    let (s, second) = number(s, 1, 2)?;
518    if !(0..=60).contains(&second) {
519        return Err(ParseError::OutOfRange);
520    }
521    // optional fraction
522    let (s, nano) = if let Some(rest) = s.strip_prefix('.') {
523        nanosecond(rest)?
524    } else {
525        (s, 0)
526    };
527    // offset
528    let s = s.trim_start();
529    let (s, offset_secs) = if s.len() >= 3 && s.as_bytes()[..3].eq_ignore_ascii_case(b"UTC") {
530        (&s[3..], 0)
531    } else {
532        timezone_offset(s, colon_or_space)?
533    };
534    if !s.trim_start().is_empty() {
535        return Err(ParseError::TooLong);
536    }
537    Ok(Fields {
538        year,
539        month: month as u32,
540        day: day as u32,
541        hour: hour as u32,
542        minute: minute as u32,
543        second: second as u32,
544        nano,
545        offset_secs,
546    })
547}
548
549// ---------------------------------------------------------------------------
550// serde adapters
551// ---------------------------------------------------------------------------
552
553/// `#[serde(with = "crate::timefmt::serde_ts")]` for `OffsetDateTime`:
554/// serializes as [`to_rfc3339_z`], deserializes with [`parse_relaxed`], like
555/// chrono's `DateTime<Utc>` serde.
556pub mod serde_ts {
557    use super::*;
558    use serde::{de, Deserializer, Serializer};
559
560    pub fn serialize<S: Serializer>(dt: &OffsetDateTime, s: S) -> Result<S::Ok, S::Error> {
561        s.serialize_str(&to_rfc3339_z(*dt))
562    }
563
564    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<OffsetDateTime, D::Error> {
565        struct Visitor;
566        impl de::Visitor<'_> for Visitor {
567            type Value = OffsetDateTime;
568            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
569                f.write_str("a formatted date and time string")
570            }
571            fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
572                parse_relaxed(v).map_err(E::custom)
573            }
574        }
575        d.deserialize_str(Visitor)
576    }
577}
578
579/// [`serde_ts`] for `Option<OffsetDateTime>` (`null` / missing is `None`).
580pub mod serde_ts_option {
581    use super::*;
582    use serde::{Deserialize, Deserializer, Serialize, Serializer};
583
584    pub fn serialize<S: Serializer>(dt: &Option<OffsetDateTime>, s: S) -> Result<S::Ok, S::Error> {
585        dt.map(to_rfc3339_z).serialize(s)
586    }
587
588    pub fn deserialize<'de, D: Deserializer<'de>>(
589        d: D,
590    ) -> Result<Option<OffsetDateTime>, D::Error> {
591        use serde::de::Error;
592        Option::<String>::deserialize(d)?
593            .map(|v| parse_relaxed(&v).map_err(D::Error::custom))
594            .transpose()
595    }
596}
597
598/// chrono serialized a `TimeDelta` as the tuple `(secs, nanos)` with the
599/// seconds rounded toward negative infinity and `0 <= nanos < 1e9`.
600pub mod serde_duration {
601    use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
602
603    /// chrono's `TimeDelta` holds at most `i64::MAX` milliseconds either way.
604    const LIMIT_NANOS: i128 = (i64::MAX as i128) * 1_000_000;
605
606    pub(super) fn to_parts(d: time::Duration) -> (i64, i32) {
607        let mut secs = d.whole_seconds();
608        let mut nanos = d.subsec_nanoseconds();
609        if nanos < 0 {
610            secs -= 1;
611            nanos += 1_000_000_000;
612        }
613        (secs, nanos)
614    }
615
616    pub(super) fn from_parts(secs: i64, nanos: i32) -> Option<time::Duration> {
617        let nanos = u32::try_from(nanos).ok().filter(|n| *n < 1_000_000_000)?;
618        let total = i128::from(secs) * 1_000_000_000 + i128::from(nanos);
619        if !(-LIMIT_NANOS..=LIMIT_NANOS).contains(&total) {
620            return None;
621        }
622        Some(time::Duration::new(secs, nanos as i32))
623    }
624
625    pub fn serialize<S: Serializer>(d: &time::Duration, s: S) -> Result<S::Ok, S::Error> {
626        to_parts(*d).serialize(s)
627    }
628
629    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<time::Duration, D::Error> {
630        let (secs, nanos) = <(i64, i32)>::deserialize(d)?;
631        from_parts(secs, nanos).ok_or_else(|| D::Error::custom("TimeDelta out of bounds"))
632    }
633}
634
635/// [`serde_duration`] for `Option<time::Duration>`.
636pub mod serde_duration_option {
637    use super::*;
638    use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
639
640    pub fn serialize<S: Serializer>(d: &Option<time::Duration>, s: S) -> Result<S::Ok, S::Error> {
641        d.map(serde_duration::to_parts).serialize(s)
642    }
643
644    pub fn deserialize<'de, D: Deserializer<'de>>(
645        d: D,
646    ) -> Result<Option<time::Duration>, D::Error> {
647        Option::<(i64, i32)>::deserialize(d)?
648            .map(|(secs, nanos)| {
649                serde_duration::from_parts(secs, nanos)
650                    .ok_or_else(|| D::Error::custom("TimeDelta out of bounds"))
651            })
652            .transpose()
653    }
654}