Debian Codegraph @

debian/rust-vendor/jiff/src/fmt/util.rs

raw
1 use jcore::{bounds::Sign, constants as c};
2
3 use crate::{
4 error::{fmt::util::Error as E, ErrorContext},
5 fmt::Parsed,
6 util::{b, parse},
7 Error, SignedDuration, Span, Unit,
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(Debug, Default)]
34 pub(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
54 impl 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 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 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 if self.values[Unit::Minute.as_usize()] != 0 {
320 let value = self.get_unit_value(Unit::Minute)?;
321 span = set_time_unit(Unit::Minute, value, span, |span| {
322 span.try_minutes(value)
323 })?;
324 }
325 if self.values[Unit::Second.as_usize()] != 0 {
326 let value = self.get_unit_value(Unit::Second)?;
327 span = set_time_unit(Unit::Second, value, span, |span| {
328 span.try_seconds(value)
329 })?;
330 }
331 if self.values[Unit::Millisecond.as_usize()] != 0 {
332 let value = self.get_unit_value(Unit::Millisecond)?;
333 span = set_time_unit(Unit::Millisecond, value, span, |span| {
334 span.try_milliseconds(value)
335 })?;
336 }
337 if self.values[Unit::Microsecond.as_usize()] != 0 {
338 let value = self.get_unit_value(Unit::Microsecond)?;
339 span = set_time_unit(Unit::Microsecond, value, span, |span| {
340 span.try_microseconds(value)
341 })?;
342 }
343 if self.values[Unit::Nanosecond.as_usize()] != 0 {
344 let value = self.get_unit_value(Unit::Nanosecond)?;
345 span = set_time_unit(Unit::Nanosecond, value, span, |span| {
346 span.try_nanoseconds(value)
347 })?;
348 }
349
350 if let Some(fraction) = self.get_fraction()? {
351 let value = self.get_unit_value(min)?;
352 span = fractional_time_to_span(min, value, fraction, span)?;
353 }
354
355 Ok(span)
356 }
357
358 /// Convert these duration components to a `SignedDuration`.
359 ///
360 /// # Errors
361 ///
362 /// If the total number of nanoseconds represented by all units combined
363 /// exceeds what can bit in a 96-bit signed integer, then an error is
364 /// returned.
365 ///
366 /// An error is also returned if any calendar units (days or greater) were
367 /// set or if no units were set.
368 #[cfg_attr(feature = "perf-inline", inline(always))]
369 pub(crate) fn to_signed_duration(&self) -> Result<SignedDuration, Error> {
370 // When every unit value is less than this, *and* there is
371 // no fractional component, then we trigger a fast path that
372 // doesn't need to bother with error handling and careful
373 // handling of the sign.
374 //
375 // Why `999`? Well, I think it's nice to use one limit for all
376 // units to make the comparisons simpler (although we could
377 // use more targeted values to admit more cases, I didn't try
378 // that). But specifically, this means we can have `999ms 999us
379 // 999ns` as a maximal subsecond value without overflowing
380 // the nanosecond component of a `SignedDuration`. This lets
381 // us "just do math" without needing to check each result and
382 // handle errors.
383 const LIMIT: u64 = 999;
384
385 if self.fraction.is_some()
386 || self.values[..Unit::Day.as_usize()]
387 .iter()
388 .any(|&value| value > LIMIT)
389 || self.max.map_or(true, |max| max > Unit::Hour)
390 {
391 return self.to_signed_duration_general();
392 }
393
394 let hours = self.values[Unit::Hour.as_usize()] as i64;
395 let mins = self.values[Unit::Minute.as_usize()] as i64;
396 let secs = self.values[Unit::Second.as_usize()] as i64;
397 let millis = self.values[Unit::Millisecond.as_usize()] as i32;
398 let micros = self.values[Unit::Microsecond.as_usize()] as i32;
399 let nanos = self.values[Unit::Nanosecond.as_usize()] as i32;
400
401 let total_secs = (hours * 3600) + (mins * 60) + secs;
402 let total_nanos = (millis * 1_000_000) + (micros * 1_000) + nanos;
403 let mut sdur = SignedDuration::new_unchecked(total_secs, total_nanos);
404 if self.get_sign().is_negative() {
405 sdur = -sdur;
406 }
407
408 Ok(sdur)
409 }
410
411 /// The "general" implementation of `DurationUnits::to_signed_duration`.
412 ///
413 /// This handles all possible cases, including fractional units, with good
414 /// error handling. Basically, we take this path when we think an error
415 /// _could_ occur. But this function is more bloaty and does more work, so
416 /// the more it can be avoided, the better.
417 #[cold]
418 #[inline(never)]
419 fn to_signed_duration_general(&self) -> Result<SignedDuration, Error> {
420 let (min, max) = self.get_min_max_units()?;
421 if max > Unit::Hour {
422 return Err(Error::from(E::NotAllowedCalendarUnit { unit: max }));
423 }
424
425 let mut sdur = SignedDuration::ZERO;
426 if self.values[Unit::Hour.as_usize()] != 0 {
427 let value = self.get_unit_value(Unit::Hour)?;
428 sdur = SignedDuration::try_from_hours(value)
429 .and_then(|nanos| sdur.checked_add(nanos))
430 .ok_or(E::OverflowForUnit { unit: Unit::Hour })?;
431 }
432 if self.values[Unit::Minute.as_usize()] != 0 {
433 let value = self.get_unit_value(Unit::Minute)?;
434 sdur = SignedDuration::try_from_mins(value)
435 .and_then(|nanos| sdur.checked_add(nanos))
436 .ok_or(E::OverflowForUnit { unit: Unit::Minute })?;
437 }
438 if self.values[Unit::Second.as_usize()] != 0 {
439 let value = self.get_unit_value(Unit::Second)?;
440 sdur = SignedDuration::from_secs(value)
441 .checked_add(sdur)
442 .ok_or(E::OverflowForUnit { unit: Unit::Second })?;
443 }
444 if self.values[Unit::Millisecond.as_usize()] != 0 {
445 let value = self.get_unit_value(Unit::Millisecond)?;
446 sdur = SignedDuration::from_millis(value)
447 .checked_add(sdur)
448 .ok_or(E::OverflowForUnit { unit: Unit::Millisecond })?;
449 }
450 if self.values[Unit::Microsecond.as_usize()] != 0 {
451 let value = self.get_unit_value(Unit::Microsecond)?;
452 sdur = SignedDuration::from_micros(value)
453 .checked_add(sdur)
454 .ok_or(E::OverflowForUnit { unit: Unit::Microsecond })?;
455 }
456 if self.values[Unit::Nanosecond.as_usize()] != 0 {
457 let value = self.get_unit_value(Unit::Nanosecond)?;
458 sdur = SignedDuration::from_nanos(value)
459 .checked_add(sdur)
460 .ok_or(E::OverflowForUnit { unit: Unit::Nanosecond })?;
461 }
462
463 if let Some(fraction) = self.get_fraction()? {
464 sdur = sdur
465 .checked_add(fractional_duration(min, fraction)?)
466 .ok_or(E::OverflowForUnitFractional { unit: min })?;
467 }
468
469 Ok(sdur)
470 }
471
472 /// Convert these duration components to a `core::time::Duration`.
473 ///
474 /// # Errors
475 ///
476 /// If the total number of nanoseconds represented by all units combined
477 /// exceeds what can bit in a 96-bit signed integer, then an error is
478 /// returned.
479 ///
480 /// An error is also returned if any calendar units (days or greater) were
481 /// set or if no units were set.
482 #[cfg_attr(feature = "perf-inline", inline(always))]
483 pub(crate) fn to_unsigned_duration(
484 &self,
485 ) -> Result<core::time::Duration, Error> {
486 // When every unit value is less than this, *and* there is
487 // no fractional component, then we trigger a fast path that
488 // doesn't need to bother with error handling and careful
489 // handling of the sign.
490 //
491 // Why `999`? Well, I think it's nice to use one limit for all
492 // units to make the comparisons simpler (although we could
493 // use more targeted values to admit more cases, I didn't try
494 // that). But specifically, this means we can have `999ms 999us
495 // 999ns` as a maximal subsecond value without overflowing
496 // the nanosecond component of a `core::time::Duration`. This lets
497 // us "just do math" without needing to check each result and
498 // handle errors.
499 const LIMIT: u64 = 999;
500
501 if self.fraction.is_some()
502 || self.values[..Unit::Day.as_usize()]
503 .iter()
504 .any(|&value| value > LIMIT)
505 || self.max.map_or(true, |max| max > Unit::Hour)
506 || self.sign.is_negative()
507 {
508 return self.to_unsigned_duration_general();
509 }
510
511 let hours = self.values[Unit::Hour.as_usize()];
512 let mins = self.values[Unit::Minute.as_usize()];
513 let secs = self.values[Unit::Second.as_usize()];
514 let millis = self.values[Unit::Millisecond.as_usize()] as u32;
515 let micros = self.values[Unit::Microsecond.as_usize()] as u32;
516 let nanos = self.values[Unit::Nanosecond.as_usize()] as u32;
517
518 let total_secs = (hours * 3600) + (mins * 60) + secs;
519 let total_nanos = (millis * 1_000_000) + (micros * 1_000) + nanos;
520 let sdur = core::time::Duration::new(total_secs, total_nanos);
521
522 Ok(sdur)
523 }
524
525 /// The "general" implementation of `DurationUnits::to_unsigned_duration`.
526 ///
527 /// This handles all possible cases, including fractional units, with good
528 /// error handling. Basically, we take this path when we think an error
529 /// _could_ occur. But this function is more bloaty and does more work, so
530 /// the more it can be avoided, the better.
531 #[cold]
532 #[inline(never)]
533 fn to_unsigned_duration_general(
534 &self,
535 ) -> Result<core::time::Duration, Error> {
536 #[inline]
537 const fn try_from_hours(hours: u64) -> Option<core::time::Duration> {
538 // OK because (SECS_PER_MINUTE*MINS_PER_HOUR)!={-1,0}.
539 const MAX_HOUR: u64 = u64::MAX / (60 * 60);
540 if hours > MAX_HOUR {
541 return None;
542 }
543 Some(core::time::Duration::from_secs(hours * 60 * 60))
544 }
545
546 #[inline]
547 const fn try_from_mins(mins: u64) -> Option<core::time::Duration> {
548 // OK because SECS_PER_MINUTE!={-1,0}.
549 const MAX_MINUTE: u64 = u64::MAX / 60;
550 if mins > MAX_MINUTE {
551 return None;
552 }
553 Some(core::time::Duration::from_secs(mins * 60))
554 }
555
556 if self.sign.is_negative() {
557 return Err(Error::from(E::NotAllowedNegative));
558 }
559
560 let (min, max) = self.get_min_max_units()?;
561 if max > Unit::Hour {
562 return Err(Error::from(E::NotAllowedCalendarUnit { unit: max }));
563 }
564
565 let mut sdur = core::time::Duration::ZERO;
566 if self.values[Unit::Hour.as_usize()] != 0 {
567 let value = self.values[Unit::Hour.as_usize()];
568 sdur = try_from_hours(value)
569 .and_then(|nanos| sdur.checked_add(nanos))
570 .ok_or(E::OverflowForUnit { unit: Unit::Hour })?;
571 }
572 if self.values[Unit::Minute.as_usize()] != 0 {
573 let value = self.values[Unit::Minute.as_usize()];
574 sdur = try_from_mins(value)
575 .and_then(|nanos| sdur.checked_add(nanos))
576 .ok_or(E::OverflowForUnit { unit: Unit::Minute })?;
577 }
578 if self.values[Unit::Second.as_usize()] != 0 {
579 let value = self.values[Unit::Second.as_usize()];
580 sdur = core::time::Duration::from_secs(value)
581 .checked_add(sdur)
582 .ok_or(E::OverflowForUnit { unit: Unit::Second })?;
583 }
584 if self.values[Unit::Millisecond.as_usize()] != 0 {
585 let value = self.values[Unit::Millisecond.as_usize()];
586 sdur = core::time::Duration::from_millis(value)
587 .checked_add(sdur)
588 .ok_or(E::OverflowForUnit { unit: Unit::Millisecond })?;
589 }
590 if self.values[Unit::Microsecond.as_usize()] != 0 {
591 let value = self.values[Unit::Microsecond.as_usize()];
592 sdur = core::time::Duration::from_micros(value)
593 .checked_add(sdur)
594 .ok_or(E::OverflowForUnit { unit: Unit::Microsecond })?;
595 }
596 if self.values[Unit::Nanosecond.as_usize()] != 0 {
597 let value = self.values[Unit::Nanosecond.as_usize()];
598 sdur = core::time::Duration::from_nanos(value)
599 .checked_add(sdur)
600 .ok_or(E::OverflowForUnit { unit: Unit::Nanosecond })?;
601 }
602
603 if let Some(fraction) = self.get_fraction()? {
604 sdur = sdur
605 .checked_add(
606 fractional_duration(min, fraction)?.unsigned_abs(),
607 )
608 .ok_or(E::OverflowForUnitFractional { unit: Unit::Hour })?;
609 }
610
611 Ok(sdur)
612 }
613
614 /// Returns the minimum unit set.
615 ///
616 /// This only returns `None` when no units have been set.
617 pub(crate) fn get_min(&self) -> Option<Unit> {
618 self.min
619 }
620
621 /// Returns the minimum and maximum units set.
622 ///
623 /// This returns an error if no units were set. (Since this means there
624 /// were no parsed duration components.)
625 fn get_min_max_units(&self) -> Result<(Unit, Unit), Error> {
626 let (Some(min), Some(max)) = (self.min, self.max) else {
627 return Err(Error::from(E::EmptyDuration));
628 };
629 Ok((min, max))
630 }
631
632 /// Returns the corresponding unit value using the set signed-ness.
633 #[cfg_attr(feature = "perf-inline", inline(always))]
634 fn get_unit_value(&self, unit: Unit) -> Result<i64, Error> {
635 const I64_MIN_ABS: u64 = i64::MIN.unsigned_abs();
636
637 #[cold]
638 #[inline(never)]
639 fn general(unit: Unit, value: u64, sign: Sign) -> Result<i64, Error> {
640 // As a weird special case, when we need to represent i64::MIN,
641 // we'll have a unit value of `|i64::MIN|` as a `u64`. We can't
642 // convert that to a positive `i64` first, since it will overflow.
643 if sign.is_negative() && value == I64_MIN_ABS {
644 return Ok(i64::MIN);
645 }
646 // Otherwise, if a conversion to `i64` fails, then that failure
647 // is correct.
648 let mut value = i64::try_from(value)
649 .map_err(|_| E::SignedOverflowForUnit { unit })?;
650 if sign.is_negative() {
651 value = value
652 .checked_neg()
653 .ok_or(E::SignedOverflowForUnit { unit })?;
654 }
655 Ok(value)
656 }
657
658 let sign = self.get_sign();
659 let value = self.values[unit.as_usize()];
660 if value >= I64_MIN_ABS {
661 return general(unit, value, sign);
662 }
663 let mut value = value as i64;
664 if sign.is_negative() {
665 value = -value;
666 }
667 Ok(value)
668 }
669
670 /// Returns the fraction using the set signed-ness.
671 ///
672 /// This returns `None` when no fraction has been set.
673 fn get_fraction(&self) -> Result<Option<i32>, Error> {
674 let Some(fraction) = self.fraction else {
675 return Ok(None);
676 };
677 // OK because `set_fraction` guarantees `0..=999_999_999`.
678 let mut fraction = fraction as i32;
679 if self.get_sign().is_negative() {
680 // OK because `set_fraction` guarantees `0..=999_999_999`.
681 fraction = -fraction;
682 }
683 Ok(Some(fraction))
684 }
685
686 /// Returns the sign that should be applied to each individual unit.
687 fn get_sign(&self) -> Sign {
688 if self.any_non_zero_units {
689 self.sign
690 } else {
691 Sign::Zero
692 }
693 }
694 }
695
696 /// Parses an optional fractional number from the start of `input`.
697 ///
698 /// If `input` does not begin with a `.` (or a `,`), then this returns `None`
699 /// and no input is consumed. Otherwise, up to 9 ASCII digits are parsed after
700 /// the decimal separator.
701 ///
702 /// While this is most typically used to parse the fractional component of
703 /// second units, it is also used to parse the fractional component of hours or
704 /// minutes in ISO 8601 duration parsing, and milliseconds and microseconds in
705 /// the "friendly" duration format. The return type in that case is obviously a
706 /// misnomer, but the range of possible values is still correct. (That is, the
707 /// fractional component of an hour is still limited to 9 decimal places per
708 /// the Temporal spec.)
709 ///
710 /// The number returned is guaranteed to be in the range `0..=999_999_999`.
711 #[cfg_attr(feature = "perf-inline", inline(always))]
712 pub(crate) fn parse_temporal_fraction<'i>(
713 input: &'i [u8],
714 ) -> Result<Parsed<'i, Option<u32>>, Error> {
715 // TimeFraction :::
716 // TemporalDecimalFraction
717 //
718 // TemporalDecimalFraction :::
719 // TemporalDecimalSeparator DecimalDigit
720 // TemporalDecimalSeparator DecimalDigit DecimalDigit
721 // TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
722 // TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
723 // DecimalDigit
724 // TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
725 // DecimalDigit DecimalDigit
726 // TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
727 // DecimalDigit DecimalDigit DecimalDigit
728 // TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
729 // DecimalDigit DecimalDigit DecimalDigit
730 // DecimalDigit
731 // TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
732 // DecimalDigit DecimalDigit DecimalDigit
733 // DecimalDigit DecimalDigit
734 // TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
735 // DecimalDigit DecimalDigit DecimalDigit
736 // DecimalDigit DecimalDigit DecimalDigit
737 //
738 // TemporalDecimalSeparator ::: one of
739 // . ,
740 //
741 // DecimalDigit :: one of
742 // 0 1 2 3 4 5 6 7 8 9
743
744 #[inline(never)]
745 fn imp<'i>(mut input: &'i [u8]) -> Result<Parsed<'i, Option<u32>>, Error> {
746 let mkdigits = parse::slicer(input);
747 while mkdigits(input).len() <= 8
748 && input.first().map_or(false, u8::is_ascii_digit)
749 {
750 input = &input[1..];
751 }
752 let digits = mkdigits(input);
753 if digits.is_empty() {
754 return Err(Error::from(E::MissingFractionalDigits));
755 }
756 // I believe this error can never happen, since we know we have no more
757 // than 9 ASCII digits. Any sequence of 9 ASCII digits can be parsed
758 // into an `i64`.
759 let nanoseconds =
760 parse::fraction(digits).context(E::InvalidFraction)?;
761 // OK because parsing is forcefully limited to 9 digits,
762 // which can never be greater than `999_999_99`,
763 // which is less than `u32::MAX`.
764 Ok(Parsed { value: Some(nanoseconds), input })
765 }
766
767 if input.is_empty() || (input[0] != b'.' && input[0] != b',') {
768 return Ok(Parsed { value: None, input });
769 }
770 imp(&input[1..])
771 }
772
773 /// This routine returns a span based on the given unit and value with
774 /// fractional time applied to it.
775 ///
776 /// For example, given a span like `P1dT1.5h`, the `unit` would be
777 /// `Unit::Hour`, the `value` would be `1` and the `fraction` would be
778 /// `500_000_000`. The span given would just be `1d`. The span returned would
779 /// be `P1dT1h30m`.
780 ///
781 /// Note that `fraction` can be a fractional hour, minute, second, millisecond
782 /// or microsecond (even though its type suggests its only a fraction of a
783 /// second). When milliseconds or microseconds, the given fraction has any
784 /// sub-nanosecond precision truncated.
785 ///
786 /// # Errors
787 ///
788 /// This can error if the resulting units would be too large for the limits on
789 /// a `span`. This also errors if `unit` is not `Hour`, `Minute`, `Second`,
790 /// `Millisecond` or `Microsecond`.
791 #[inline(never)]
792 fn fractional_time_to_span(
793 unit: Unit,
794 value: i64,
795 fraction: i32,
796 mut span: Span,
797 ) -> Result<Span, Error> {
798 const MAX_HOURS: i64 = b::SpanHours::MAX as i64;
799 const MAX_MINS: i64 = b::SpanMinutes::MAX;
800 const MAX_SECS: i64 = b::SpanSeconds::MAX;
801 const MAX_MILLIS: i128 = b::SpanMilliseconds::MAX as i128;
802 const MAX_MICROS: i128 = b::SpanMicroseconds::MAX as i128;
803 const MIN_HOURS: i64 = b::SpanHours::MIN as i64;
804 const MIN_MINS: i64 = b::SpanMinutes::MIN;
805 const MIN_SECS: i64 = b::SpanSeconds::MIN;
806 const MIN_MILLIS: i128 = b::SpanMilliseconds::MIN as i128;
807 const MIN_MICROS: i128 = b::SpanMicroseconds::MIN as i128;
808
809 // We switch everything over to nanoseconds and then divy that up as
810 // appropriate. In general, we always create a balanced span, but there
811 // are some cases where we can't. For example, if one serializes a span
812 // with both the maximum number of seconds and the maximum number of
813 // milliseconds, then this just can't be balanced due to the limits on
814 // each of the units. When this kind of span is serialized to a string,
815 // it results in a second value that is actually bigger than the maximum
816 // allowed number of seconds in a span. So here, we have to reverse that
817 // operation and spread the seconds over smaller units. This in turn
818 // creates an unbalanced span. Annoying.
819 //
820 // The above is why we have `if unit_value > MAX { <do adjustments> }` in
821 // the balancing code below. Basically, if we overshoot our limit, we back
822 // out anything over the limit and carry it over to the lesser units. If
823 // our value is truly too big, then the final call to set nanoseconds will
824 // fail.
825 let mut sdur = fractional_time_to_duration(unit, value, fraction)?;
826
827 if unit >= Unit::Hour && !sdur.is_zero() {
828 let (mut hours, rem) = sdur.as_hours_with_remainder();
829 sdur = rem;
830 if hours > MAX_HOURS {
831 sdur += SignedDuration::from_hours(hours - MAX_HOURS);
832 hours = MAX_HOURS;
833 } else if hours < MIN_HOURS {
834 sdur += SignedDuration::from_hours(hours - MIN_HOURS);
835 hours = MIN_HOURS;
836 }
837 // OK because we just checked that our units are in range.
838 span = span.hours(hours);
839 }
840 if unit >= Unit::Minute && !sdur.is_zero() {
841 let (mut mins, rem) = sdur.as_mins_with_remainder();
842 sdur = rem;
843 if mins > MAX_MINS {
844 sdur += SignedDuration::from_mins(mins - MAX_MINS);
845 mins = MAX_MINS;
846 } else if mins < MIN_MINS {
847 sdur += SignedDuration::from_mins(mins - MIN_MINS);
848 mins = MIN_MINS;
849 }
850 // OK because we just checked that our units are in range.
851 span = span.minutes(mins);
852 }
853 if unit >= Unit::Second && !sdur.is_zero() {
854 let (mut secs, rem) = sdur.as_secs_with_remainder();
855 sdur = rem;
856 if secs > MAX_SECS {
857 sdur += SignedDuration::from_secs(secs - MAX_SECS);
858 secs = MAX_SECS;
859 } else if secs < MIN_SECS {
860 sdur += SignedDuration::from_secs(secs - MIN_SECS);
861 secs = MIN_SECS;
862 }
863 // OK because we just checked that our units are in range.
864 span = span.seconds(secs);
865 }
866 if unit >= Unit::Millisecond && !sdur.is_zero() {
867 let (mut millis, rem) = sdur.as_millis_with_remainder();
868 sdur = rem;
869 if millis > MAX_MILLIS {
870 sdur += SignedDuration::from_millis_i128(millis - MAX_MILLIS);
871 millis = MAX_MILLIS;
872 } else if millis < MIN_MILLIS {
873 sdur += SignedDuration::from_millis_i128(millis - MIN_MILLIS);
874 millis = MIN_MILLIS;
875 }
876 // OK because we just checked that our units are in range.
877 span = span.milliseconds(i64::try_from(millis).unwrap());
878 }
879 if unit >= Unit::Microsecond && !sdur.is_zero() {
880 let (mut micros, rem) = sdur.as_micros_with_remainder();
881 sdur = rem;
882 if micros > MAX_MICROS {
883 sdur += SignedDuration::from_micros_i128(micros - MAX_MICROS);
884 micros = MAX_MICROS;
885 } else if micros < MIN_MICROS {
886 sdur += SignedDuration::from_micros_i128(micros - MIN_MICROS);
887 micros = MIN_MICROS;
888 }
889 // OK because we just checked that our units are in range.
890 span = span.microseconds(i64::try_from(micros).unwrap());
891 }
892 if !sdur.is_zero() {
893 let nanos = sdur.as_nanos();
894 let nanos64 =
895 i64::try_from(nanos).map_err(|_| E::InvalidFractionNanos)?;
896 span =
897 span.try_nanoseconds(nanos64).context(E::InvalidFractionNanos)?;
898 }
899
900 Ok(span)
901 }
902
903 /// Like `fractional_time_to_span`, but just converts the fraction of the given
904 /// unit to a signed duration.
905 ///
906 /// Since a signed duration doesn't keep track of individual units, there is
907 /// no loss of fidelity between it and ISO 8601 durations like there is for
908 /// `Span`.
909 ///
910 /// Note that `fraction` can be a fractional hour, minute, second, millisecond
911 /// or microsecond (even though its type suggests it's only a fraction of a
912 /// second). When milliseconds or microseconds, the given fraction has any
913 /// sub-nanosecond precision truncated.
914 ///
915 /// # Errors
916 ///
917 /// This returns an error if `unit` is not `Hour`, `Minute`, `Second`,
918 /// `Millisecond` or `Microsecond`.
919 #[inline(never)]
920 fn fractional_time_to_duration(
921 unit: Unit,
922 value: i64,
923 fraction: i32,
924 ) -> Result<SignedDuration, Error> {
925 let sdur = duration_unit_value(unit, value)?;
926 let fraction_dur = fractional_duration(unit, fraction)?;
927 Ok(sdur
928 .checked_add(fraction_dur)
929 .ok_or(E::OverflowForUnitFractional { unit })?)
930 }
931
932 /// Converts the fraction of the given unit to a signed duration.
933 ///
934 /// Since a signed duration doesn't keep track of individual units, there is
935 /// no loss of fidelity between it and ISO 8601 durations like there is for
936 /// `Span`. Thus, we can do something far less complicated.
937 ///
938 /// # Panics
939 ///
940 /// When `fraction` isn't in the range `-999_999_999..=999_999_999`.
941 ///
942 /// # Errors
943 ///
944 /// This returns an error if `unit` is not `Hour`, `Minute`, `Second`,
945 /// `Millisecond` or `Microsecond`.
946 #[inline(never)]
947 fn fractional_duration(
948 unit: Unit,
949 fraction: i32,
950 ) -> Result<SignedDuration, Error> {
951 let fraction = i64::from(fraction);
952 let nanos = match unit {
953 Unit::Hour => fraction * c::SECS_PER_HOUR,
954 Unit::Minute => fraction * c::SECS_PER_MIN,
955 Unit::Second => fraction,
956 Unit::Millisecond => fraction / c::NANOS_PER_MICRO,
957 Unit::Microsecond => fraction / c::NANOS_PER_MILLI,
958 unit => {
959 return Err(Error::from(E::NotAllowedFractionalUnit {
960 found: unit,
961 }));
962 }
963 };
964 Ok(SignedDuration::from_nanos(nanos))
965 }
966
967 /// Returns the given parsed value, interpreted as the given unit, as a
968 /// `SignedDuration`.
969 ///
970 /// If the given unit is not supported for signed durations (i.e., calendar
971 /// units), or if converting the given value to a `SignedDuration` for the
972 /// given units overflows, then an error is returned.
973 #[cfg_attr(feature = "perf-inline", inline(always))]
974 fn duration_unit_value(
975 unit: Unit,
976 value: i64,
977 ) -> Result<SignedDuration, Error> {
978 // Convert our parsed unit into a number of nanoseconds.
979 //
980 // Note also that overflow isn't possible here for units less than minutes,
981 // since a `SignedDuration` supports all `i64` second values.
982 let sdur = match unit {
983 Unit::Hour => {
984 let seconds = value
985 .checked_mul(c::SECS_PER_HOUR)
986 .ok_or(E::ConversionToSecondsFailed { unit: Unit::Hour })?;
987 SignedDuration::from_secs(seconds)
988 }
989 Unit::Minute => {
990 let seconds = value
991 .checked_mul(c::SECS_PER_MIN)
992 .ok_or(E::ConversionToSecondsFailed { unit: Unit::Minute })?;
993 SignedDuration::from_secs(seconds)
994 }
995 Unit::Second => SignedDuration::from_secs(value),
996 Unit::Millisecond => SignedDuration::from_millis(value),
997 Unit::Microsecond => SignedDuration::from_micros(value),
998 Unit::Nanosecond => SignedDuration::from_nanos(value),
999 unsupported => {
1000 return Err(Error::from(E::NotAllowedCalendarUnit {
1001 unit: unsupported,
1002 }))
1003 }
1004 };
1005 Ok(sdur)
1006 }