1use jcore::bounds::Sign;
23use crate::{
4Error, SignedDuration, Span, Unit,
5 error::{ErrorContext, fmt::friendly::Erroras E},
6 fmt::{
7Parsed,
8friendly::parser_label,
9 util::{DurationUnits, parse_temporal_fraction},
10 },
11util::parse,
12};
1314/// A parser for Jiff's "friendly" duration format.
15///
16/// See the [module documentation](super) for more details on the precise
17/// format supported by this parser.
18///
19/// Unlike [`SpanPrinter`](super::SpanPrinter), this parser doesn't have any
20/// configuration knobs. While it may grow some in the future, the approach
21/// taken here is for the parser to support the entire grammar. That is, the
22/// parser can parse anything emitted by `SpanPrinter`. (And indeed, the
23/// parser can even handle things that the printer can't emit due to lack of
24/// configurability. For example, `1hour1m` is a valid friendly duration,
25/// but `SpanPrinter` cannot emit it due to a mixing of verbose and compact
26/// designator labels.)
27///
28/// # Advice
29///
30/// Since this parser has no configuration, there are generally only two reasons
31/// why you might want to use this type specifically:
32///
33/// 1. You need to parse from `&[u8]`.
34/// 2. You need to parse _only_ the "friendly" format.
35///
36/// Otherwise, you can use the `FromStr` implementations on both `Span` and
37/// `SignedDuration`, which automatically support the friendly format in
38/// addition to the ISO 8601 format simultaneously:
39///
40/// ```
41/// use jiff::{SignedDuration, Span, ToSpan};
42///
43/// let span: Span = "5 years, 2 months".parse()?;
44/// assert_eq!(span, 5.years().months(2).fieldwise());
45///
46/// let sdur: SignedDuration = "5 hours, 2 minutes".parse()?;
47/// assert_eq!(sdur, SignedDuration::new(5 * 60 * 60 + 2 * 60, 0));
48///
49/// # Ok::<(), Box<dyn std::error::Error>>(())
50/// ```
51///
52/// # Example
53///
54/// This example shows how to parse a `Span` directly from `&str`:
55///
56/// ```
57/// use jiff::{fmt::friendly::SpanParser, ToSpan};
58///
59/// static PARSER: SpanParser = SpanParser::new();
60///
61/// let string = "1 year, 3 months, 15:00:01.3";
62/// let span = PARSER.parse_span(string)?;
63/// assert_eq!(
64/// span,
65/// 1.year().months(3).hours(15).seconds(1).milliseconds(300).fieldwise(),
66/// );
67///
68/// // Negative durations are supported too!
69/// let string = "1 year, 3 months, 15:00:01.3 ago";
70/// let span = PARSER.parse_span(string)?;
71/// assert_eq!(
72/// span,
73/// -1.year().months(3).hours(15).seconds(1).milliseconds(300).fieldwise(),
74/// );
75///
76/// # Ok::<(), Box<dyn std::error::Error>>(())
77/// ```
78#[derive(#[automatically_derived]impl ::core::clone::Clone for SpanParser {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
SpanParser { _private: ::core::clone::Clone::clone(&self._private) }
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for SpanParser {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"SpanParser _private", &&self._private)
}
}Debug, #[automatically_derived]impl ::core::default::Default for SpanParser {
#[inline]
fn default() -> Self {
SpanParser { _private: ::core::default::Default::default() }
}
}Default)]
79pub struct SpanParser {
80 _private: (),
81}
8283impl SpanParser {
84/// Creates a new parser for the "friendly" duration format.
85 ///
86 /// The parser returned uses the default configuration. (Although, at time
87 /// of writing, there are no available configuration options for this
88 /// parser.) This is identical to `SpanParser::default`, but it can be used
89 /// in a `const` context.
90 ///
91 /// # Example
92 ///
93 /// This example shows how to parse a `Span` directly from `&[u8]`:
94 ///
95 /// ```
96 /// use jiff::{fmt::friendly::SpanParser, ToSpan};
97 ///
98 /// static PARSER: SpanParser = SpanParser::new();
99 ///
100 /// let bytes = b"1 year 3 months 15 hours 1300ms";
101 /// let span = PARSER.parse_span(bytes)?;
102 /// assert_eq!(
103 /// span,
104 /// 1.year().months(3).hours(15).milliseconds(1300).fieldwise(),
105 /// );
106 ///
107 /// # Ok::<(), Box<dyn std::error::Error>>(())
108 /// ```
109#[inline]
110pub const fn new() -> SpanParser {
111SpanParser { _private: () }
112 }
113114/// Run the parser on the given string (which may be plain bytes) and,
115 /// if successful, return the parsed `Span`.
116 ///
117 /// See the [module documentation](super) for more details on the specific
118 /// grammar supported by this parser.
119 ///
120 /// # Example
121 ///
122 /// This shows a number of different duration formats that can be parsed
123 /// into a `Span`:
124 ///
125 /// ```
126 /// use jiff::{fmt::friendly::SpanParser, ToSpan};
127 ///
128 /// let spans = [
129 /// ("40d", 40.days()),
130 /// ("40 days", 40.days()),
131 /// ("1y1d", 1.year().days(1)),
132 /// ("1yr 1d", 1.year().days(1)),
133 /// ("3d4h59m", 3.days().hours(4).minutes(59)),
134 /// ("3 days, 4 hours, 59 minutes", 3.days().hours(4).minutes(59)),
135 /// ("3d 4h 59m", 3.days().hours(4).minutes(59)),
136 /// ("2h30m", 2.hours().minutes(30)),
137 /// ("2h 30m", 2.hours().minutes(30)),
138 /// ("1mo", 1.month()),
139 /// ("1w", 1.week()),
140 /// ("1 week", 1.week()),
141 /// ("1w4d", 1.week().days(4)),
142 /// ("1 wk 4 days", 1.week().days(4)),
143 /// ("1m", 1.minute()),
144 /// ("0.0021s", 2.milliseconds().microseconds(100)),
145 /// ("0s", 0.seconds()),
146 /// ("0d", 0.seconds()),
147 /// ("0 days", 0.seconds()),
148 /// (
149 /// "1y1mo1d1h1m1.1s",
150 /// 1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
151 /// ),
152 /// (
153 /// "1yr 1mo 1day 1hr 1min 1.1sec",
154 /// 1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
155 /// ),
156 /// (
157 /// "1 year, 1 month, 1 day, 1 hour, 1 minute 1.1 seconds",
158 /// 1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
159 /// ),
160 /// (
161 /// "1 year, 1 month, 1 day, 01:01:01.1",
162 /// 1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
163 /// ),
164 /// (
165 /// "1 yr, 1 month, 1 d, 1 h, 1 min 1.1 second",
166 /// 1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
167 /// ),
168 /// ];
169 ///
170 /// static PARSER: SpanParser = SpanParser::new();
171 /// for (string, span) in spans {
172 /// let parsed = PARSER.parse_span(string)?;
173 /// assert_eq!(
174 /// span.fieldwise(),
175 /// parsed.fieldwise(),
176 /// "result of parsing {string:?}",
177 /// );
178 /// }
179 ///
180 /// # Ok::<(), Box<dyn std::error::Error>>(())
181 /// ```
182#[inline]
183pub fn parse_span<I: AsRef<[u8]>>(&self, input: I) -> Result<Span, Error> {
184#[inline(never)]
185fn imp(span_parser: &SpanParser, input: &[u8]) -> Result<Span, Error> {
186let mut builder = DurationUnits::default();
187let parsed = span_parser.parse(input, &mut builder)?;
188let parsed = parsed.and_then(|_| builder.to_span())?;
189parsed.into_full()
190 }
191192let input = input.as_ref();
193imp(self, input).context(E::Failed)
194 }
195196/// Run the parser on the given string (which may be plain bytes) and,
197 /// if successful, return the parsed `SignedDuration`.
198 ///
199 /// See the [module documentation](super) for more details on the specific
200 /// grammar supported by this parser.
201 ///
202 /// # Example
203 ///
204 /// This shows a number of different duration formats that can be parsed
205 /// into a `SignedDuration`:
206 ///
207 /// ```
208 /// use jiff::{fmt::friendly::SpanParser, SignedDuration};
209 ///
210 /// let durations = [
211 /// ("2h30m", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
212 /// ("2 hrs 30 mins", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
213 /// ("2 hours 30 minutes", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
214 /// ("2 hrs 30 minutes", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
215 /// ("2.5h", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
216 /// ("1m", SignedDuration::from_mins(1)),
217 /// ("1.5m", SignedDuration::from_secs(90)),
218 /// ("0.0021s", SignedDuration::new(0, 2_100_000)),
219 /// ("0s", SignedDuration::ZERO),
220 /// ("0.000000001s", SignedDuration::from_nanos(1)),
221 /// ];
222 ///
223 /// static PARSER: SpanParser = SpanParser::new();
224 /// for (string, duration) in durations {
225 /// let parsed = PARSER.parse_duration(string)?;
226 /// assert_eq!(duration, parsed, "result of parsing {string:?}");
227 /// }
228 ///
229 /// # Ok::<(), Box<dyn std::error::Error>>(())
230 /// ```
231#[inline]
232pub fn parse_duration<I: AsRef<[u8]>>(
233&self,
234 input: I,
235 ) -> Result<SignedDuration, Error> {
236#[inline(never)]
237fn imp(
238 span_parser: &SpanParser,
239 input: &[u8],
240 ) -> Result<SignedDuration, Error> {
241let mut builder = DurationUnits::default();
242let parsed = span_parser.parse(input, &mut builder)?;
243let parsed = parsed.and_then(|_| builder.to_signed_duration())?;
244parsed.into_full()
245 }
246247let input = input.as_ref();
248imp(self, input).context(E::Failed)
249 }
250251/// Run the parser on the given string (which may be plain bytes) and,
252 /// if successful, return the parsed `std::time::Duration`.
253 ///
254 /// See the [module documentation](super) for more details on the specific
255 /// grammar supported by this parser.
256 ///
257 /// # Example
258 ///
259 /// This shows a number of different duration formats that can be parsed
260 /// into a `std::time::Duration`:
261 ///
262 /// ```
263 /// use std::time::Duration;
264 ///
265 /// use jiff::fmt::friendly::SpanParser;
266 ///
267 /// let durations = [
268 /// ("2h30m", Duration::from_secs(2 * 60 * 60 + 30 * 60)),
269 /// ("2 hrs 30 mins", Duration::from_secs(2 * 60 * 60 + 30 * 60)),
270 /// ("2 hours 30 minutes", Duration::from_secs(2 * 60 * 60 + 30 * 60)),
271 /// ("2 hrs 30 minutes", Duration::from_secs(2 * 60 * 60 + 30 * 60)),
272 /// ("2.5h", Duration::from_secs(2 * 60 * 60 + 30 * 60)),
273 /// ("1m", Duration::from_secs(1 * 60)),
274 /// ("1.5m", Duration::from_secs(90)),
275 /// ("0.0021s", Duration::new(0, 2_100_000)),
276 /// ("0s", Duration::ZERO),
277 /// ("0.000000001s", Duration::from_nanos(1)),
278 /// ];
279 ///
280 /// static PARSER: SpanParser = SpanParser::new();
281 /// for (string, duration) in durations {
282 /// let parsed = PARSER.parse_unsigned_duration(string)?;
283 /// assert_eq!(duration, parsed, "result of parsing {string:?}");
284 /// }
285 ///
286 /// # Ok::<(), Box<dyn std::error::Error>>(())
287 /// ```
288#[inline]
289pub fn parse_unsigned_duration<I: AsRef<[u8]>>(
290&self,
291 input: I,
292 ) -> Result<core::time::Duration, Error> {
293#[inline(never)]
294fn imp(
295 span_parser: &SpanParser,
296 input: &[u8],
297 ) -> Result<core::time::Duration, Error> {
298let mut builder = DurationUnits::default();
299let parsed = span_parser.parse(input, &mut builder)?;
300let parsed =
301 parsed.and_then(|_| builder.to_unsigned_duration())?;
302let d = parsed.value;
303parsed.into_full_with(format_args!("{0:?}", d)format_args!("{d:?}"))
304 }
305306let input = input.as_ref();
307imp(self, input).context(E::Failed)
308 }
309310#[cfg_attr(feature = "perf-inline", inline(always))]
311fn parse<'i>(
312&self,
313 input: &'i [u8],
314 builder: &mut DurationUnits,
315 ) -> Result<Parsed<'i, ()>, Error> {
316if input.is_empty() {
317return Err(Error::from(E::Empty));
318 }
319// Guard prefix sign parsing to avoid the function call, which is
320 // marked unlineable to keep the fast path tighter.
321let (sign, input) =
322if !input.first().map_or(false, |&b| #[allow(non_exhaustive_omitted_patterns)] match b {
b'+' | b'-' => true,
_ => false,
}matches!(b, b'+' | b'-')) {
323 (None, input)
324 } else {
325let Parsed { value: sign, input } =
326self.parse_prefix_sign(input);
327 (sign, input)
328 };
329330let Parsed { value, input } = self.parse_unit_value(input)?;
331let Some(first_unit_value) = valueelse {
332return Err(Error::from(E::ExpectedIntegerAfterSign));
333 };
334335let Parsed { input, .. } =
336self.parse_duration_units(input, first_unit_value, builder)?;
337338// As with the prefix sign parsing, guard it to avoid calling the
339 // function.
340let (sign, input) = if !input.first().map_or(false, is_whitespace) {
341 (sign.unwrap_or(Sign::Positive), input)
342 } else {
343let parsed = self.parse_suffix_sign(sign, input)?;
344 (parsed.value, parsed.input)
345 };
346builder.set_sign(sign);
347Ok(Parsed { value: (), input })
348 }
349350#[cfg_attr(feature = "perf-inline", inline(always))]
351fn parse_duration_units<'i>(
352&self,
353mut input: &'i [u8],
354 first_unit_value: u64,
355 builder: &mut DurationUnits,
356 ) -> Result<Parsed<'i, ()>, Error> {
357let mut parsed_any_after_comma = true;
358let mut value = first_unit_value;
359loop {
360let parsed = self.parse_hms_maybe(input, value)?;
361input = parsed.input;
362if let Some(hms) = parsed.value {
363 builder.set_hms(
364 hms.hour,
365 hms.minute,
366 hms.second,
367 hms.fraction,
368 )?;
369break;
370 }
371372let fraction =
373if input.first().map_or(false, |&b| b == b'.' || b == b',') {
374let parsed = parse_temporal_fraction(input)?;
375input = parsed.input;
376parsed.value
377 } else {
378None379 };
380381// Eat any optional whitespace between the unit value and label.
382input = self.parse_optional_whitespace(input).input;
383384// Parse the actual unit label/designator.
385let parsed = self.parse_unit_designator(input)?;
386input = parsed.input;
387let unit = parsed.value;
388389// A comma is allowed to immediately follow the designator.
390 // Since this is a rarer case, we guard it with a check to see
391 // if the comma is there and only then call the function (which is
392 // marked unlineable to try and keep the hot path tighter).
393if input.first().map_or(false, |&b| b == b',') {
394input = self.parse_optional_comma(input)?.input;
395parsed_any_after_comma = false;
396 }
397398 builder.set_unit_value(unit, value)?;
399if let Some(fraction) = fraction {
400 builder.set_fraction(fraction)?;
401// Once we see a fraction, we are done. We don't permit parsing
402 // any more units. That is, a fraction can only occur on the
403 // lowest unit of time.
404break;
405 }
406407// Eat any optional whitespace after the designator (or comma) and
408 // before the next unit value. But if we don't see a unit value,
409 // we don't eat the whitespace.
410let after_whitespace = self.parse_optional_whitespace(input).input;
411let parsed = self.parse_unit_value(after_whitespace)?;
412value = match parsed.value {
413None => break,
414Some(value) => value,
415 };
416input = parsed.input;
417parsed_any_after_comma = true;
418 }
419if !parsed_any_after_comma {
420return Err(Error::from(E::ExpectedOneMoreUnitAfterComma));
421 }
422Ok(Parsed { value: (), input })
423 }
424425/// This possibly parses a `HH:MM:SS[.fraction]`.
426 ///
427 /// This expects that a unit value has been parsed and looks for a `:`
428 /// at `input[0]`. If `:` is found, then this proceeds to parse HMS.
429 /// Otherwise, a `None` value is returned.
430#[cfg_attr(feature = "perf-inline", inline(always))]
431fn parse_hms_maybe<'i>(
432&self,
433 input: &'i [u8],
434 hour: u64,
435 ) -> Result<Parsed<'i, Option<HMS>>, Error> {
436let Some((&first, tail)) = input.split_first() else {
437return Ok(Parsed { input, value: None });
438 };
439if first != b':' {
440return Ok(Parsed { input, value: None });
441 }
442let Parsed { input, value } = self.parse_hms(tail, hour)?;
443Ok(Parsed { input, value: Some(value) })
444 }
445446/// This parses a `HH:MM:SS[.fraction]` when it is known/expected to be
447 /// present.
448 ///
449 /// This is also marked as non-inlined since we expect this to be a
450 /// less common case. Where as `parse_hms_maybe` is called unconditionally
451 /// to check to see if the HMS should be parsed.
452 ///
453 /// This assumes that the beginning of `input` immediately follows the
454 /// first `:` in `HH:MM:SS[.fraction]`.
455#[inline(never)]
456fn parse_hms<'i>(
457&self,
458 input: &'i [u8],
459 hour: u64,
460 ) -> Result<Parsed<'i, HMS>, Error> {
461let Parsed { input, value } = self.parse_unit_value(input)?;
462let minute = value.ok_or(E::ExpectedMinuteAfterHour)?;
463464let (&first, input) =
465 input.split_first().ok_or(E::ExpectedColonAfterMinute)?;
466if first != b':' {
467return Err(Error::from(E::ExpectedColonAfterMinute));
468 }
469470let Parsed { input, value } = self.parse_unit_value(input)?;
471let second = value.ok_or(E::ExpectedSecondAfterMinute)?;
472let (fraction, input) =
473if input.first().map_or(false, |&b| b == b'.' || b == b',') {
474let parsed = parse_temporal_fraction(input)?;
475 (parsed.value, parsed.input)
476 } else {
477 (None, input)
478 };
479let hms = HMS { hour, minute, second, fraction };
480Ok(Parsed { input, value: hms })
481 }
482483/// Parsed a unit value, i.e., an integer.
484 ///
485 /// If no digits (`[0-9]`) were found at the current position of the parser
486 /// then `None` is returned. This means, for example, that parsing a
487 /// duration should stop.
488 ///
489 /// Note that this is safe to call on untrusted input. It will not attempt
490 /// to consume more input than could possibly fit into a parsed integer.
491 ///
492 /// Since this returns a `u64`, it is possible that an integer that cannot
493 /// fit into an `i64` is returned. Callers should handle this. (Indeed,
494 /// `DurationUnits` handles this case.)
495#[cfg_attr(feature = "perf-inline", inline(always))]
496fn parse_unit_value<'i>(
497&self,
498 input: &'i [u8],
499 ) -> Result<Parsed<'i, Option<u64>>, Error> {
500let (value, input) = parse::u64_prefix(input)?;
501Ok(Parsed { value, input })
502 }
503504/// Parse a unit designator, e.g., `years` or `nano`.
505 ///
506 /// If no designator could be found, including if the given `input` is
507 /// empty, then this return an error.
508 ///
509 /// This does not attempt to handle leading or trailing whitespace.
510#[cfg_attr(feature = "perf-inline", inline(always))]
511fn parse_unit_designator<'i>(
512&self,
513 input: &'i [u8],
514 ) -> Result<Parsed<'i, Unit>, Error> {
515let (unit, len) =
516 parser_label::find(input).ok_or(E::ExpectedUnitSuffix)?;
517Ok(Parsed { value: unit, input: &input[len..] })
518 }
519520/// Parses an optional prefix sign from the given input.
521 ///
522 /// A prefix sign is either a `+` or a `-`. If neither are found, then
523 /// `None` is returned.
524#[inline(never)]
525fn parse_prefix_sign<'i>(
526&self,
527 input: &'i [u8],
528 ) -> Parsed<'i, Option<Sign>> {
529let Some(sign) = input.first().copied() else {
530return Parsed { value: None, input };
531 };
532let sign = if sign == b'+' {
533 Sign::Positive534 } else if sign == b'-' {
535 Sign::Negative536 } else {
537return Parsed { value: None, input };
538 };
539Parsed { value: Some(sign), input: &input[1..] }
540 }
541542/// Parses an optional suffix sign from the given input.
543 ///
544 /// This requires, as input, the result of parsing a prefix sign since this
545 /// will return an error if both a prefix and a suffix sign were found.
546 ///
547 /// A suffix sign is the string `ago`. Any other string means that there is
548 /// no suffix sign. This will also look for mandatory whitespace and eat
549 /// any additional optional whitespace. i.e., This should be called
550 /// immediately after parsing the last unit designator/label.
551 ///
552 /// Regardless of whether a prefix or suffix sign was found, a definitive
553 /// sign is returned. (When there's no prefix or suffix sign, then the sign
554 /// returned is positive.)
555#[inline(never)]
556fn parse_suffix_sign<'i>(
557&self,
558 prefix_sign: Option<Sign>,
559mut input: &'i [u8],
560 ) -> Result<Parsed<'i, Sign>, Error> {
561if !input.first().map_or(false, is_whitespace) {
562let sign = prefix_sign.unwrap_or(Sign::Positive);
563return Ok(Parsed { value: sign, input });
564 }
565// Eat any additional whitespace we find before looking for 'ago'.
566input = self.parse_optional_whitespace(&input[1..]).input;
567let (suffix_sign, input) =
568if let Some(tail) = input.strip_prefix(b"ago") {
569 (Some(Sign::Negative), tail)
570 } else {
571 (None, input)
572 };
573let sign = match (prefix_sign, suffix_sign) {
574 (Some(_), Some(_)) => {
575return Err(Error::from(E::ExpectedOneSign));
576 }
577 (Some(sign), None) => sign,
578 (None, Some(sign)) => sign,
579 (None, None) => Sign::Positive,
580 };
581Ok(Parsed { value: sign, input })
582 }
583584/// Parses an optional comma following a unit designator.
585 ///
586 /// If a comma is seen, then it is mandatory that it be followed by
587 /// whitespace.
588 ///
589 /// This also takes care to provide a custom error message if the end of
590 /// input is seen after a comma.
591 ///
592 /// If `input` doesn't start with a comma, then this is a no-op.
593#[inline(never)]
594fn parse_optional_comma<'i>(
595&self,
596 input: &'i [u8],
597 ) -> Result<Parsed<'i, ()>, Error> {
598let Some((&first, tail)) = input.split_first() else {
599return Ok(Parsed { value: (), input });
600 };
601if first != b',' {
602return Ok(Parsed { value: (), input });
603 }
604605let (second, input) = tail
606 .split_first()
607 .ok_or(E::ExpectedWhitespaceAfterCommaEndOfInput)?;
608if !is_whitespace(second) {
609return Err(Error::from(E::ExpectedWhitespaceAfterComma {
610 byte: *second,
611 }));
612 }
613Ok(Parsed { value: (), input })
614 }
615616/// Parses zero or more bytes of ASCII whitespace.
617#[cfg_attr(feature = "perf-inline", inline(always))]
618fn parse_optional_whitespace<'i>(
619&self,
620mut input: &'i [u8],
621 ) -> Parsed<'i, ()> {
622while input.first().map_or(false, is_whitespace) {
623 input = &input[1..];
624 }
625Parsed { value: (), input }
626 }
627}
628629/// A type that represents the parsed components of `HH:MM:SS[.fraction]`.
630#[derive(#[automatically_derived]impl ::core::fmt::Debug for HMS {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"HMS hour minute second fraction", &self.hour, &self.minute,
&self.second, &&self.fraction)
}
}Debug)]
631struct HMS {
632 hour: u64,
633 minute: u64,
634 second: u64,
635 fraction: Option<u32>,
636}
637638/// Returns true if the byte is ASCII whitespace.
639#[cfg_attr(feature = "perf-inline", inline(always))]
640fn is_whitespace(byte: &u8) -> bool {
641#[allow(non_exhaustive_omitted_patterns)] match *byte {
b' ' | b'\t' | b'\n' | b'\r' | b'\x0C' => true,
_ => false,
}matches!(*byte, b' ' | b'\t' | b'\n' | b'\r' | b'\x0C')642}
643644#[cfg(feature = "alloc")]
645#[cfg(test)]
646mod tests {
647use super::*;
648649#[test]
650fn parse_span_basic() {
651let p = |s: &str| SpanParser::new().parse_span(s).unwrap();
652653insta::assert_snapshot!(p("5 years"), @"P5Y");
654insta::assert_snapshot!(p("5 years 4 months"), @"P5Y4M");
655insta::assert_snapshot!(p("5 years 4 months 3 hours"), @"P5Y4MT3H");
656insta::assert_snapshot!(p("5 years, 4 months, 3 hours"), @"P5Y4MT3H");
657658insta::assert_snapshot!(p("01:02:03"), @"PT1H2M3S");
659insta::assert_snapshot!(p("5 days 01:02:03"), @"P5DT1H2M3S");
660// This is Python's `str(timedelta)` format!
661insta::assert_snapshot!(p("5 days, 01:02:03"), @"P5DT1H2M3S");
662insta::assert_snapshot!(p("3yrs 5 days 01:02:03"), @"P3Y5DT1H2M3S");
663insta::assert_snapshot!(p("3yrs 5 days, 01:02:03"), @"P3Y5DT1H2M3S");
664insta::assert_snapshot!(
665 p("3yrs 5 days, 01:02:03.123456789"),
666 @"P3Y5DT1H2M3.123456789S",
667 );
668insta::assert_snapshot!(p("999:999:999"), @"PT999H999M999S");
669 }
670671#[test]
672fn parse_span_fractional() {
673let p = |s: &str| SpanParser::new().parse_span(s).unwrap();
674675insta::assert_snapshot!(p("1.5hrs"), @"PT1H30M");
676insta::assert_snapshot!(p("1.5mins"), @"PT1M30S");
677insta::assert_snapshot!(p("1.5secs"), @"PT1.5S");
678insta::assert_snapshot!(p("1.5msecs"), @"PT0.0015S");
679insta::assert_snapshot!(p("1.5µsecs"), @"PT0.0000015S");
680insta::assert_snapshot!(p("-0.5secs"), @"-PT0.5S");
681insta::assert_snapshot!(p("0.5secs ago"), @"-PT0.5S");
682683insta::assert_snapshot!(p("1d 1.5hrs"), @"P1DT1H30M");
684insta::assert_snapshot!(p("1h 1.5mins"), @"PT1H1M30S");
685insta::assert_snapshot!(p("1m 1.5secs"), @"PT1M1.5S");
686insta::assert_snapshot!(p("1s 1.5msecs"), @"PT1.0015S");
687insta::assert_snapshot!(p("1ms 1.5µsecs"), @"PT0.0010015S");
688689insta::assert_snapshot!(p("1s2000ms"), @"PT3S");
690 }
691692#[test]
693fn parse_span_boundaries() {
694let p = |s: &str| SpanParser::new().parse_span(s).unwrap();
695696insta::assert_snapshot!(p("19998 years"), @"P19998Y");
697insta::assert_snapshot!(p("19998 years ago"), @"-P19998Y");
698insta::assert_snapshot!(p("239976 months"), @"P239976M");
699insta::assert_snapshot!(p("239976 months ago"), @"-P239976M");
700insta::assert_snapshot!(p("1043497 weeks"), @"P1043497W");
701insta::assert_snapshot!(p("1043497 weeks ago"), @"-P1043497W");
702insta::assert_snapshot!(p("7304484 days"), @"P7304484D");
703insta::assert_snapshot!(p("7304484 days ago"), @"-P7304484D");
704insta::assert_snapshot!(p("175307616 hours"), @"PT175307616H");
705insta::assert_snapshot!(p("175307616 hours ago"), @"-PT175307616H");
706insta::assert_snapshot!(p("10518456960 minutes"), @"PT10518456960M");
707insta::assert_snapshot!(p("10518456960 minutes ago"), @"-PT10518456960M");
708insta::assert_snapshot!(p("631107417600 seconds"), @"PT631107417600S");
709insta::assert_snapshot!(p("631107417600 seconds ago"), @"-PT631107417600S");
710insta::assert_snapshot!(p("631107417600000 milliseconds"), @"PT631107417600S");
711insta::assert_snapshot!(p("631107417600000 milliseconds ago"), @"-PT631107417600S");
712insta::assert_snapshot!(p("631107417600000000 microseconds"), @"PT631107417600S");
713insta::assert_snapshot!(p("631107417600000000 microseconds ago"), @"-PT631107417600S");
714insta::assert_snapshot!(p("9223372036854775807 nanoseconds"), @"PT9223372036.854775807S");
715insta::assert_snapshot!(p("9223372036854775807 nanoseconds ago"), @"-PT9223372036.854775807S");
716717insta::assert_snapshot!(p("175307617 hours"), @"PT175307616H60M");
718insta::assert_snapshot!(p("175307617 hours ago"), @"-PT175307616H60M");
719insta::assert_snapshot!(p("10518456961 minutes"), @"PT10518456960M60S");
720insta::assert_snapshot!(p("10518456961 minutes ago"), @"-PT10518456960M60S");
721insta::assert_snapshot!(p("631107417601 seconds"), @"PT631107417601S");
722insta::assert_snapshot!(p("631107417601 seconds ago"), @"-PT631107417601S");
723insta::assert_snapshot!(p("631107417600001 milliseconds"), @"PT631107417600.001S");
724insta::assert_snapshot!(p("631107417600001 milliseconds ago"), @"-PT631107417600.001S");
725insta::assert_snapshot!(p("631107417600000001 microseconds"), @"PT631107417600.000001S");
726insta::assert_snapshot!(p("631107417600000001 microseconds ago"), @"-PT631107417600.000001S");
727// We don't include nanoseconds here, because that will fail to
728 // parse due to overflowing i64.
729}
730731// When a time unit exceeds its limit, the excess is carried over into
732 // smaller units. This tests that the excess is combined with any smaller
733 // units that were also parsed, instead of one clobbering the other.
734 //
735 // Regression test for: https://github.com/BurntSushi/jiff/issues/660
736#[test]
737fn parse_span_boundaries_carry() {
738// This also checks that the span parsed is consistent with parsing
739 // the same input into a `SignedDuration`.
740let p = |s: &str| {
741let span = SpanParser::new().parse_span(s).unwrap();
742let dur = SpanParser::new().parse_duration(s).unwrap();
743assert_eq!(dur, SignedDuration::try_from(span).unwrap(), "{s}");
744 span
745 };
746let pe = |s: &str| SpanParser::new().parse_span(s).unwrap_err();
747748insta::assert_snapshot!(p("175307617h 1m"), @"PT175307616H61M");
749insta::assert_snapshot!(p("175307617h 1m ago"), @"-PT175307616H61M");
750insta::assert_snapshot!(p("200000000h 30m"), @"PT175307616H1481543070M");
751insta::assert_snapshot!(p("200000000:30:00"), @"PT175307616H1481543070M");
752insta::assert_snapshot!(p("200000000h 30.5m"), @"PT175307616H1481543070M30S");
753insta::assert_snapshot!(p("10518456961m 1s"), @"PT10518456960M61S");
754insta::assert_snapshot!(p("631107417601s 1ms"), @"PT631107417601.001S");
755insta::assert_snapshot!(p("631107417600001ms 1us"), @"PT631107417600.001001S");
756insta::assert_snapshot!(p("631107417600000001us 1ns"), @"PT631107417600.000001001S");
757758// The minutes are already at their limit, so the extra hour needs to
759 // skip over them and get added to the seconds.
760insta::assert_snapshot!(
761 p("175307617h 10518456960m 1s"),
762 @"PT175307616H10518456960M3601S",
763 );
764765// Combining the excess with the seconds overflows an `i64`.
766insta::assert_snapshot!(
767 pe("10518456961m 9223372036854775807s"),
768 @r#"failed to parse input in the "friendly" duration format: failed to set value for second unit on span: failed to set nanosecond value from fractional component"#,
769 );
770 }
771772#[test]
773fn err_span_basic() {
774let p = |s: &str| SpanParser::new().parse_span(s).unwrap_err();
775776insta::assert_snapshot!(
777 p(""),
778 @r#"failed to parse input in the "friendly" duration format: an empty string is not valid"#,
779 );
780insta::assert_snapshot!(
781 p(" "),
782 @r#"failed to parse input in the "friendly" duration format: expected duration to start with a unit value (a decimal integer) after an optional sign, but no integer was found"#,
783 );
784insta::assert_snapshot!(
785 p("a"),
786 @r#"failed to parse input in the "friendly" duration format: expected duration to start with a unit value (a decimal integer) after an optional sign, but no integer was found"#,
787 );
788insta::assert_snapshot!(
789 p("2 months 1 year"),
790 @r#"failed to parse input in the "friendly" duration format: found value with unit year after unit month, but units must be written from largest to smallest (and they can't be repeated)"#,
791 );
792insta::assert_snapshot!(
793 p("1 year 1 mont"),
794 @r#"failed to parse input in the "friendly" duration format: parsed value 'P1Y1M', but unparsed input "nt" remains (expected no unparsed input)"#,
795 );
796insta::assert_snapshot!(
797 p("2 months,"),
798 @r#"failed to parse input in the "friendly" duration format: expected whitespace after comma, but found end of input"#,
799 );
800insta::assert_snapshot!(
801 p("2 months, "),
802 @r#"failed to parse input in the "friendly" duration format: found comma at the end of duration, but a comma indicates at least one more unit follows"#,
803 );
804insta::assert_snapshot!(
805 p("2 months ,"),
806 @r#"failed to parse input in the "friendly" duration format: parsed value 'P2M', but unparsed input "," remains (expected no unparsed input)"#,
807 );
808 }
809810#[test]
811fn err_span_sign() {
812let p = |s: &str| SpanParser::new().parse_span(s).unwrap_err();
813814insta::assert_snapshot!(
815 p("1yago"),
816 @r#"failed to parse input in the "friendly" duration format: parsed value 'P1Y', but unparsed input "ago" remains (expected no unparsed input)"#,
817 );
818insta::assert_snapshot!(
819 p("1 year 1 monthago"),
820 @r#"failed to parse input in the "friendly" duration format: parsed value 'P1Y1M', but unparsed input "ago" remains (expected no unparsed input)"#,
821 );
822insta::assert_snapshot!(
823 p("+1 year 1 month ago"),
824 @r#"failed to parse input in the "friendly" duration format: expected to find either a prefix sign (+/-) or a suffix sign (`ago`), but found both"#,
825 );
826insta::assert_snapshot!(
827 p("-1 year 1 month ago"),
828 @r#"failed to parse input in the "friendly" duration format: expected to find either a prefix sign (+/-) or a suffix sign (`ago`), but found both"#,
829 );
830 }
831832#[test]
833fn err_span_overflow_fraction() {
834let p = |s: &str| SpanParser::new().parse_span(s).unwrap();
835let pe = |s: &str| SpanParser::new().parse_span(s).unwrap_err();
836837insta::assert_snapshot!(
838// One fewer micro, and this parses okay. The error occurs because
839 // the maximum number of microseconds is subtracted off, and we're
840 // left over with a value that overflows an i64.
841pe("640330789636854776 micros"),
842 @r#"failed to parse input in the "friendly" duration format: failed to set value for microsecond unit on span: failed to set nanosecond value from fractional component"#,
843 );
844// one fewer is okay
845insta::assert_snapshot!(
846 p("640330789636854775 micros"),
847 @"PT640330789636.854775S"
848);
849850insta::assert_snapshot!(
851// This is like the test above, but actually exercises a slightly
852 // different error path by using an explicit fraction. Here, if
853 // we had x.807 micros, it would parse successfully.
854pe("640330789636854775.808 micros"),
855 @r#"failed to parse input in the "friendly" duration format: failed to set nanosecond value from fractional component"#,
856 );
857// one fewer is okay
858insta::assert_snapshot!(
859 p("640330789636854775.807 micros"),
860 @"PT640330789636.854775807S"
861);
862 }
863864#[test]
865fn err_span_overflow_units() {
866let p = |s: &str| SpanParser::new().parse_span(s).unwrap_err();
867868insta::assert_snapshot!(
869 p("19999 years"),
870 @r#"failed to parse input in the "friendly" duration format: failed to set value for year unit on span: parameter 'years' is not in the required range of -19998..=19998"#,
871 );
872insta::assert_snapshot!(
873 p("19999 years ago"),
874 @r#"failed to parse input in the "friendly" duration format: failed to set value for year unit on span: parameter 'years' is not in the required range of -19998..=19998"#,
875 );
876877insta::assert_snapshot!(
878 p("239977 months"),
879 @r#"failed to parse input in the "friendly" duration format: failed to set value for month unit on span: parameter 'months' is not in the required range of -239976..=239976"#,
880 );
881insta::assert_snapshot!(
882 p("239977 months ago"),
883 @r#"failed to parse input in the "friendly" duration format: failed to set value for month unit on span: parameter 'months' is not in the required range of -239976..=239976"#,
884 );
885886insta::assert_snapshot!(
887 p("1043498 weeks"),
888 @r#"failed to parse input in the "friendly" duration format: failed to set value for week unit on span: parameter 'weeks' is not in the required range of -1043497..=1043497"#,
889 );
890insta::assert_snapshot!(
891 p("1043498 weeks ago"),
892 @r#"failed to parse input in the "friendly" duration format: failed to set value for week unit on span: parameter 'weeks' is not in the required range of -1043497..=1043497"#,
893 );
894895insta::assert_snapshot!(
896 p("7304485 days"),
897 @r#"failed to parse input in the "friendly" duration format: failed to set value for day unit on span: parameter 'days' is not in the required range of -7304484..=7304484"#,
898 );
899insta::assert_snapshot!(
900 p("7304485 days ago"),
901 @r#"failed to parse input in the "friendly" duration format: failed to set value for day unit on span: parameter 'days' is not in the required range of -7304484..=7304484"#,
902 );
903904insta::assert_snapshot!(
905 p("9223372036854775808 nanoseconds"),
906 @r#"failed to parse input in the "friendly" duration format: value for nanoseconds is too big (or small) to fit into a signed 64-bit integer"#,
907 );
908insta::assert_snapshot!(
909 p("9223372036854775808 nanoseconds ago"),
910 @r#"failed to parse input in the "friendly" duration format: failed to set value for nanosecond unit on span: parameter 'nanoseconds' is not in the required range of -9223372036854775807..=9223372036854775807"#,
911 );
912 }
913914#[test]
915fn err_span_fraction() {
916let p = |s: &str| SpanParser::new().parse_span(s).unwrap_err();
917918insta::assert_snapshot!(
919 p("1.5 years"),
920 @r#"failed to parse input in the "friendly" duration format: fractional years are not supported"#,
921 );
922insta::assert_snapshot!(
923 p("1.5 nanos"),
924 @r#"failed to parse input in the "friendly" duration format: fractional nanoseconds are not supported"#,
925 );
926 }
927928#[test]
929fn err_span_hms() {
930let p = |s: &str| SpanParser::new().parse_span(s).unwrap_err();
931932insta::assert_snapshot!(
933 p("05:"),
934 @r#"failed to parse input in the "friendly" duration format: when parsing the `HH:MM:SS` format, expected to parse minute following hour"#,
935 );
936insta::assert_snapshot!(
937 p("05:06"),
938 @r#"failed to parse input in the "friendly" duration format: when parsing the `HH:MM:SS` format, expected to parse `:` following minute"#,
939 );
940insta::assert_snapshot!(
941 p("05:06:"),
942 @r#"failed to parse input in the "friendly" duration format: when parsing the `HH:MM:SS` format, expected to parse second following minute"#,
943 );
944insta::assert_snapshot!(
945 p("2 hours, 05:06:07"),
946 @r#"failed to parse input in the "friendly" duration format: found `HH:MM:SS` after unit hour, but `HH:MM:SS` can only appear after years, months, weeks or days"#,
947 );
948 }
949950#[test]
951fn parse_signed_duration_basic() {
952let p = |s: &str| SpanParser::new().parse_duration(s).unwrap();
953954insta::assert_snapshot!(p("1 hour, 2 minutes, 3 seconds"), @"PT1H2M3S");
955insta::assert_snapshot!(p("01:02:03"), @"PT1H2M3S");
956insta::assert_snapshot!(p("999:999:999"), @"PT1015H55M39S");
957 }
958959#[test]
960fn parse_signed_duration_negate() {
961let p = |s: &str| SpanParser::new().parse_duration(s).unwrap();
962let perr = |s: &str| SpanParser::new().parse_duration(s).unwrap_err();
963964insta::assert_snapshot!(
965 p("9223372036854775807s"),
966 @"PT2562047788015215H30M7S",
967 );
968insta::assert_snapshot!(
969 perr("9223372036854775808s"),
970 @r#"failed to parse input in the "friendly" duration format: value for seconds is too big (or small) to fit into a signed 64-bit integer"#,
971 );
972insta::assert_snapshot!(
973 p("-9223372036854775808s"),
974 @"-PT2562047788015215H30M8S",
975 );
976 }
977978#[test]
979fn parse_signed_duration_fractional() {
980let p = |s: &str| SpanParser::new().parse_duration(s).unwrap();
981982insta::assert_snapshot!(p("1.5hrs"), @"PT1H30M");
983insta::assert_snapshot!(p("1.5mins"), @"PT1M30S");
984insta::assert_snapshot!(p("1.5secs"), @"PT1.5S");
985insta::assert_snapshot!(p("1.5msecs"), @"PT0.0015S");
986insta::assert_snapshot!(p("1.5µsecs"), @"PT0.0000015S");
987insta::assert_snapshot!(p("-0.5secs"), @"-PT0.5S");
988insta::assert_snapshot!(p("0.5secs ago"), @"-PT0.5S");
989990insta::assert_snapshot!(p("1h 1.5mins"), @"PT1H1M30S");
991insta::assert_snapshot!(p("1m 1.5secs"), @"PT1M1.5S");
992insta::assert_snapshot!(p("1s 1.5msecs"), @"PT1.0015S");
993insta::assert_snapshot!(p("1ms 1.5µsecs"), @"PT0.0010015S");
994995insta::assert_snapshot!(p("1s2000ms"), @"PT3S");
996 }
997998#[test]
999fn parse_signed_duration_boundaries() {
1000let p = |s: &str| SpanParser::new().parse_duration(s).unwrap();
1001let pe = |s: &str| SpanParser::new().parse_duration(s).unwrap_err();
10021003insta::assert_snapshot!(p("175307616 hours"), @"PT175307616H");
1004insta::assert_snapshot!(p("175307616 hours ago"), @"-PT175307616H");
1005insta::assert_snapshot!(p("10518456960 minutes"), @"PT175307616H");
1006insta::assert_snapshot!(p("10518456960 minutes ago"), @"-PT175307616H");
1007insta::assert_snapshot!(p("631107417600 seconds"), @"PT175307616H");
1008insta::assert_snapshot!(p("631107417600 seconds ago"), @"-PT175307616H");
1009insta::assert_snapshot!(p("631107417600000 milliseconds"), @"PT175307616H");
1010insta::assert_snapshot!(p("631107417600000 milliseconds ago"), @"-PT175307616H");
1011insta::assert_snapshot!(p("631107417600000000 microseconds"), @"PT175307616H");
1012insta::assert_snapshot!(p("631107417600000000 microseconds ago"), @"-PT175307616H");
1013insta::assert_snapshot!(p("9223372036854775807 nanoseconds"), @"PT2562047H47M16.854775807S");
1014insta::assert_snapshot!(p("9223372036854775807 nanoseconds ago"), @"-PT2562047H47M16.854775807S");
10151016insta::assert_snapshot!(p("175307617 hours"), @"PT175307617H");
1017insta::assert_snapshot!(p("175307617 hours ago"), @"-PT175307617H");
1018insta::assert_snapshot!(p("10518456961 minutes"), @"PT175307616H1M");
1019insta::assert_snapshot!(p("10518456961 minutes ago"), @"-PT175307616H1M");
1020insta::assert_snapshot!(p("631107417601 seconds"), @"PT175307616H1S");
1021insta::assert_snapshot!(p("631107417601 seconds ago"), @"-PT175307616H1S");
1022insta::assert_snapshot!(p("631107417600001 milliseconds"), @"PT175307616H0.001S");
1023insta::assert_snapshot!(p("631107417600001 milliseconds ago"), @"-PT175307616H0.001S");
1024insta::assert_snapshot!(p("631107417600000001 microseconds"), @"PT175307616H0.000001S");
1025insta::assert_snapshot!(p("631107417600000001 microseconds ago"), @"-PT175307616H0.000001S");
1026// We don't include nanoseconds here, because that will fail to
1027 // parse due to overflowing i64.
10281029 // The above were copied from the corresponding `Span` test, which has
1030 // tighter limits on components. But a `SignedDuration` supports the
1031 // full range of `i64` seconds.
1032insta::assert_snapshot!(p("2562047788015215hours"), @"PT2562047788015215H");
1033insta::assert_snapshot!(p("-2562047788015215hours"), @"-PT2562047788015215H");
1034insta::assert_snapshot!(
1035 pe("2562047788015216hrs"),
1036 @r#"failed to parse input in the "friendly" duration format: accumulated duration overflowed when adding value to unit hour"#,
1037 );
10381039insta::assert_snapshot!(p("153722867280912930minutes"), @"PT2562047788015215H30M");
1040insta::assert_snapshot!(p("153722867280912930minutes ago"), @"-PT2562047788015215H30M");
1041insta::assert_snapshot!(
1042 pe("153722867280912931mins"),
1043 @r#"failed to parse input in the "friendly" duration format: accumulated duration overflowed when adding value to unit minute"#,
1044 );
10451046insta::assert_snapshot!(p("9223372036854775807seconds"), @"PT2562047788015215H30M7S");
1047insta::assert_snapshot!(p("-9223372036854775807seconds"), @"-PT2562047788015215H30M7S");
1048insta::assert_snapshot!(
1049 pe("9223372036854775808s"),
1050 @r#"failed to parse input in the "friendly" duration format: value for seconds is too big (or small) to fit into a signed 64-bit integer"#,
1051 );
1052insta::assert_snapshot!(
1053 p("-9223372036854775808s"),
1054 @"-PT2562047788015215H30M8S",
1055 );
1056 }
10571058#[test]
1059fn err_signed_duration_basic() {
1060let p = |s: &str| SpanParser::new().parse_duration(s).unwrap_err();
10611062insta::assert_snapshot!(
1063 p(""),
1064 @r#"failed to parse input in the "friendly" duration format: an empty string is not valid"#,
1065 );
1066insta::assert_snapshot!(
1067 p(" "),
1068 @r#"failed to parse input in the "friendly" duration format: expected duration to start with a unit value (a decimal integer) after an optional sign, but no integer was found"#,
1069 );
1070insta::assert_snapshot!(
1071 p("5"),
1072 @r#"failed to parse input in the "friendly" duration format: expected to find unit designator suffix (e.g., `years` or `secs`) after parsing integer"#,
1073 );
1074insta::assert_snapshot!(
1075 p("a"),
1076 @r#"failed to parse input in the "friendly" duration format: expected duration to start with a unit value (a decimal integer) after an optional sign, but no integer was found"#,
1077 );
1078insta::assert_snapshot!(
1079 p("2 minutes 1 hour"),
1080 @r#"failed to parse input in the "friendly" duration format: found value with unit hour after unit minute, but units must be written from largest to smallest (and they can't be repeated)"#,
1081 );
1082insta::assert_snapshot!(
1083 p("1 hour 1 minut"),
1084 @r#"failed to parse input in the "friendly" duration format: parsed value 'PT1H1M', but unparsed input "ut" remains (expected no unparsed input)"#,
1085 );
1086insta::assert_snapshot!(
1087 p("2 minutes,"),
1088 @r#"failed to parse input in the "friendly" duration format: expected whitespace after comma, but found end of input"#,
1089 );
1090insta::assert_snapshot!(
1091 p("2 minutes, "),
1092 @r#"failed to parse input in the "friendly" duration format: found comma at the end of duration, but a comma indicates at least one more unit follows"#,
1093 );
1094insta::assert_snapshot!(
1095 p("2 minutes ,"),
1096 @r#"failed to parse input in the "friendly" duration format: parsed value 'PT2M', but unparsed input "," remains (expected no unparsed input)"#,
1097 );
1098 }
10991100#[test]
1101fn err_signed_duration_sign() {
1102let p = |s: &str| SpanParser::new().parse_duration(s).unwrap_err();
11031104insta::assert_snapshot!(
1105 p("1hago"),
1106 @r#"failed to parse input in the "friendly" duration format: parsed value 'PT1H', but unparsed input "ago" remains (expected no unparsed input)"#,
1107 );
1108insta::assert_snapshot!(
1109 p("1 hour 1 minuteago"),
1110 @r#"failed to parse input in the "friendly" duration format: parsed value 'PT1H1M', but unparsed input "ago" remains (expected no unparsed input)"#,
1111 );
1112insta::assert_snapshot!(
1113 p("+1 hour 1 minute ago"),
1114 @r#"failed to parse input in the "friendly" duration format: expected to find either a prefix sign (+/-) or a suffix sign (`ago`), but found both"#,
1115 );
1116insta::assert_snapshot!(
1117 p("-1 hour 1 minute ago"),
1118 @r#"failed to parse input in the "friendly" duration format: expected to find either a prefix sign (+/-) or a suffix sign (`ago`), but found both"#,
1119 );
1120 }
11211122#[test]
1123fn err_signed_duration_overflow_fraction() {
1124let p = |s: &str| SpanParser::new().parse_duration(s).unwrap();
1125let pe = |s: &str| SpanParser::new().parse_duration(s).unwrap_err();
11261127insta::assert_snapshot!(
1128// Unlike `Span`, this just overflows because it can't be parsed
1129 // as a 64-bit integer.
1130pe("9223372036854775808 micros"),
1131 @r#"failed to parse input in the "friendly" duration format: value for microseconds is too big (or small) to fit into a signed 64-bit integer"#,
1132 );
1133// one fewer is okay
1134insta::assert_snapshot!(
1135 p("9223372036854775807 micros"),
1136 @"PT2562047788H54.775807S"
1137);
1138 }
11391140#[test]
1141fn err_signed_duration_fraction() {
1142let p = |s: &str| SpanParser::new().parse_duration(s).unwrap_err();
11431144insta::assert_snapshot!(
1145 p("1.5 nanos"),
1146 @r#"failed to parse input in the "friendly" duration format: fractional nanoseconds are not supported"#,
1147 );
1148 }
11491150#[test]
1151fn err_signed_duration_hms() {
1152let p = |s: &str| SpanParser::new().parse_duration(s).unwrap_err();
11531154insta::assert_snapshot!(
1155 p("05:"),
1156 @r#"failed to parse input in the "friendly" duration format: when parsing the `HH:MM:SS` format, expected to parse minute following hour"#,
1157 );
1158insta::assert_snapshot!(
1159 p("05:06"),
1160 @r#"failed to parse input in the "friendly" duration format: when parsing the `HH:MM:SS` format, expected to parse `:` following minute"#,
1161 );
1162insta::assert_snapshot!(
1163 p("05:06:"),
1164 @r#"failed to parse input in the "friendly" duration format: when parsing the `HH:MM:SS` format, expected to parse second following minute"#,
1165 );
1166insta::assert_snapshot!(
1167 p("2 hours, 05:06:07"),
1168 @r#"failed to parse input in the "friendly" duration format: found `HH:MM:SS` after unit hour, but `HH:MM:SS` can only appear after years, months, weeks or days"#,
1169 );
1170 }
11711172#[test]
1173fn parse_unsigned_duration_basic() {
1174let p = |s: &str| {
1175let dur = SpanParser::new().parse_unsigned_duration(s).unwrap();
1176crate::fmt::temporal::SpanPrinter::new()
1177 .unsigned_duration_to_string(&dur)
1178 };
11791180insta::assert_snapshot!(
1181 p("1 hour, 2 minutes, 3 seconds"),
1182 @"PT1H2M3S",
1183 );
1184insta::assert_snapshot!(p("01:02:03"), @"PT1H2M3S");
1185insta::assert_snapshot!(p("999:999:999"), @"PT1015H55M39S");
1186insta::assert_snapshot!(
1187 p("+1hr"),
1188 @"PT1H",
1189 );
1190 }
11911192#[test]
1193fn parse_unsigned_duration_negate() {
1194let p = |s: &str| {
1195let dur = SpanParser::new().parse_unsigned_duration(s).unwrap();
1196crate::fmt::temporal::SpanPrinter::new()
1197 .unsigned_duration_to_string(&dur)
1198 };
1199let perr = |s: &str| {
1200 SpanParser::new().parse_unsigned_duration(s).unwrap_err()
1201 };
12021203insta::assert_snapshot!(
1204 p("18446744073709551615s"),
1205 @"PT5124095576030431H15S",
1206 );
1207insta::assert_snapshot!(
1208 perr("18446744073709551616s"),
1209 @r#"failed to parse input in the "friendly" duration format: number too big to parse into 64-bit integer"#,
1210 );
1211insta::assert_snapshot!(
1212 perr("-1s"),
1213 @r#"failed to parse input in the "friendly" duration format: cannot parse negative duration into unsigned `std::time::Duration`"#,
1214 );
1215 }
12161217#[test]
1218fn parse_unsigned_duration_fractional() {
1219let p = |s: &str| {
1220let dur = SpanParser::new().parse_unsigned_duration(s).unwrap();
1221crate::fmt::temporal::SpanPrinter::new()
1222 .unsigned_duration_to_string(&dur)
1223 };
12241225insta::assert_snapshot!(p("1.5hrs"), @"PT1H30M");
1226insta::assert_snapshot!(p("1.5mins"), @"PT1M30S");
1227insta::assert_snapshot!(p("1.5secs"), @"PT1.5S");
1228insta::assert_snapshot!(p("1.5msecs"), @"PT0.0015S");
1229insta::assert_snapshot!(p("1.5µsecs"), @"PT0.0000015S");
12301231insta::assert_snapshot!(p("1h 1.5mins"), @"PT1H1M30S");
1232insta::assert_snapshot!(p("1m 1.5secs"), @"PT1M1.5S");
1233insta::assert_snapshot!(p("1s 1.5msecs"), @"PT1.0015S");
1234insta::assert_snapshot!(p("1ms 1.5µsecs"), @"PT0.0010015S");
12351236insta::assert_snapshot!(p("1s2000ms"), @"PT3S");
1237 }
12381239#[test]
1240fn parse_unsigned_duration_boundaries() {
1241let p = |s: &str| {
1242let dur = SpanParser::new().parse_unsigned_duration(s).unwrap();
1243crate::fmt::temporal::SpanPrinter::new()
1244 .unsigned_duration_to_string(&dur)
1245 };
1246let pe = |s: &str| SpanParser::new().parse_duration(s).unwrap_err();
12471248insta::assert_snapshot!(p("175307616 hours"), @"PT175307616H");
1249insta::assert_snapshot!(p("10518456960 minutes"), @"PT175307616H");
1250insta::assert_snapshot!(p("631107417600 seconds"), @"PT175307616H");
1251insta::assert_snapshot!(p("631107417600000 milliseconds"), @"PT175307616H");
1252insta::assert_snapshot!(p("631107417600000000 microseconds"), @"PT175307616H");
1253insta::assert_snapshot!(p("9223372036854775807 nanoseconds"), @"PT2562047H47M16.854775807S");
12541255insta::assert_snapshot!(p("175307617 hours"), @"PT175307617H");
1256insta::assert_snapshot!(p("10518456961 minutes"), @"PT175307616H1M");
1257insta::assert_snapshot!(p("631107417601 seconds"), @"PT175307616H1S");
1258insta::assert_snapshot!(p("631107417600001 milliseconds"), @"PT175307616H0.001S");
1259insta::assert_snapshot!(p("631107417600000001 microseconds"), @"PT175307616H0.000001S");
12601261// The above were copied from the corresponding `Span` test, which has
1262 // tighter limits on components. But a `std::time::Duration` supports
1263 // the full range of `u64` seconds.
1264insta::assert_snapshot!(p("5124095576030431hours"), @"PT5124095576030431H");
1265insta::assert_snapshot!(
1266 pe("5124095576030432hrs"),
1267 @r#"failed to parse input in the "friendly" duration format: accumulated duration overflowed when adding value to unit hour"#,
1268 );
12691270insta::assert_snapshot!(p("307445734561825860minutes"), @"PT5124095576030431H");
1271insta::assert_snapshot!(
1272 pe("307445734561825861mins"),
1273 @r#"failed to parse input in the "friendly" duration format: accumulated duration overflowed when adding value to unit minute"#,
1274 );
12751276insta::assert_snapshot!(p("18446744073709551615seconds"), @"PT5124095576030431H15S");
1277insta::assert_snapshot!(
1278 pe("18446744073709551616s"),
1279 @r#"failed to parse input in the "friendly" duration format: number too big to parse into 64-bit integer"#,
1280 );
1281 }
12821283#[test]
1284fn err_unsigned_duration_basic() {
1285let p = |s: &str| {
1286 SpanParser::new().parse_unsigned_duration(s).unwrap_err()
1287 };
12881289insta::assert_snapshot!(
1290 p(""),
1291 @r#"failed to parse input in the "friendly" duration format: an empty string is not valid"#,
1292 );
1293insta::assert_snapshot!(
1294 p(" "),
1295 @r#"failed to parse input in the "friendly" duration format: expected duration to start with a unit value (a decimal integer) after an optional sign, but no integer was found"#,
1296 );
1297insta::assert_snapshot!(
1298 p("5"),
1299 @r#"failed to parse input in the "friendly" duration format: expected to find unit designator suffix (e.g., `years` or `secs`) after parsing integer"#,
1300 );
1301insta::assert_snapshot!(
1302 p("a"),
1303 @r#"failed to parse input in the "friendly" duration format: expected duration to start with a unit value (a decimal integer) after an optional sign, but no integer was found"#,
1304 );
1305insta::assert_snapshot!(
1306 p("2 minutes 1 hour"),
1307 @r#"failed to parse input in the "friendly" duration format: found value with unit hour after unit minute, but units must be written from largest to smallest (and they can't be repeated)"#,
1308 );
1309insta::assert_snapshot!(
1310 p("1 hour 1 minut"),
1311 @r#"failed to parse input in the "friendly" duration format: parsed value '3660s', but unparsed input "ut" remains (expected no unparsed input)"#,
1312 );
1313insta::assert_snapshot!(
1314 p("2 minutes,"),
1315 @r#"failed to parse input in the "friendly" duration format: expected whitespace after comma, but found end of input"#,
1316 );
1317insta::assert_snapshot!(
1318 p("2 minutes, "),
1319 @r#"failed to parse input in the "friendly" duration format: found comma at the end of duration, but a comma indicates at least one more unit follows"#,
1320 );
1321insta::assert_snapshot!(
1322 p("2 minutes ,"),
1323 @r#"failed to parse input in the "friendly" duration format: parsed value '120s', but unparsed input "," remains (expected no unparsed input)"#,
1324 );
1325 }
13261327#[test]
1328fn err_unsigned_duration_sign() {
1329let p = |s: &str| {
1330 SpanParser::new().parse_unsigned_duration(s).unwrap_err()
1331 };
13321333insta::assert_snapshot!(
1334 p("1hago"),
1335 @r#"failed to parse input in the "friendly" duration format: parsed value '3600s', but unparsed input "ago" remains (expected no unparsed input)"#,
1336 );
1337insta::assert_snapshot!(
1338 p("1 hour 1 minuteago"),
1339 @r#"failed to parse input in the "friendly" duration format: parsed value '3660s', but unparsed input "ago" remains (expected no unparsed input)"#,
1340 );
1341insta::assert_snapshot!(
1342 p("+1 hour 1 minute ago"),
1343 @r#"failed to parse input in the "friendly" duration format: expected to find either a prefix sign (+/-) or a suffix sign (`ago`), but found both"#,
1344 );
1345insta::assert_snapshot!(
1346 p("-1 hour 1 minute ago"),
1347 @r#"failed to parse input in the "friendly" duration format: expected to find either a prefix sign (+/-) or a suffix sign (`ago`), but found both"#,
1348 );
1349 }
13501351#[test]
1352fn err_unsigned_duration_overflow_fraction() {
1353let p = |s: &str| {
1354let dur = SpanParser::new().parse_unsigned_duration(s).unwrap();
1355crate::fmt::temporal::SpanPrinter::new()
1356 .unsigned_duration_to_string(&dur)
1357 };
1358let pe = |s: &str| {
1359 SpanParser::new().parse_unsigned_duration(s).unwrap_err()
1360 };
13611362insta::assert_snapshot!(
1363// Unlike `Span`, this just overflows because it can't be parsed
1364 // as a 64-bit integer.
1365pe("18446744073709551616 micros"),
1366 @r#"failed to parse input in the "friendly" duration format: number too big to parse into 64-bit integer"#,
1367 );
1368// one fewer is okay
1369insta::assert_snapshot!(
1370 p("18446744073709551615 micros"),
1371 @"PT5124095576H1M49.551615S"
1372);
1373 }
13741375#[test]
1376fn err_unsigned_duration_fraction() {
1377let p = |s: &str| {
1378 SpanParser::new().parse_unsigned_duration(s).unwrap_err()
1379 };
13801381insta::assert_snapshot!(
1382 p("1.5 nanos"),
1383 @r#"failed to parse input in the "friendly" duration format: fractional nanoseconds are not supported"#,
1384 );
1385 }
13861387#[test]
1388fn err_unsigned_duration_hms() {
1389let p = |s: &str| {
1390 SpanParser::new().parse_unsigned_duration(s).unwrap_err()
1391 };
13921393insta::assert_snapshot!(
1394 p("05:"),
1395 @r#"failed to parse input in the "friendly" duration format: when parsing the `HH:MM:SS` format, expected to parse minute following hour"#,
1396 );
1397insta::assert_snapshot!(
1398 p("05:06"),
1399 @r#"failed to parse input in the "friendly" duration format: when parsing the `HH:MM:SS` format, expected to parse `:` following minute"#,
1400 );
1401insta::assert_snapshot!(
1402 p("05:06:"),
1403 @r#"failed to parse input in the "friendly" duration format: when parsing the `HH:MM:SS` format, expected to parse second following minute"#,
1404 );
1405insta::assert_snapshot!(
1406 p("2 hours, 05:06:07"),
1407 @r#"failed to parse input in the "friendly" duration format: found `HH:MM:SS` after unit hour, but `HH:MM:SS` can only appear after years, months, weeks or days"#,
1408 );
1409 }
1410}