Skip to main content

jiff/fmt/
util.rs

1use jcore::{bounds::Sign, constants as c};
2
3use crate::{
4    Error, SignedDuration, Span, Unit,
5    error::{ErrorContext, fmt::util::Error as E},
6    fmt::Parsed,
7    util::{b, parse},
8};
9
10/// A container for holding a partially parsed duration.
11///
12/// This is used for parsing into `Span`, `SignedDuration` and (hopefully
13/// soon) `std::time::Duration`. It's _also_ used for both the ISO 8601
14/// duration and "friendly" format.
15///
16/// This replaced a significant chunk of code that was bespoke to each
17/// combination of duration type _and_ format.
18///
19/// The idea behind it is that we parse each duration component as an unsigned
20/// 64-bit integer and keep track of the sign separately. This is a critical
21/// aspect that was motivated by being able to roundtrip all legal values of
22/// a 96-bit signed integer number of nanoseconds (i.e., `SignedDuration`).
23/// In particular, if we used `i64` to represent each component, then it
24/// makes it much more difficult to parse, e.g., `9223372036854775808
25/// seconds ago`. Namely, `9223372036854775808` is not a valid `i64` but
26/// `-9223372036854775808` is. Notably, the sign is indicated by a suffix,
27/// so we don't know it's negative when parsing the integer itself. So we
28/// represent all components as their unsigned absolute value and apply the
29/// sign at the end.
30///
31/// This also centralizes a lot of thorny duration math and opens up the
32/// opportunity for tighter optimization.
33#[derive(#[automatically_derived]impl ::core::fmt::Debug for DurationUnits {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_fields_finish(f,
            "DurationUnits values fraction sign min max any_non_zero_units",
            &[&self.values, &self.fraction, &self.sign, &self.min, &self.max,
                        &&self.any_non_zero_units])
    }
}Debug, #[automatically_derived]impl ::core::default::Default for DurationUnits {
    #[inline]
    fn default() -> Self {
        DurationUnits {
            values: ::core::default::Default::default(),
            fraction: ::core::default::Default::default(),
            sign: ::core::default::Default::default(),
            min: ::core::default::Default::default(),
            max: ::core::default::Default::default(),
            any_non_zero_units: ::core::default::Default::default(),
        }
    }
}Default)]
34pub(crate) struct DurationUnits {
35    /// The parsed unit values in descending order. That is, nanoseconds are
36    /// at index 0 while years are at index 9.
37    values: [u64; 10],
38    /// Any fractional component parsed. The fraction is necessarily a fraction
39    /// of the minimum unit if present.
40    fraction: Option<u32>,
41    /// The sign of the duration. This may be set at any time.
42    ///
43    /// Note that this defaults to zero! So callers will always want to set
44    /// this.
45    sign: Sign,
46    /// The smallest unit value that was explicitly set.
47    min: Option<Unit>,
48    /// The largest unit value that was explicitly set.
49    max: Option<Unit>,
50    /// Whether there are any non-zero units.
51    any_non_zero_units: bool,
52}
53
54impl DurationUnits {
55    /// Set the duration component value for the given unit.
56    ///
57    /// The value here is always unsigned. To deal with negative values, set
58    /// the sign independently. It will be accounted for when using one of this
59    /// type's methods for converting to a concrete duration type.
60    ///
61    /// # Panics
62    ///
63    /// When this is called after `set_fraction`.
64    ///
65    /// # Errors
66    ///
67    /// Since this is meant to be used in service of duration parsing and all
68    /// duration parsing proceeds from largest to smallest units, this will
69    /// return an error if the given unit is bigger than or equal to any
70    /// previously set unit. This also implies that this can only be called
71    /// at most once for each unit value.
72    #[cfg_attr(feature = "perf-inline", inline(always))]
73    pub(crate) fn set_unit_value(
74        &mut self,
75        unit: Unit,
76        value: u64,
77    ) -> Result<(), Error> {
78        if !self.fraction.is_none() {
    ::core::panicking::panic("assertion failed: self.fraction.is_none()")
};assert!(self.fraction.is_none());
79
80        if let Some(min) = self.min {
81            if min <= unit {
82                return Err(Error::from(E::OutOfOrderUnits {
83                    found: unit,
84                    previous: min,
85                }));
86            }
87        }
88        // Given the above check, the given unit must be smaller than any we
89        // have seen so far.
90        self.min = Some(unit);
91        // The maximum unit is always the first unit set, since we can never
92        // see a unit bigger than it without an error occurring.
93        if self.max.is_none() {
94            self.max = Some(unit);
95        }
96        self.values[unit.as_usize()] = value;
97        self.any_non_zero_units = self.any_non_zero_units || value != 0;
98        Ok(())
99    }
100
101    /// A convenience routine for setting values parsed from an `HH:MM:SS`
102    /// format (including the fraction).
103    ///
104    /// # Errors
105    ///
106    /// This forwards errors from `DurationUnits::set_unit_value`. It will also
107    /// return an error is the minimum parsed unit (so far) is smaller than
108    /// days. (Since `HH:MM:SS` can only appear after units of years, months,
109    /// weeks or days.)
110    pub(crate) fn set_hms(
111        &mut self,
112        hours: u64,
113        minutes: u64,
114        seconds: u64,
115        fraction: Option<u32>,
116    ) -> Result<(), Error> {
117        if let Some(min) = self.min {
118            if min <= Unit::Hour {
119                return Err(Error::from(E::OutOfOrderHMS { found: min }));
120            }
121        }
122        self.set_unit_value(Unit::Hour, hours)?;
123        self.set_unit_value(Unit::Minute, minutes)?;
124        self.set_unit_value(Unit::Second, seconds)?;
125        if let Some(fraction) = fraction {
126            self.set_fraction(fraction)?;
127        }
128        Ok(())
129    }
130
131    /// Set the fractional value.
132    ///
133    /// This is always interpreted as a fraction of the minimal unit.
134    ///
135    /// Callers must ensure this is called after the last call to
136    /// `DurationUnits::set_unit_value`.
137    ///
138    /// # Panics
139    ///
140    /// When `fraction` is not in the range `0..=999_999_999`. Callers are
141    /// expected to uphold this invariant.
142    ///
143    /// # Errors
144    ///
145    /// This will return an error if the minimum unit is `Unit::Nanosecond`.
146    /// (Because fractional nanoseconds are not supported.) This will also
147    /// return an error if the minimum unit is bigger than `Unit::Hour`.
148    pub(crate) fn set_fraction(&mut self, fraction: u32) -> Result<(), Error> {
149        if !(fraction <= 999_999_999) {
    ::core::panicking::panic("assertion failed: fraction <= 999_999_999")
};assert!(fraction <= 999_999_999);
150        if let Some(min) = self.min {
151            if min > Unit::Hour || min == Unit::Nanosecond {
152                return Err(Error::from(E::NotAllowedFractionalUnit {
153                    found: min,
154                }));
155            }
156        }
157        self.fraction = Some(fraction);
158        self.any_non_zero_units = self.any_non_zero_units || fraction != 0;
159        Ok(())
160    }
161
162    /// Set the sign associated with the components.
163    ///
164    /// The sign applies to the entire duration. There is no support for
165    /// having some components signed and some unsigned.
166    ///
167    /// If no sign is set, then it is assumed to be zero. Note also that
168    /// even if a sign is explicitly set *and* all unit values are zero,
169    /// then the sign will be set to zero.
170    pub(crate) fn set_sign(&mut self, sign: Sign) {
171        self.sign = sign;
172    }
173
174    /// Convert these duration components to a `Span`.
175    ///
176    /// # Errors
177    ///
178    /// If any individual unit exceeds the limits of a `Span`, or if the units
179    /// combine to exceed what can be represented by a `Span`, then this
180    /// returns an error.
181    ///
182    /// This also returns an error if no units were set.
183    #[cfg_attr(feature = "perf-inline", inline(always))]
184    pub(crate) fn to_span(&self) -> Result<Span, Error> {
185        // When every unit value is less than this, *and* there is
186        // no fractional component, then we trigger a fast path that
187        // doesn't need to bother with error handling and careful
188        // handling of the sign.
189        //
190        // Why do we use the maximum year value? Because years are
191        // the "biggest" unit, it follows that there can't be any
192        // other unit whose limit is smaller than years as a
193        // dimenionless quantity. That is, if all parsed unit values
194        // are no bigger than the maximum year, then we know all
195        // parsed unit values are necessarily within their
196        // appropriate limits.
197        const LIMIT: u64 = b::SpanYears::MAX as u64;
198
199        // If we have a fraction or a particularly large unit,
200        // bail out to the general case.
201        if self.fraction.is_some()
202            || self.values.iter().any(|&value| value > LIMIT)
203            // If no unit was set, it's an error case.
204            || self.max.is_none()
205        {
206            return self.to_span_general();
207        }
208
209        let mut span = Span::new();
210
211        let years = self.values[Unit::Year.as_usize()] as i16;
212        let months = self.values[Unit::Month.as_usize()] as i32;
213        let weeks = self.values[Unit::Week.as_usize()] as i32;
214        let days = self.values[Unit::Day.as_usize()] as i32;
215        let hours = self.values[Unit::Hour.as_usize()] as i32;
216        let mins = self.values[Unit::Minute.as_usize()] as i64;
217        let secs = self.values[Unit::Second.as_usize()] as i64;
218        let millis = self.values[Unit::Millisecond.as_usize()] as i64;
219        let micros = self.values[Unit::Microsecond.as_usize()] as i64;
220        let nanos = self.values[Unit::Nanosecond.as_usize()] as i64;
221
222        span = span.years_unchecked(years);
223        span = span.months_unchecked(months);
224        span = span.weeks_unchecked(weeks);
225        span = span.days_unchecked(days);
226        span = span.hours_unchecked(hours);
227        span = span.minutes_unchecked(mins);
228        span = span.seconds_unchecked(secs);
229        span = span.milliseconds_unchecked(millis);
230        span = span.microseconds_unchecked(micros);
231        span = span.nanoseconds_unchecked(nanos);
232
233        // The unchecked setters above don't manipulate
234        // the sign, which defaults to zero. So we need to
235        // set it even when it's positive.
236        span = span.sign_unchecked(self.get_sign());
237
238        Ok(span)
239    }
240
241    /// The "general" implementation of `DurationUnits::to_span`.
242    ///
243    /// This handles all possible cases, including fractional units, with good
244    /// error handling. Basically, we take this path when we think an error
245    /// _could_ occur. But this function is more bloaty and does more work, so
246    /// the more it can be avoided, the better.
247    #[cold]
248    #[inline(never)]
249    fn to_span_general(&self) -> Result<Span, Error> {
250        #[cfg_attr(feature = "perf-inline", inline(always))]
251        fn set_time_unit(
252            unit: Unit,
253            value: i64,
254            span: Span,
255            set: impl FnOnce(Span) -> Result<Span, Error>,
256        ) -> Result<Span, Error> {
257            #[cold]
258            #[inline(never)]
259            fn fractional_fallback(
260                err: Error,
261                unit: Unit,
262                value: i64,
263                span: Span,
264            ) -> Result<Span, Error> {
265                // Fractional calendar units aren't supported. Neither are
266                // fractional nanoseconds. So there's nothing we can do in
267                // this case.
268                if unit > Unit::Hour || unit == Unit::Nanosecond {
269                    Err(err)
270                } else {
271                    // This is annoying, but because we can write out a larger
272                    // number of hours/minutes/seconds than what we actually
273                    // support, we need to be prepared to parse an unbalanced
274                    // span if our time units are too big here. In essence,
275                    // this lets a single time unit "overflow" into smaller
276                    // units if it exceeds the limits.
277                    fractional_time_to_span(unit, value, 0, span)
278                }
279            }
280
281            set(span)
282                .or_else(|err| fractional_fallback(err, unit, value, span))
283                .context(E::FailedValueSet { unit })
284        }
285
286        let (min, _) = self.get_min_max_units()?;
287        let mut span = Span::new();
288
289        if self.values[Unit::Year.as_usize()] != 0 {
290            let value = self.get_unit_value(Unit::Year)?;
291            span = span
292                .try_years(value)
293                .context(E::FailedValueSet { unit: Unit::Year })?;
294        }
295        if self.values[Unit::Month.as_usize()] != 0 {
296            let value = self.get_unit_value(Unit::Month)?;
297            span = span
298                .try_months(value)
299                .context(E::FailedValueSet { unit: Unit::Month })?;
300        }
301        if self.values[Unit::Week.as_usize()] != 0 {
302            let value = self.get_unit_value(Unit::Week)?;
303            span = span
304                .try_weeks(value)
305                .context(E::FailedValueSet { unit: Unit::Week })?;
306        }
307        if self.values[Unit::Day.as_usize()] != 0 {
308            let value = self.get_unit_value(Unit::Day)?;
309            span = span
310                .try_days(value)
311                .context(E::FailedValueSet { unit: Unit::Day })?;
312        }
313        if self.values[Unit::Hour.as_usize()] != 0 {
314            let value = self.get_unit_value(Unit::Hour)?;
315            span = set_time_unit(Unit::Hour, value, span, |span| {
316                span.try_hours(value)
317            })?;
318        }
319        // For the units below, a bigger unit may have exceeded its limit and
320        // overflowed into them. So we need to add to whatever is already on
321        // the span. Otherwise, we'd clobber the excess from the bigger unit.
322        if self.values[Unit::Minute.as_usize()] != 0 {
323            let value = self.get_unit_value(Unit::Minute)?;
324            span = set_time_unit(Unit::Minute, value, span, |span| {
325                let value =
326                    b::SpanMinutes::checked_add(value, span.get_minutes())?;
327                span.try_minutes(value)
328            })?;
329        }
330        if self.values[Unit::Second.as_usize()] != 0 {
331            let value = self.get_unit_value(Unit::Second)?;
332            span = set_time_unit(Unit::Second, value, span, |span| {
333                let value =
334                    b::SpanSeconds::checked_add(value, span.get_seconds())?;
335                span.try_seconds(value)
336            })?;
337        }
338        if self.values[Unit::Millisecond.as_usize()] != 0 {
339            let value = self.get_unit_value(Unit::Millisecond)?;
340            span = set_time_unit(Unit::Millisecond, value, span, |span| {
341                let value = b::SpanMilliseconds::checked_add(
342                    value,
343                    span.get_milliseconds(),
344                )?;
345                span.try_milliseconds(value)
346            })?;
347        }
348        if self.values[Unit::Microsecond.as_usize()] != 0 {
349            let value = self.get_unit_value(Unit::Microsecond)?;
350            span = set_time_unit(Unit::Microsecond, value, span, |span| {
351                let value = b::SpanMicroseconds::checked_add(
352                    value,
353                    span.get_microseconds(),
354                )?;
355                span.try_microseconds(value)
356            })?;
357        }
358        if self.values[Unit::Nanosecond.as_usize()] != 0 {
359            let value = self.get_unit_value(Unit::Nanosecond)?;
360            span = set_time_unit(Unit::Nanosecond, value, span, |span| {
361                let value = b::SpanNanoseconds::checked_add(
362                    value,
363                    span.get_nanoseconds(),
364                )?;
365                span.try_nanoseconds(value)
366            })?;
367        }
368
369        if let Some(fraction) = self.get_fraction()? {
370            // The whole number part of `min` was already set above.
371            span = fractional_time_to_span(min, 0, fraction, span)?;
372        }
373
374        Ok(span)
375    }
376
377    /// Convert these duration components to a `SignedDuration`.
378    ///
379    /// # Errors
380    ///
381    /// If the total number of nanoseconds represented by all units combined
382    /// exceeds what can bit in a 96-bit signed integer, then an error is
383    /// returned.
384    ///
385    /// An error is also returned if any calendar units (days or greater) were
386    /// set or if no units were set.
387    #[cfg_attr(feature = "perf-inline", inline(always))]
388    pub(crate) fn to_signed_duration(&self) -> Result<SignedDuration, Error> {
389        // When every unit value is less than this, *and* there is
390        // no fractional component, then we trigger a fast path that
391        // doesn't need to bother with error handling and careful
392        // handling of the sign.
393        //
394        // Why `999`? Well, I think it's nice to use one limit for all
395        // units to make the comparisons simpler (although we could
396        // use more targeted values to admit more cases, I didn't try
397        // that). But specifically, this means we can have `999ms 999us
398        // 999ns` as a maximal subsecond value without overflowing
399        // the nanosecond component of a `SignedDuration`. This lets
400        // us "just do math" without needing to check each result and
401        // handle errors.
402        const LIMIT: u64 = 999;
403
404        if self.fraction.is_some()
405            || self.values[..Unit::Day.as_usize()]
406                .iter()
407                .any(|&value| value > LIMIT)
408            || self.max.map_or(true, |max| max > Unit::Hour)
409        {
410            return self.to_signed_duration_general();
411        }
412
413        let hours = self.values[Unit::Hour.as_usize()] as i64;
414        let mins = self.values[Unit::Minute.as_usize()] as i64;
415        let secs = self.values[Unit::Second.as_usize()] as i64;
416        let millis = self.values[Unit::Millisecond.as_usize()] as i32;
417        let micros = self.values[Unit::Microsecond.as_usize()] as i32;
418        let nanos = self.values[Unit::Nanosecond.as_usize()] as i32;
419
420        let total_secs = (hours * 3600) + (mins * 60) + secs;
421        let total_nanos = (millis * 1_000_000) + (micros * 1_000) + nanos;
422        let mut sdur = SignedDuration::new_unchecked(total_secs, total_nanos);
423        if self.get_sign().is_negative() {
424            sdur = -sdur;
425        }
426
427        Ok(sdur)
428    }
429
430    /// The "general" implementation of `DurationUnits::to_signed_duration`.
431    ///
432    /// This handles all possible cases, including fractional units, with good
433    /// error handling. Basically, we take this path when we think an error
434    /// _could_ occur. But this function is more bloaty and does more work, so
435    /// the more it can be avoided, the better.
436    #[cold]
437    #[inline(never)]
438    fn to_signed_duration_general(&self) -> Result<SignedDuration, Error> {
439        let (min, max) = self.get_min_max_units()?;
440        if max > Unit::Hour {
441            return Err(Error::from(E::NotAllowedCalendarUnit { unit: max }));
442        }
443
444        let mut sdur = SignedDuration::ZERO;
445        if self.values[Unit::Hour.as_usize()] != 0 {
446            let value = self.get_unit_value(Unit::Hour)?;
447            sdur = SignedDuration::try_from_hours(value)
448                .and_then(|nanos| sdur.checked_add(nanos))
449                .ok_or(E::OverflowForUnit { unit: Unit::Hour })?;
450        }
451        if self.values[Unit::Minute.as_usize()] != 0 {
452            let value = self.get_unit_value(Unit::Minute)?;
453            sdur = SignedDuration::try_from_mins(value)
454                .and_then(|nanos| sdur.checked_add(nanos))
455                .ok_or(E::OverflowForUnit { unit: Unit::Minute })?;
456        }
457        if self.values[Unit::Second.as_usize()] != 0 {
458            let value = self.get_unit_value(Unit::Second)?;
459            sdur = SignedDuration::from_secs(value)
460                .checked_add(sdur)
461                .ok_or(E::OverflowForUnit { unit: Unit::Second })?;
462        }
463        if self.values[Unit::Millisecond.as_usize()] != 0 {
464            let value = self.get_unit_value(Unit::Millisecond)?;
465            sdur = SignedDuration::from_millis(value)
466                .checked_add(sdur)
467                .ok_or(E::OverflowForUnit { unit: Unit::Millisecond })?;
468        }
469        if self.values[Unit::Microsecond.as_usize()] != 0 {
470            let value = self.get_unit_value(Unit::Microsecond)?;
471            sdur = SignedDuration::from_micros(value)
472                .checked_add(sdur)
473                .ok_or(E::OverflowForUnit { unit: Unit::Microsecond })?;
474        }
475        if self.values[Unit::Nanosecond.as_usize()] != 0 {
476            let value = self.get_unit_value(Unit::Nanosecond)?;
477            sdur = SignedDuration::from_nanos(value)
478                .checked_add(sdur)
479                .ok_or(E::OverflowForUnit { unit: Unit::Nanosecond })?;
480        }
481
482        if let Some(fraction) = self.get_fraction()? {
483            sdur = sdur
484                .checked_add(fractional_duration(min, fraction)?)
485                .ok_or(E::OverflowForUnitFractional { unit: min })?;
486        }
487
488        Ok(sdur)
489    }
490
491    /// Convert these duration components to a `core::time::Duration`.
492    ///
493    /// # Errors
494    ///
495    /// If the total number of nanoseconds represented by all units combined
496    /// exceeds what can bit in a 96-bit signed integer, then an error is
497    /// returned.
498    ///
499    /// An error is also returned if any calendar units (days or greater) were
500    /// set or if no units were set.
501    #[cfg_attr(feature = "perf-inline", inline(always))]
502    pub(crate) fn to_unsigned_duration(
503        &self,
504    ) -> Result<core::time::Duration, Error> {
505        // When every unit value is less than this, *and* there is
506        // no fractional component, then we trigger a fast path that
507        // doesn't need to bother with error handling and careful
508        // handling of the sign.
509        //
510        // Why `999`? Well, I think it's nice to use one limit for all
511        // units to make the comparisons simpler (although we could
512        // use more targeted values to admit more cases, I didn't try
513        // that). But specifically, this means we can have `999ms 999us
514        // 999ns` as a maximal subsecond value without overflowing
515        // the nanosecond component of a `core::time::Duration`. This lets
516        // us "just do math" without needing to check each result and
517        // handle errors.
518        const LIMIT: u64 = 999;
519
520        if self.fraction.is_some()
521            || self.values[..Unit::Day.as_usize()]
522                .iter()
523                .any(|&value| value > LIMIT)
524            || self.max.map_or(true, |max| max > Unit::Hour)
525            || self.sign.is_negative()
526        {
527            return self.to_unsigned_duration_general();
528        }
529
530        let hours = self.values[Unit::Hour.as_usize()];
531        let mins = self.values[Unit::Minute.as_usize()];
532        let secs = self.values[Unit::Second.as_usize()];
533        let millis = self.values[Unit::Millisecond.as_usize()] as u32;
534        let micros = self.values[Unit::Microsecond.as_usize()] as u32;
535        let nanos = self.values[Unit::Nanosecond.as_usize()] as u32;
536
537        let total_secs = (hours * 3600) + (mins * 60) + secs;
538        let total_nanos = (millis * 1_000_000) + (micros * 1_000) + nanos;
539        let sdur = core::time::Duration::new(total_secs, total_nanos);
540
541        Ok(sdur)
542    }
543
544    /// The "general" implementation of `DurationUnits::to_unsigned_duration`.
545    ///
546    /// This handles all possible cases, including fractional units, with good
547    /// error handling. Basically, we take this path when we think an error
548    /// _could_ occur. But this function is more bloaty and does more work, so
549    /// the more it can be avoided, the better.
550    #[cold]
551    #[inline(never)]
552    fn to_unsigned_duration_general(
553        &self,
554    ) -> Result<core::time::Duration, Error> {
555        #[inline]
556        const fn try_from_hours(hours: u64) -> Option<core::time::Duration> {
557            // OK because (SECS_PER_MINUTE*MINS_PER_HOUR)!={-1,0}.
558            const MAX_HOUR: u64 = u64::MAX / (60 * 60);
559            if hours > MAX_HOUR {
560                return None;
561            }
562            Some(core::time::Duration::from_secs(hours * 60 * 60))
563        }
564
565        #[inline]
566        const fn try_from_mins(mins: u64) -> Option<core::time::Duration> {
567            // OK because SECS_PER_MINUTE!={-1,0}.
568            const MAX_MINUTE: u64 = u64::MAX / 60;
569            if mins > MAX_MINUTE {
570                return None;
571            }
572            Some(core::time::Duration::from_secs(mins * 60))
573        }
574
575        if self.sign.is_negative() {
576            return Err(Error::from(E::NotAllowedNegative));
577        }
578
579        let (min, max) = self.get_min_max_units()?;
580        if max > Unit::Hour {
581            return Err(Error::from(E::NotAllowedCalendarUnit { unit: max }));
582        }
583
584        let mut sdur = core::time::Duration::ZERO;
585        if self.values[Unit::Hour.as_usize()] != 0 {
586            let value = self.values[Unit::Hour.as_usize()];
587            sdur = try_from_hours(value)
588                .and_then(|nanos| sdur.checked_add(nanos))
589                .ok_or(E::OverflowForUnit { unit: Unit::Hour })?;
590        }
591        if self.values[Unit::Minute.as_usize()] != 0 {
592            let value = self.values[Unit::Minute.as_usize()];
593            sdur = try_from_mins(value)
594                .and_then(|nanos| sdur.checked_add(nanos))
595                .ok_or(E::OverflowForUnit { unit: Unit::Minute })?;
596        }
597        if self.values[Unit::Second.as_usize()] != 0 {
598            let value = self.values[Unit::Second.as_usize()];
599            sdur = core::time::Duration::from_secs(value)
600                .checked_add(sdur)
601                .ok_or(E::OverflowForUnit { unit: Unit::Second })?;
602        }
603        if self.values[Unit::Millisecond.as_usize()] != 0 {
604            let value = self.values[Unit::Millisecond.as_usize()];
605            sdur = core::time::Duration::from_millis(value)
606                .checked_add(sdur)
607                .ok_or(E::OverflowForUnit { unit: Unit::Millisecond })?;
608        }
609        if self.values[Unit::Microsecond.as_usize()] != 0 {
610            let value = self.values[Unit::Microsecond.as_usize()];
611            sdur = core::time::Duration::from_micros(value)
612                .checked_add(sdur)
613                .ok_or(E::OverflowForUnit { unit: Unit::Microsecond })?;
614        }
615        if self.values[Unit::Nanosecond.as_usize()] != 0 {
616            let value = self.values[Unit::Nanosecond.as_usize()];
617            sdur = core::time::Duration::from_nanos(value)
618                .checked_add(sdur)
619                .ok_or(E::OverflowForUnit { unit: Unit::Nanosecond })?;
620        }
621
622        if let Some(fraction) = self.get_fraction()? {
623            sdur = sdur
624                .checked_add(
625                    fractional_duration(min, fraction)?.unsigned_abs(),
626                )
627                .ok_or(E::OverflowForUnitFractional { unit: Unit::Hour })?;
628        }
629
630        Ok(sdur)
631    }
632
633    /// Returns the minimum unit set.
634    ///
635    /// This only returns `None` when no units have been set.
636    pub(crate) fn get_min(&self) -> Option<Unit> {
637        self.min
638    }
639
640    /// Returns the minimum and maximum units set.
641    ///
642    /// This returns an error if no units were set. (Since this means there
643    /// were no parsed duration components.)
644    fn get_min_max_units(&self) -> Result<(Unit, Unit), Error> {
645        let (Some(min), Some(max)) = (self.min, self.max) else {
646            return Err(Error::from(E::EmptyDuration));
647        };
648        Ok((min, max))
649    }
650
651    /// Returns the corresponding unit value using the set signed-ness.
652    #[cfg_attr(feature = "perf-inline", inline(always))]
653    fn get_unit_value(&self, unit: Unit) -> Result<i64, Error> {
654        const I64_MIN_ABS: u64 = i64::MIN.unsigned_abs();
655
656        #[cold]
657        #[inline(never)]
658        fn general(unit: Unit, value: u64, sign: Sign) -> Result<i64, Error> {
659            // As a weird special case, when we need to represent i64::MIN,
660            // we'll have a unit value of `|i64::MIN|` as a `u64`. We can't
661            // convert that to a positive `i64` first, since it will overflow.
662            if sign.is_negative() && value == I64_MIN_ABS {
663                return Ok(i64::MIN);
664            }
665            // Otherwise, if a conversion to `i64` fails, then that failure
666            // is correct.
667            let mut value = i64::try_from(value)
668                .map_err(|_| E::SignedOverflowForUnit { unit })?;
669            if sign.is_negative() {
670                value = value
671                    .checked_neg()
672                    .ok_or(E::SignedOverflowForUnit { unit })?;
673            }
674            Ok(value)
675        }
676
677        let sign = self.get_sign();
678        let value = self.values[unit.as_usize()];
679        if value >= I64_MIN_ABS {
680            return general(unit, value, sign);
681        }
682        let mut value = value as i64;
683        if sign.is_negative() {
684            value = -value;
685        }
686        Ok(value)
687    }
688
689    /// Returns the fraction using the set signed-ness.
690    ///
691    /// This returns `None` when no fraction has been set.
692    fn get_fraction(&self) -> Result<Option<i32>, Error> {
693        let Some(fraction) = self.fraction else {
694            return Ok(None);
695        };
696        // OK because `set_fraction` guarantees `0..=999_999_999`.
697        let mut fraction = fraction as i32;
698        if self.get_sign().is_negative() {
699            // OK because `set_fraction` guarantees `0..=999_999_999`.
700            fraction = -fraction;
701        }
702        Ok(Some(fraction))
703    }
704
705    /// Returns the sign that should be applied to each individual unit.
706    fn get_sign(&self) -> Sign {
707        if self.any_non_zero_units { self.sign } else { Sign::Zero }
708    }
709}
710
711/// Parses an optional fractional number from the start of `input`.
712///
713/// If `input` does not begin with a `.` (or a `,`), then this returns `None`
714/// and no input is consumed. Otherwise, up to 9 ASCII digits are parsed after
715/// the decimal separator.
716///
717/// While this is most typically used to parse the fractional component of
718/// second units, it is also used to parse the fractional component of hours or
719/// minutes in ISO 8601 duration parsing, and milliseconds and microseconds in
720/// the "friendly" duration format. The return type in that case is obviously a
721/// misnomer, but the range of possible values is still correct. (That is, the
722/// fractional component of an hour is still limited to 9 decimal places per
723/// the Temporal spec.)
724///
725/// The number returned is guaranteed to be in the range `0..=999_999_999`.
726#[cfg_attr(feature = "perf-inline", inline(always))]
727pub(crate) fn parse_temporal_fraction<'i>(
728    input: &'i [u8],
729) -> Result<Parsed<'i, Option<u32>>, Error> {
730    // TimeFraction :::
731    //   TemporalDecimalFraction
732    //
733    // TemporalDecimalFraction :::
734    //   TemporalDecimalSeparator DecimalDigit
735    //   TemporalDecimalSeparator DecimalDigit DecimalDigit
736    //   TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
737    //   TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
738    //                            DecimalDigit
739    //   TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
740    //                            DecimalDigit DecimalDigit
741    //   TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
742    //                            DecimalDigit DecimalDigit DecimalDigit
743    //   TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
744    //                            DecimalDigit DecimalDigit DecimalDigit
745    //                            DecimalDigit
746    //   TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
747    //                            DecimalDigit DecimalDigit DecimalDigit
748    //                            DecimalDigit DecimalDigit
749    //   TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
750    //                            DecimalDigit DecimalDigit DecimalDigit
751    //                            DecimalDigit DecimalDigit DecimalDigit
752    //
753    // TemporalDecimalSeparator ::: one of
754    //   . ,
755    //
756    // DecimalDigit :: one of
757    //   0 1 2 3 4 5 6 7 8 9
758
759    #[inline(never)]
760    fn imp<'i>(mut input: &'i [u8]) -> Result<Parsed<'i, Option<u32>>, Error> {
761        let mkdigits = parse::slicer(input);
762        while mkdigits(input).len() <= 8
763            && input.first().map_or(false, u8::is_ascii_digit)
764        {
765            input = &input[1..];
766        }
767        let digits = mkdigits(input);
768        if digits.is_empty() {
769            return Err(Error::from(E::MissingFractionalDigits));
770        }
771        // I believe this error can never happen, since we know we have no more
772        // than 9 ASCII digits. Any sequence of 9 ASCII digits can be parsed
773        // into an `i64`.
774        let nanoseconds =
775            parse::fraction(digits).context(E::InvalidFraction)?;
776        // OK because parsing is forcefully limited to 9 digits,
777        // which can never be greater than `999_999_99`,
778        // which is less than `u32::MAX`.
779        Ok(Parsed { value: Some(nanoseconds), input })
780    }
781
782    if input.is_empty() || (input[0] != b'.' && input[0] != b',') {
783        return Ok(Parsed { value: None, input });
784    }
785    imp(&input[1..])
786}
787
788/// This routine returns a span based on the given unit and value with
789/// fractional time applied to it.
790///
791/// For example, given a span like `P1dT1.5h`, the `unit` would be
792/// `Unit::Hour`, the `value` would be `1` and the `fraction` would be
793/// `500_000_000`. The span given would just be `1d`. The span returned would
794/// be `P1dT1h30m`.
795///
796/// The time is added to whatever is already in the span given. For example,
797/// if the span given above were `P1dT5m`, then the span returned would be
798/// `P1dT1h35m`.
799///
800/// Note that `fraction` can be a fractional hour, minute, second, millisecond
801/// or microsecond (even though its type suggests its only a fraction of a
802/// second). When milliseconds or microseconds, the given fraction has any
803/// sub-nanosecond precision truncated.
804///
805/// # Errors
806///
807/// This can error if the resulting units would be too large for the limits on
808/// a `span`. This also errors if `unit` is not `Hour`, `Minute`, `Second`,
809/// `Millisecond` or `Microsecond`.
810#[inline(never)]
811fn fractional_time_to_span(
812    unit: Unit,
813    value: i64,
814    fraction: i32,
815    mut span: Span,
816) -> Result<Span, Error> {
817    const MAX_HOURS: i64 = b::SpanHours::MAX as i64;
818    const MAX_MINS: i64 = b::SpanMinutes::MAX;
819    const MAX_SECS: i64 = b::SpanSeconds::MAX;
820    const MAX_MILLIS: i128 = b::SpanMilliseconds::MAX as i128;
821    const MAX_MICROS: i128 = b::SpanMicroseconds::MAX as i128;
822    const MIN_HOURS: i64 = b::SpanHours::MIN as i64;
823    const MIN_MINS: i64 = b::SpanMinutes::MIN;
824    const MIN_SECS: i64 = b::SpanSeconds::MIN;
825    const MIN_MILLIS: i128 = b::SpanMilliseconds::MIN as i128;
826    const MIN_MICROS: i128 = b::SpanMicroseconds::MIN as i128;
827
828    // We switch everything over to nanoseconds and then divy that up as
829    // appropriate. In general, we always create a balanced span, but there
830    // are some cases where we can't. For example, if one serializes a span
831    // with both the maximum number of seconds and the maximum number of
832    // milliseconds, then this just can't be balanced due to the limits on
833    // each of the units. When this kind of span is serialized to a string,
834    // it results in a second value that is actually bigger than the maximum
835    // allowed number of seconds in a span. So here, we have to reverse that
836    // operation and spread the seconds over smaller units. This in turn
837    // creates an unbalanced span. Annoying.
838    //
839    // The above is why we have `if unit_value > MAX { <do adjustments> }` in
840    // the balancing code below. Basically, if we overshoot our limit, we back
841    // out anything over the limit and carry it over to the lesser units. If
842    // our value is truly too big, then the final call to set nanoseconds will
843    // fail.
844    //
845    // Each unit is added to whatever is already in the span. We use saturating
846    // arithmetic for this so that overflow is never a concern. In practice,
847    // only seconds can saturate, and when they do, our value is truly too big.
848    let mut sdur = fractional_time_to_duration(unit, value, fraction)?;
849
850    if unit >= Unit::Hour && !sdur.is_zero() {
851        let (mut hours, rem) = sdur.as_hours_with_remainder();
852        sdur = rem;
853        hours = hours.saturating_add(i64::from(span.get_hours()));
854        if hours > MAX_HOURS {
855            sdur += SignedDuration::from_hours(hours - MAX_HOURS);
856            hours = MAX_HOURS;
857        } else if hours < MIN_HOURS {
858            sdur += SignedDuration::from_hours(hours - MIN_HOURS);
859            hours = MIN_HOURS;
860        }
861        // OK because we just checked that our units are in range.
862        span = span.hours(hours);
863    }
864    if unit >= Unit::Minute && !sdur.is_zero() {
865        let (mut mins, rem) = sdur.as_mins_with_remainder();
866        sdur = rem;
867        mins = mins.saturating_add(span.get_minutes());
868        if mins > MAX_MINS {
869            sdur += SignedDuration::from_mins(mins - MAX_MINS);
870            mins = MAX_MINS;
871        } else if mins < MIN_MINS {
872            sdur += SignedDuration::from_mins(mins - MIN_MINS);
873            mins = MIN_MINS;
874        }
875        // OK because we just checked that our units are in range.
876        span = span.minutes(mins);
877    }
878    if unit >= Unit::Second && !sdur.is_zero() {
879        let (mut secs, rem) = sdur.as_secs_with_remainder();
880        sdur = rem;
881        secs = secs.saturating_add(span.get_seconds());
882        if secs > MAX_SECS {
883            sdur += SignedDuration::from_secs(secs - MAX_SECS);
884            secs = MAX_SECS;
885        } else if secs < MIN_SECS {
886            sdur += SignedDuration::from_secs(secs - MIN_SECS);
887            secs = MIN_SECS;
888        }
889        // OK because we just checked that our units are in range.
890        span = span.seconds(secs);
891    }
892    if unit >= Unit::Millisecond && !sdur.is_zero() {
893        let (mut millis, rem) = sdur.as_millis_with_remainder();
894        sdur = rem;
895        millis = millis.saturating_add(i128::from(span.get_milliseconds()));
896        if millis > MAX_MILLIS {
897            sdur += SignedDuration::from_millis_i128(millis - MAX_MILLIS);
898            millis = MAX_MILLIS;
899        } else if millis < MIN_MILLIS {
900            sdur += SignedDuration::from_millis_i128(millis - MIN_MILLIS);
901            millis = MIN_MILLIS;
902        }
903        // OK because we just checked that our units are in range.
904        span = span.milliseconds(i64::try_from(millis).unwrap());
905    }
906    if unit >= Unit::Microsecond && !sdur.is_zero() {
907        let (mut micros, rem) = sdur.as_micros_with_remainder();
908        sdur = rem;
909        micros = micros.saturating_add(i128::from(span.get_microseconds()));
910        if micros > MAX_MICROS {
911            sdur += SignedDuration::from_micros_i128(micros - MAX_MICROS);
912            micros = MAX_MICROS;
913        } else if micros < MIN_MICROS {
914            sdur += SignedDuration::from_micros_i128(micros - MIN_MICROS);
915            micros = MIN_MICROS;
916        }
917        // OK because we just checked that our units are in range.
918        span = span.microseconds(i64::try_from(micros).unwrap());
919    }
920    if !sdur.is_zero() {
921        let nanos =
922            sdur.as_nanos().saturating_add(i128::from(span.get_nanoseconds()));
923        let nanos64 =
924            i64::try_from(nanos).map_err(|_| E::InvalidFractionNanos)?;
925        span =
926            span.try_nanoseconds(nanos64).context(E::InvalidFractionNanos)?;
927    }
928
929    Ok(span)
930}
931
932/// Like `fractional_time_to_span`, but just converts the fraction of the given
933/// unit to a signed duration.
934///
935/// Since a signed duration doesn't keep track of individual units, there is
936/// no loss of fidelity between it and ISO 8601 durations like there is for
937/// `Span`.
938///
939/// Note that `fraction` can be a fractional hour, minute, second, millisecond
940/// or microsecond (even though its type suggests it's only a fraction of a
941/// second). When milliseconds or microseconds, the given fraction has any
942/// sub-nanosecond precision truncated.
943///
944/// # Errors
945///
946/// This returns an error if `unit` is not `Hour`, `Minute`, `Second`,
947/// `Millisecond` or `Microsecond`.
948#[inline(never)]
949fn fractional_time_to_duration(
950    unit: Unit,
951    value: i64,
952    fraction: i32,
953) -> Result<SignedDuration, Error> {
954    let sdur = duration_unit_value(unit, value)?;
955    let fraction_dur = fractional_duration(unit, fraction)?;
956    Ok(sdur
957        .checked_add(fraction_dur)
958        .ok_or(E::OverflowForUnitFractional { unit })?)
959}
960
961/// Converts the fraction of the given unit to a signed duration.
962///
963/// Since a signed duration doesn't keep track of individual units, there is
964/// no loss of fidelity between it and ISO 8601 durations like there is for
965/// `Span`. Thus, we can do something far less complicated.
966///
967/// # Panics
968///
969/// When `fraction` isn't in the range `-999_999_999..=999_999_999`.
970///
971/// # Errors
972///
973/// This returns an error if `unit` is not `Hour`, `Minute`, `Second`,
974/// `Millisecond` or `Microsecond`.
975#[inline(never)]
976fn fractional_duration(
977    unit: Unit,
978    fraction: i32,
979) -> Result<SignedDuration, Error> {
980    let fraction = i64::from(fraction);
981    let nanos = match unit {
982        Unit::Hour => fraction * c::SECS_PER_HOUR,
983        Unit::Minute => fraction * c::SECS_PER_MIN,
984        Unit::Second => fraction,
985        Unit::Millisecond => fraction / c::NANOS_PER_MICRO,
986        Unit::Microsecond => fraction / c::NANOS_PER_MILLI,
987        unit => {
988            return Err(Error::from(E::NotAllowedFractionalUnit {
989                found: unit,
990            }));
991        }
992    };
993    Ok(SignedDuration::from_nanos(nanos))
994}
995
996/// Returns the given parsed value, interpreted as the given unit, as a
997/// `SignedDuration`.
998///
999/// If the given unit is not supported for signed durations (i.e., calendar
1000/// units), or if converting the given value to a `SignedDuration` for the
1001/// given units overflows, then an error is returned.
1002#[cfg_attr(feature = "perf-inline", inline(always))]
1003fn duration_unit_value(
1004    unit: Unit,
1005    value: i64,
1006) -> Result<SignedDuration, Error> {
1007    // Convert our parsed unit into a number of nanoseconds.
1008    //
1009    // Note also that overflow isn't possible here for units less than minutes,
1010    // since a `SignedDuration` supports all `i64` second values.
1011    let sdur = match unit {
1012        Unit::Hour => {
1013            let seconds = value
1014                .checked_mul(c::SECS_PER_HOUR)
1015                .ok_or(E::ConversionToSecondsFailed { unit: Unit::Hour })?;
1016            SignedDuration::from_secs(seconds)
1017        }
1018        Unit::Minute => {
1019            let seconds = value
1020                .checked_mul(c::SECS_PER_MIN)
1021                .ok_or(E::ConversionToSecondsFailed { unit: Unit::Minute })?;
1022            SignedDuration::from_secs(seconds)
1023        }
1024        Unit::Second => SignedDuration::from_secs(value),
1025        Unit::Millisecond => SignedDuration::from_millis(value),
1026        Unit::Microsecond => SignedDuration::from_micros(value),
1027        Unit::Nanosecond => SignedDuration::from_nanos(value),
1028        unsupported => {
1029            return Err(Error::from(E::NotAllowedCalendarUnit {
1030                unit: unsupported,
1031            }));
1032        }
1033    };
1034    Ok(sdur)
1035}