Skip to main content

jiff/fmt/friendly/
printer.rs

1use jcore::constants as c;
2
3use crate::{
4    Error, SignedDuration, Span, Unit,
5    fmt::{
6        Write,
7        buffer::{ArrayBuffer, BorrowedBuffer},
8    },
9};
10
11const SECS_PER_HOUR: u64 = c::SECS_PER_HOUR as u64;
12const SECS_PER_MIN: u64 = c::SECS_PER_MIN as u64;
13const MINS_PER_HOUR: u64 = c::MINS_PER_HOUR as u64;
14const NANOS_PER_HOUR: u128 = c::NANOS_PER_HOUR as u128;
15const NANOS_PER_MIN: u128 = c::NANOS_PER_MIN as u128;
16const NANOS_PER_MILLI: u32 = c::NANOS_PER_MILLI_32 as u32;
17const NANOS_PER_MICRO: u32 = c::NANOS_PER_MICRO_32 as u32;
18
19/// Defines the maximum possible length (in bytes) of a `Span` printed in the
20/// friendly format.
21///
22/// The way I computed this length was by using settings that would produce the
23/// maximal amount of text and using a negative `Span` with each unit set to
24/// its minimum value:
25///
26/// ```ignore
27/// SpanPrinter::new()
28///     .padding(u8::MAX)
29///     .designator(friendly::Designator::Verbose)
30///     .spacing(friendly::Spacing::BetweenUnitsAndDesignators)
31///     .comma_after_designator(true);
32/// ```
33const MAX_SPAN_LEN: usize = 306;
34
35/// Defines the maximum possible length (in bytes) of a `SignedDuration`
36/// printed in the friendly format.
37///
38/// See `MAX_SPAN_LEN` for how this was computed. In this case,
39/// `SignedDuration::MIN` was used.
40const MAX_SIGNED_DURATION_LEN: usize = 194;
41
42/// Defines the maximum possible length (in bytes) of a `std::time::Duration`
43/// printed in the friendly format.
44///
45/// See `MAX_SPAN_LEN` for how this was computed. In this case,
46/// `std::time::Duration::MAX - std::time::Duration::from_secs(16)` was used
47/// to find the maximal length. This was a little tricky because the maximal
48/// unsigned duration has minute units equivalent to `0`, and is thus quite a
49/// bit shorter than the maximum possible length.
50///
51/// Note that this is shorter than `MAX_SIGNED_DURATION` because one cannot
52/// get a negative formatted duration from a `std::time::Duration`. So there's
53/// no way to get an ` ago` suffix (or a `-` prefix). It can still get a `+`
54/// prefix with `Direction::ForceSign` though, which is counted here.
55const MAX_UNSIGNED_DURATION_LEN: usize = 191;
56
57/// Configuration for [`SpanPrinter::designator`].
58///
59/// This controls which kinds of designators to use when formatting a
60/// "friendly" duration. Generally, this only provides one axis of control:
61/// the length of each designator.
62///
63/// # Example
64///
65/// ```
66/// use jiff::{fmt::friendly::{Designator, SpanPrinter}, ToSpan};
67///
68/// let span = 1.year().months(2);
69///
70/// let printer = SpanPrinter::new();
71/// assert_eq!(printer.span_to_string(&span), "1y 2mo");
72///
73/// let printer = SpanPrinter::new().designator(Designator::Short);
74/// assert_eq!(printer.span_to_string(&span), "1yr 2mos");
75///
76/// let printer = SpanPrinter::new().designator(Designator::Verbose);
77/// assert_eq!(printer.span_to_string(&span), "1year 2months");
78///
79/// let printer = SpanPrinter::new().designator(Designator::HumanTime);
80/// assert_eq!(printer.span_to_string(&span), "1y 2months");
81/// ```
82#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Designator {
}
#[automatically_derived]impl ::core::clone::Clone for Designator {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Designator { }Copy, #[automatically_derived]impl ::core::fmt::Debug for Designator {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Designator::Verbose => "Verbose",
                Designator::Short => "Short",
                Designator::Compact => "Compact",
                Designator::HumanTime => "HumanTime",
            })
    }
}Debug)]
83#[non_exhaustive]
84pub enum Designator {
85    /// This writes out the full word of each unit designation. For example,
86    /// `year`.
87    Verbose,
88    /// This writes out a short but not minimal label for each unit. For
89    /// example, `yr` for `year` and `yrs` for `years`.
90    Short,
91    /// This writes out the shortest possible label for each unit that is still
92    /// generally recognizable. For example, `y`. Note that in the compact
93    /// representation, and unlike the verbose and short representations, there
94    /// is no distinction between singular or plural.
95    Compact,
96    /// A special mode that uses designator labels that are known to be
97    /// compatible with the `humantime` crate.
98    ///
99    /// None of `Verbose`, `Short` or `Compact` are compatible with
100    /// `humantime`.
101    ///
102    /// `Compact` is, on its own, nearly compatible. When using `Compact`, all
103    /// designator labels are parsable by `humantime` except for months and
104    /// microseconds. For months, Jiff uses `mo` and `mos`, but `humantime`
105    /// only parses `months`, `month` and `M`. Jiff specifically doesn't
106    /// support `M` for months because of the confusability with minutes.
107    /// For microseconds, Jiff uses `µs` which `humantime` does not support
108    /// parsing.
109    ///
110    /// Most of the designator labels Jiff uses for `Short` aren't supported
111    /// by `humantime`. And even when they are, `humantime` is inconsistent.
112    /// For example, `humantime` supports `sec` and `secs`, but only `nsec`
113    /// and not `nsecs`.
114    ///
115    /// Finally, for `Verbose`, humantime supports spelling out some units
116    /// in their entirety (e.g., `seconds`) but not others (e.g., `nanoseconds`
117    /// is not supported by `humantime`).
118    ///
119    /// Therefore, this custom variant is provided so that designator labels
120    /// that are compatible with both Jiff and `humantime`, even when there
121    /// isn't a coherent concept otherwise connecting their style.
122    HumanTime,
123}
124
125/// Configuration for [`SpanPrinter::spacing`].
126///
127/// This controls how much or how little whitespace is inserted into a
128/// "friendly" formatted duration. Typically, one wants less whitespace when
129/// using short unit designators (i.e., `y` instead of `years`), and more
130/// whitespace when using longer unit designators.
131///
132/// # Example
133///
134/// ```
135/// use jiff::{
136///     fmt::friendly::{Designator, Spacing, SpanPrinter},
137///     ToSpan,
138/// };
139///
140/// let span = 1.year().months(2);
141///
142/// // The default tries to balance spacing with compact
143/// // unit designators.
144/// let printer = SpanPrinter::new();
145/// assert_eq!(printer.span_to_string(&span), "1y 2mo");
146///
147/// // But you can use slightly more descriptive
148/// // designators without being too verbose.
149/// let printer = SpanPrinter::new()
150///     .designator(Designator::Short);
151/// assert_eq!(printer.span_to_string(&span), "1yr 2mos");
152///
153/// // When spacing is removed, it usually looks nicer
154/// // to use compact unit designators.
155/// let printer = SpanPrinter::new()
156///     .spacing(Spacing::None)
157///     .designator(Designator::Compact);
158/// assert_eq!(printer.span_to_string(&span), "1y2mo");
159///
160/// // Conversely, when using more spacing, it usually
161/// // looks nicer to use verbose unit designators.
162/// let printer = SpanPrinter::new()
163///     .spacing(Spacing::BetweenUnitsAndDesignators)
164///     .designator(Designator::Verbose);
165/// assert_eq!(printer.span_to_string(&span), "1 year 2 months");
166/// ```
167#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Spacing {
}
#[automatically_derived]impl ::core::clone::Clone for Spacing {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Spacing { }Copy, #[automatically_derived]impl ::core::fmt::Debug for Spacing {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Spacing::None => "None",
                Spacing::BetweenUnits => "BetweenUnits",
                Spacing::BetweenUnitsAndDesignators =>
                    "BetweenUnitsAndDesignators",
            })
    }
}Debug)]
168#[non_exhaustive]
169pub enum Spacing {
170    /// Does not insert any ASCII whitespace.
171    ///
172    /// Except in the case that [`SpanPrinter::hours_minutes_seconds`] is
173    /// enabled and one is formatting a span with non-zero calendar units, then
174    /// an ASCII whitespace is inserted between the calendar and non-calendar
175    /// units even when `Spacing::None` is used.
176    None,
177    /// Inserts one ASCII whitespace between the unit designator and the next
178    /// unit value.
179    ///
180    /// For example, `1year 2months`.
181    BetweenUnits,
182    /// Inserts one ASCII whitespace between the unit value and the unit
183    /// designator, in addition to inserting one ASCII whitespace between the
184    /// unit designator and the next unit value.
185    ///
186    /// For example, `1 year 2 months`.
187    BetweenUnitsAndDesignators,
188}
189
190impl Spacing {
191    fn between_units(self) -> Option<u8> {
192        match self {
193            Spacing::None => None,
194            Spacing::BetweenUnits => Some(b' '),
195            Spacing::BetweenUnitsAndDesignators => Some(b' '),
196        }
197    }
198
199    fn between_units_and_designators(self) -> Option<u8> {
200        match self {
201            Spacing::None => None,
202            Spacing::BetweenUnits => None,
203            Spacing::BetweenUnitsAndDesignators => Some(b' '),
204        }
205    }
206}
207
208/// Configuration for [`SpanPrinter::direction`].
209///
210/// This controls how the sign, if at all, is included in the formatted
211/// duration.
212///
213/// When using the "hours-minutes-seconds" format, `Auto` and `Suffix` are
214/// both treated as equivalent to `Sign` when all calendar units (days and
215/// greater) are zero.
216///
217/// # Example
218///
219/// ```
220/// use jiff::{fmt::friendly::{Direction, SpanPrinter}, SignedDuration};
221///
222/// let duration = SignedDuration::from_secs(-1);
223///
224/// let printer = SpanPrinter::new();
225/// assert_eq!(printer.duration_to_string(&duration), "1s ago");
226///
227/// let printer = SpanPrinter::new().direction(Direction::Sign);
228/// assert_eq!(printer.duration_to_string(&duration), "-1s");
229/// ```
230#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Direction {
}
#[automatically_derived]impl ::core::clone::Clone for Direction {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Direction { }Copy, #[automatically_derived]impl ::core::fmt::Debug for Direction {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Direction::Auto => "Auto",
                Direction::Sign => "Sign",
                Direction::ForceSign => "ForceSign",
                Direction::Suffix => "Suffix",
            })
    }
}Debug)]
231#[non_exhaustive]
232pub enum Direction {
233    /// Sets the sign format based on other configuration options.
234    ///
235    /// When [`SpanPrinter::spacing`] is set to [`Spacing::None`], then
236    /// `Auto` is equivalent to `Sign`.
237    ///
238    /// When using the "hours-minutes-seconds" format, `Auto` is equivalent to
239    /// `Sign` when all calendar units (days and greater) are zero.
240    ///
241    /// Otherwise, `Auto` is equivalent to `Suffix`.
242    ///
243    /// This is the default used by [`SpanPrinter`].
244    Auto,
245    /// When set, a sign is only written when the span or duration is negative.
246    /// And when it is written, it is written as a prefix of the formatted
247    /// duration.
248    Sign,
249    /// A sign is always written, with `-` for negative spans and `+` for all
250    /// non-negative spans. The sign is always written as a prefix of the
251    /// formatted duration.
252    ForceSign,
253    /// When set, a sign is only written when the span or duration is negative.
254    /// And when it is written, it is written as a suffix via a trailing ` ago`
255    /// string.
256    Suffix,
257}
258
259impl Direction {
260    /// Returns the sign string to use (as either a prefix or a suffix) based
261    /// on the given parameters.
262    ///
263    /// This lets us do the case analysis for how to write the sign exactly
264    /// once.
265    fn sign(
266        self,
267        printer: &SpanPrinter,
268        has_calendar: bool,
269        signum: i8,
270    ) -> Option<DirectionSign> {
271        match self {
272            Direction::Auto => match printer.spacing {
273                Spacing::None => {
274                    if signum < 0 {
275                        Some(DirectionSign::Prefix(b'-'))
276                    } else {
277                        None
278                    }
279                }
280                Spacing::BetweenUnits
281                | Spacing::BetweenUnitsAndDesignators => {
282                    if signum < 0 {
283                        if printer.hms && !has_calendar {
284                            Some(DirectionSign::Prefix(b'-'))
285                        } else {
286                            Some(DirectionSign::Suffix)
287                        }
288                    } else {
289                        None
290                    }
291                }
292            },
293            Direction::Sign => {
294                if signum < 0 {
295                    Some(DirectionSign::Prefix(b'-'))
296                } else {
297                    None
298                }
299            }
300            Direction::ForceSign => {
301                Some(DirectionSign::Prefix(if signum < 0 {
302                    b'-'
303                } else {
304                    b'+'
305                }))
306            }
307            Direction::Suffix => {
308                if signum < 0 {
309                    Some(DirectionSign::Suffix)
310                } else {
311                    None
312                }
313            }
314        }
315    }
316}
317
318/// The sign to write and whether it should be a prefix or a suffix.
319#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DirectionSign {
}
#[automatically_derived]impl ::core::clone::Clone for DirectionSign {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<u8>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for DirectionSign { }Copy, #[automatically_derived]impl ::core::fmt::Debug for DirectionSign {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Prefix(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Prefix", &__self_0),
            Self::Suffix => ::core::fmt::Formatter::write_str(f, "Suffix"),
        }
    }
}Debug)]
320enum DirectionSign {
321    Prefix(u8),
322    Suffix,
323}
324
325/// Configuration for [`SpanPrinter::fractional`].
326///
327/// This controls what kind of fractional unit to use when printing a duration.
328/// The default, unless [`SpanPrinter::hours_minutes_seconds`] is enabled, is
329/// to not write any fractional numbers at all.
330///
331/// The fractional unit set refers to the smallest whole integer that can occur
332/// in a "friendly" formatted duration. If there are any non-zero units less
333/// than the fractional unit in the duration, then they are formatted as a
334/// fraction.
335///
336/// # Example
337///
338/// This example shows how to write the same duration with different
339/// fractional settings:
340///
341/// ```
342/// use jiff::{fmt::friendly::{FractionalUnit, SpanPrinter}, SignedDuration};
343///
344/// let duration = SignedDuration::from_secs(3663);
345///
346/// let printer = SpanPrinter::new()
347///     .fractional(Some(FractionalUnit::Hour));
348/// assert_eq!(printer.duration_to_string(&duration), "1.0175h");
349///
350/// let printer = SpanPrinter::new()
351///     .fractional(Some(FractionalUnit::Minute));
352/// assert_eq!(printer.duration_to_string(&duration), "1h 1.05m");
353///
354/// let printer = SpanPrinter::new()
355///     .fractional(Some(FractionalUnit::Second));
356/// assert_eq!(printer.duration_to_string(&duration), "1h 1m 3s");
357/// ```
358#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for FractionalUnit {
}
#[automatically_derived]impl ::core::clone::Clone for FractionalUnit {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for FractionalUnit { }Copy, #[automatically_derived]impl ::core::fmt::Debug for FractionalUnit {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "Hour Minute Second Millisecond Microsecond",
            match self {
                FractionalUnit::Hour => 0usize,
                FractionalUnit::Minute => 5usize,
                FractionalUnit::Second => 12usize,
                FractionalUnit::Millisecond => 19usize,
                FractionalUnit::Microsecond => 31usize,
            })
    }
}Debug)]
359#[non_exhaustive]
360pub enum FractionalUnit {
361    /// The smallest whole integer unit allowed is hours.
362    ///
363    /// **WARNING**: Since fractional units are limited to 9 decimal places,
364    /// using this setting could result in precision loss.
365    Hour,
366    /// The smallest whole integer unit allowed is minutes.
367    ///
368    /// **WARNING**: Since fractional units are limited to 9 decimal places,
369    /// using this setting could result in precision loss.
370    Minute,
371    /// The smallest whole integer unit allowed is seconds.
372    Second,
373    /// The smallest whole integer unit allowed is milliseconds.
374    Millisecond,
375    /// The smallest whole integer unit allowed is microseconds.
376    Microsecond,
377}
378
379impl From<FractionalUnit> for Unit {
380    fn from(u: FractionalUnit) -> Unit {
381        match u {
382            FractionalUnit::Hour => Unit::Hour,
383            FractionalUnit::Minute => Unit::Minute,
384            FractionalUnit::Second => Unit::Second,
385            FractionalUnit::Millisecond => Unit::Millisecond,
386            FractionalUnit::Microsecond => Unit::Microsecond,
387        }
388    }
389}
390
391/// A printer for Jiff's "friendly" duration format.
392///
393/// This printer provides a lot of different knobs for controlling how
394/// durations are formatted. It supports formatting both [`SignedDuration`]
395/// and [`Span`].
396///
397/// # Example: automatic use through `Display`
398///
399/// The default configuration of this printer is used for "alternate" display
400/// formatting for both [`SignedDuration`] and [`Span`]:
401///
402/// ```
403/// use jiff::{SignedDuration, ToSpan};
404///
405/// let span = 1.year().months(2).hours(15).seconds(30).nanoseconds(1);
406/// assert_eq!(format!("{span:#}"), "1y 2mo 15h 30s 1ns");
407///
408/// let sdur = SignedDuration::new(15 * 60 * 60 + 30, 1);
409/// assert_eq!(format!("{sdur:#}"), "15h 30s 1ns");
410/// ```
411///
412/// # Example: variety of formatting configurations
413///
414/// This example shows a few different ways of formatting the same `Span`:
415///
416/// ```
417/// use jiff::{
418///     fmt::friendly::{Designator, Spacing, SpanPrinter},
419///     ToSpan,
420/// };
421///
422/// let span = 1.year().months(2).hours(15).seconds(30).nanoseconds(1);
423///
424/// let printer = SpanPrinter::new();
425/// assert_eq!(
426///     printer.span_to_string(&span),
427///     "1y 2mo 15h 30s 1ns",
428/// );
429///
430/// let printer = SpanPrinter::new()
431///     .designator(Designator::Short);
432/// assert_eq!(
433///     printer.span_to_string(&span),
434///     "1yr 2mos 15hrs 30secs 1nsec",
435/// );
436///
437/// let printer = SpanPrinter::new()
438///     .spacing(Spacing::None)
439///     .designator(Designator::Compact);
440/// assert_eq!(
441///     printer.span_to_string(&span),
442///     "1y2mo15h30s1ns",
443/// );
444///
445/// let printer = SpanPrinter::new()
446///     .spacing(Spacing::BetweenUnitsAndDesignators)
447///     .comma_after_designator(true)
448///     .designator(Designator::Verbose);
449/// assert_eq!(
450///     printer.span_to_string(&span),
451///     "1 year, 2 months, 15 hours, 30 seconds, 1 nanosecond",
452/// );
453///
454/// let printer = SpanPrinter::new()
455///     .hours_minutes_seconds(true)
456///     .spacing(Spacing::BetweenUnitsAndDesignators)
457///     .comma_after_designator(true)
458///     .designator(Designator::Verbose);
459/// assert_eq!(
460///     printer.span_to_string(&span),
461///     "1 year, 2 months, 15:00:30.000000001",
462/// );
463/// ```
464///
465/// # Example: negative durations
466///
467/// By default, a negative duration will be represented with an ` ago` suffix:
468///
469/// ```
470/// use jiff::{fmt::friendly::SpanPrinter, ToSpan};
471///
472/// let span = -1.year().months(2).hours(15).seconds(30).nanoseconds(1);
473///
474/// let printer = SpanPrinter::new();
475/// assert_eq!(
476///     printer.span_to_string(&span),
477///     "1y 2mo 15h 30s 1ns ago",
478/// );
479/// ```
480///
481/// But one can also use a prefix `-` sign instead. Usually this works better
482/// without any spacing and compact designators:
483///
484/// ```
485/// use jiff::{fmt::friendly::{Designator, Spacing, SpanPrinter}, ToSpan};
486///
487/// let span = -1.year().months(2).hours(15).seconds(30).nanoseconds(1);
488///
489/// let printer = SpanPrinter::new()
490///     .spacing(Spacing::None)
491///     .designator(Designator::Compact);
492/// assert_eq!(
493///     printer.span_to_string(&span),
494///     "-1y2mo15h30s1ns",
495/// );
496/// ```
497#[derive(#[automatically_derived]impl ::core::clone::Clone for SpanPrinter {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        SpanPrinter {
            designators: ::core::clone::Clone::clone(&self.designators),
            spacing: ::core::clone::Clone::clone(&self.spacing),
            direction: ::core::clone::Clone::clone(&self.direction),
            fractional: ::core::clone::Clone::clone(&self.fractional),
            comma_after_designator: ::core::clone::Clone::clone(&self.comma_after_designator),
            hms: ::core::clone::Clone::clone(&self.hms),
            padding: ::core::clone::Clone::clone(&self.padding),
            precision: ::core::clone::Clone::clone(&self.precision),
            zero_unit: ::core::clone::Clone::clone(&self.zero_unit),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for SpanPrinter {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_fields_finish(f,
            "SpanPrinter designators spacing direction fractional comma_after_designator hms padding precision zero_unit",
            &[&self.designators, &self.spacing, &self.direction,
                        &self.fractional, &self.comma_after_designator, &self.hms,
                        &self.padding, &self.precision, &&self.zero_unit])
    }
}Debug)]
498pub struct SpanPrinter {
499    designators: &'static Designators,
500    spacing: Spacing,
501    direction: Direction,
502    fractional: Option<FractionalUnit>,
503    comma_after_designator: bool,
504    hms: bool,
505    padding: Option<u8>,
506    precision: Option<u8>,
507    zero_unit: Unit,
508}
509
510impl SpanPrinter {
511    /// Creates a new printer for the "friendly" duration format.
512    ///
513    /// The printer returned uses the default configuration. This is
514    /// identical to `SpanPrinter::default`, but it can be used in a `const`
515    /// context.
516    ///
517    /// # Example
518    ///
519    /// This example shows how to format a duration directly to a `Vec<u8>`.
520    ///
521    /// ```
522    /// use jiff::{fmt::friendly::SpanPrinter, ToSpan};
523    ///
524    /// static PRINTER: SpanPrinter = SpanPrinter::new();
525    ///
526    /// let span = 1.year().months(2);
527    /// let mut buf = vec![];
528    /// // Writing to a `Vec<u8>` never fails (aside from OOM).
529    /// PRINTER.print_span(&span, &mut buf).unwrap();
530    /// assert_eq!(buf, b"1y 2mo");
531    /// ```
532    #[inline]
533    pub const fn new() -> SpanPrinter {
534        SpanPrinter {
535            designators: Designators::new(Designator::Compact),
536            spacing: Spacing::BetweenUnits,
537            direction: Direction::Auto,
538            fractional: None,
539            comma_after_designator: false,
540            hms: false,
541            padding: None,
542            precision: None,
543            zero_unit: Unit::Second,
544        }
545    }
546
547    /// Configures the kind of unit designators to use.
548    ///
549    /// There are no specific advantages or disadvantages to the kind
550    /// of designator you pick other than aesthetic preference. Shorter
551    /// designators are also likely faster to parse and print.
552    ///
553    /// The default is [`Designator::Compact`], which uses things like `yr`
554    /// instead of `year` (verbose) or `y` (compact).
555    ///
556    /// # Example
557    ///
558    /// ```
559    /// use jiff::{
560    ///     fmt::friendly::{Designator, SpanPrinter},
561    ///     ToSpan,
562    /// };
563    ///
564    /// let span = 1.year().months(2);
565    ///
566    /// let printer = SpanPrinter::new();
567    /// assert_eq!(printer.span_to_string(&span), "1y 2mo");
568    ///
569    /// let printer = SpanPrinter::new().designator(Designator::Short);
570    /// assert_eq!(printer.span_to_string(&span), "1yr 2mos");
571    ///
572    /// let printer = SpanPrinter::new().designator(Designator::Verbose);
573    /// assert_eq!(printer.span_to_string(&span), "1year 2months");
574    /// ```
575    #[inline]
576    pub const fn designator(self, designator: Designator) -> SpanPrinter {
577        SpanPrinter { designators: Designators::new(designator), ..self }
578    }
579
580    /// Configures the spacing between the units and the designator labels.
581    ///
582    /// The default is [`Spacing::BetweenUnits`], which results in durations
583    /// like `1y 2mo`. `Spacing::None` would result in `1y2mo` and
584    /// `Spacing::BetweenUnitsAndDesignators` would result in `1 y 2 mo`.
585    ///
586    /// # Example
587    ///
588    /// ```
589    /// use jiff::{
590    ///     fmt::friendly::{Designator, Spacing, SpanPrinter},
591    ///     ToSpan,
592    /// };
593    ///
594    /// let span = 1.year().months(2);
595    ///
596    /// // The default tries to balance spacing with compact
597    /// // unit designators.
598    /// let printer = SpanPrinter::new();
599    /// assert_eq!(printer.span_to_string(&span), "1y 2mo");
600    ///
601    /// // But you can use slightly more descriptive
602    /// // designators without being too verbose.
603    /// let printer = SpanPrinter::new()
604    ///     .designator(Designator::Short);
605    /// assert_eq!(printer.span_to_string(&span), "1yr 2mos");
606    ///
607    /// // When spacing is removed, it usually looks nicer
608    /// // to use compact unit designators.
609    /// let printer = SpanPrinter::new()
610    ///     .spacing(Spacing::None)
611    ///     .designator(Designator::Compact);
612    /// assert_eq!(printer.span_to_string(&span), "1y2mo");
613    ///
614    /// // Conversely, when using more spacing, it usually
615    /// // looks nicer to use verbose unit designators.
616    /// let printer = SpanPrinter::new()
617    ///     .spacing(Spacing::BetweenUnitsAndDesignators)
618    ///     .designator(Designator::Verbose);
619    /// assert_eq!(printer.span_to_string(&span), "1 year 2 months");
620    /// ```
621    ///
622    /// # Example: `Spacing::None` can still result in whitespace
623    ///
624    /// In the case that [`SpanPrinter::hours_minutes_seconds`] is enabled
625    /// and one is formatting a span with non-zero calendar units, then an
626    /// ASCII whitespace is inserted between the calendar and non-calendar
627    /// units even when `Spacing::None` is used:
628    ///
629    /// ```
630    /// use jiff::{fmt::friendly::{Spacing, SpanPrinter}, ToSpan};
631    ///
632    /// let span = 1.year().months(2).hours(15);
633    ///
634    /// let printer = SpanPrinter::new()
635    ///     .spacing(Spacing::None)
636    ///     .hours_minutes_seconds(true);
637    /// assert_eq!(printer.span_to_string(&span), "1y2mo 15:00:00");
638    /// ```
639    #[inline]
640    pub const fn spacing(self, spacing: Spacing) -> SpanPrinter {
641        SpanPrinter { spacing, ..self }
642    }
643
644    /// Configures how and when the sign for the duration is written.
645    ///
646    /// The default is [`Direction::Auto`]. In most cases, this results in
647    /// writing the suffix ` ago` after printing the duration units when the
648    /// sign of the duration is negative. And when the sign is positive, there
649    /// is no suffix. However, this can vary based on other settings. For
650    /// example, when [`SpanPrinter::spacing`] is set to [`Spacing::None`],
651    /// then `Direction::Auto` is treated as if it were [`Direction::Sign`].
652    ///
653    /// # Example
654    ///
655    /// ```
656    /// use jiff::{fmt::friendly::{Direction, SpanPrinter}, SignedDuration};
657    ///
658    /// let duration = SignedDuration::from_secs(-1);
659    ///
660    /// let printer = SpanPrinter::new();
661    /// assert_eq!(printer.duration_to_string(&duration), "1s ago");
662    ///
663    /// let printer = SpanPrinter::new().direction(Direction::Sign);
664    /// assert_eq!(printer.duration_to_string(&duration), "-1s");
665    /// ```
666    #[inline]
667    pub const fn direction(self, direction: Direction) -> SpanPrinter {
668        SpanPrinter { direction, ..self }
669    }
670
671    /// Enable fractional formatting for the given unit.
672    ///
673    /// When [`SpanPrinter::hours_minutes_seconds`] is enabled, then this
674    /// setting is automatically set to [`FractionalUnit::Second`]. Otherwise,
675    /// it defaults to `None`, which means no fractions are ever written.
676    ///
677    /// # Example
678    ///
679    /// This example shows how to write the same duration with different
680    /// fractional settings:
681    ///
682    /// ```
683    /// use jiff::{fmt::friendly::{FractionalUnit, SpanPrinter}, SignedDuration};
684    ///
685    /// let duration = SignedDuration::from_secs(3663);
686    ///
687    /// let printer = SpanPrinter::new()
688    ///     .fractional(Some(FractionalUnit::Hour));
689    /// assert_eq!(printer.duration_to_string(&duration), "1.0175h");
690    ///
691    /// let printer = SpanPrinter::new()
692    ///     .fractional(Some(FractionalUnit::Minute));
693    /// assert_eq!(printer.duration_to_string(&duration), "1h 1.05m");
694    ///
695    /// let printer = SpanPrinter::new()
696    ///     .fractional(Some(FractionalUnit::Second));
697    /// assert_eq!(printer.duration_to_string(&duration), "1h 1m 3s");
698    /// ```
699    ///
700    /// # Example: precision loss
701    ///
702    /// Because the "friendly" format is limited to 9 decimal places, when
703    /// using `FractionalUnit::Hour` or `FractionalUnit::Minute`, it is
704    /// possible for precision loss to occur.
705    ///
706    /// ```
707    /// use jiff::{fmt::friendly::{FractionalUnit, SpanPrinter}, SignedDuration};
708    ///
709    /// // one nanosecond
710    /// let duration = SignedDuration::new(0, 1);
711    ///
712    /// let printer = SpanPrinter::new()
713    ///     .fractional(Some(FractionalUnit::Hour));
714    /// assert_eq!(printer.duration_to_string(&duration), "0h");
715    ///
716    /// let printer = SpanPrinter::new()
717    ///     .fractional(Some(FractionalUnit::Minute));
718    /// assert_eq!(printer.duration_to_string(&duration), "0m");
719    /// ```
720    #[inline]
721    pub const fn fractional(
722        self,
723        unit: Option<FractionalUnit>,
724    ) -> SpanPrinter {
725        SpanPrinter { fractional: unit, ..self }
726    }
727
728    /// When enabled, commas are written after unit designators.
729    ///
730    /// This is disabled by default.
731    ///
732    /// # Example
733    ///
734    /// ```
735    /// use jiff::{fmt::friendly::{Designator, Spacing, SpanPrinter}, ToSpan};
736    ///
737    /// static PRINTER: SpanPrinter = SpanPrinter::new()
738    ///     .designator(Designator::Verbose)
739    ///     .spacing(Spacing::BetweenUnitsAndDesignators)
740    ///     .comma_after_designator(true);
741    ///
742    /// let span = 5.years().months(3).milliseconds(123);
743    /// assert_eq!(
744    ///     PRINTER.span_to_string(&span),
745    ///     "5 years, 3 months, 123 milliseconds",
746    /// );
747    /// ```
748    #[inline]
749    pub const fn comma_after_designator(self, yes: bool) -> SpanPrinter {
750        SpanPrinter { comma_after_designator: yes, ..self }
751    }
752
753    /// Formats the span or duration into a `HH:MM:SS[.fffffffff]` format.
754    ///
755    /// When formatting a `Span` with non-zero calendar units (units of days
756    /// or greater), then the calendar units are formatted as typical with
757    /// their corresponding designators. For example, `1d 01:00:00`. Note
758    /// that when formatting a `SignedDuration`, calendar units are never used.
759    ///
760    /// When this is enabled, many of the other options are either ignored or
761    /// fixed to a specific setting:
762    ///
763    /// * Since this format does not use any unit designators for units of
764    /// hours or smaller, the [`SpanPrinter::designator`] setting is ignored
765    /// for hours or smaller. It is still used when formatting a `Span` with
766    /// non-zero calendar units.
767    /// * [`SpanPrinter::spacing`] setting is ignored for units of hours or
768    /// smaller.
769    /// * The [`SpanPrinter::fractional`] setting is forcefully set to
770    /// [`FractionalUnit::Second`]. It cannot be changed.
771    /// * The [`SpanPrinter::comma_after_designator`] setting is ignored for
772    /// units of hours or smaller.
773    /// * When the padding is not specified, it defaults to `2` for hours,
774    /// minutes and seconds and `0` for any calendar units present.
775    /// * The precision setting is respected as documented.
776    ///
777    /// This format is useful in contexts for interfacing with existing systems
778    /// that require this style of format, or if the `HH:MM:SS` is just in
779    /// general preferred.
780    ///
781    /// # Loss of fidelity
782    ///
783    /// When using this format with a `Span`, sub-second units are formatted
784    /// as a fractional second. This means that `1000 milliseconds` and
785    /// `1 second` format to precisely the same string. This is similar to the
786    /// loss of fidelity when using [`fmt::temporal`](crate::fmt::temporal)
787    /// to format spans in the ISO 8601 duration format.
788    ///
789    /// # Example
790    ///
791    /// This shows how to format a `Span` in `HH:MM:SS` format:
792    ///
793    /// ```
794    /// use jiff::{fmt::friendly::SpanPrinter, ToSpan};
795    ///
796    /// static PRINTER: SpanPrinter =
797    ///     SpanPrinter::new().hours_minutes_seconds(true);
798    ///
799    /// let span = 2.hours().minutes(59).seconds(15).milliseconds(123);
800    /// assert_eq!(PRINTER.span_to_string(&span), "02:59:15.123");
801    /// assert_eq!(PRINTER.span_to_string(&-span), "-02:59:15.123");
802    ///
803    /// // This shows what happens with calendar units.
804    /// let span = 15.days().hours(2).minutes(59).seconds(15).milliseconds(123);
805    /// assert_eq!(PRINTER.span_to_string(&span), "15d 02:59:15.123");
806    /// // Notice that because calendar units are specified and the sign
807    /// // setting is set to "auto" by default, it has switched to a suffix.
808    /// assert_eq!(PRINTER.span_to_string(&-span), "15d 02:59:15.123 ago");
809    /// ```
810    ///
811    /// And this shows the same, but with a [`SignedDuration`]:
812    ///
813    /// ```
814    /// use jiff::{fmt::friendly::SpanPrinter, SignedDuration};
815    ///
816    /// static PRINTER: SpanPrinter =
817    ///     SpanPrinter::new().hours_minutes_seconds(true);
818    ///
819    /// let duration = SignedDuration::new(
820    ///     2 * 60 * 60 + 59 * 60 + 15,
821    ///     123_000_000,
822    /// );
823    /// assert_eq!(PRINTER.duration_to_string(&duration), "02:59:15.123");
824    /// assert_eq!(PRINTER.duration_to_string(&-duration), "-02:59:15.123");
825    /// ```
826    ///
827    /// # Example: `Span` versus `SignedDuration`
828    ///
829    /// The main advantage of a `Span` is that, except for fractional
830    /// components, the unit values emitted correspond precisely to the values
831    /// in the `Span`. Where as for a `SignedDuration`, the units are always
832    /// computed from a single absolute duration in a way that is always
833    /// balanced:
834    ///
835    /// ```
836    /// use jiff::{fmt::friendly::SpanPrinter, SignedDuration, ToSpan};
837    ///
838    /// static PRINTER: SpanPrinter =
839    ///     SpanPrinter::new().hours_minutes_seconds(true);
840    ///
841    /// let span = 120.minutes();
842    /// assert_eq!(PRINTER.span_to_string(&span), "00:120:00");
843    ///
844    /// let duration = SignedDuration::from_mins(120);
845    /// assert_eq!(PRINTER.duration_to_string(&duration), "02:00:00");
846    /// ```
847    ///
848    /// Of course, a balanced duration is sometimes what you want. But `Span`
849    /// affords the flexibility of controlling precisely what the unit values
850    /// are.
851    #[inline]
852    pub const fn hours_minutes_seconds(self, yes: bool) -> SpanPrinter {
853        SpanPrinter { hms: yes, ..self }
854    }
855
856    /// The padding to use when writing unit values.
857    ///
858    /// If a unit value has fewer digits than specified here, it is padded to
859    /// the left with zeroes. (To control precision, i.e., padding to the right
860    /// when writing fractional values, use [`SpanPrinter::precision`].)
861    ///
862    /// By default, when writing in the hours-minutes-seconds format, a padding
863    /// of `2` is used for units of hours, minutes and seconds. Otherwise, a
864    /// padding of `0` is used.
865    ///
866    /// Padding is clamped to a maximum value of `20` (corresponding to the
867    /// number of digits in `u64::MAX`).
868    ///
869    /// # Example
870    ///
871    /// This shows some examples of configuring padding when writing in default
872    /// format with unit designators:
873    ///
874    /// ```
875    /// use jiff::{fmt::friendly::SpanPrinter, ToSpan};
876    ///
877    /// let printer = SpanPrinter::new();
878    /// assert_eq!(printer.span_to_string(&1.hour()), "1h");
879    /// let printer = SpanPrinter::new().padding(3);
880    /// assert_eq!(printer.span_to_string(&1.hour()), "001h");
881    /// ```
882    ///
883    /// And this shows some examples with the hours-minutes-seconds format.
884    /// Notice how padding is enabled by default.
885    ///
886    /// ```
887    /// use jiff::{fmt::friendly::SpanPrinter, ToSpan};
888    ///
889    /// let printer = SpanPrinter::new().hours_minutes_seconds(true);
890    /// assert_eq!(printer.span_to_string(&1.hour()), "01:00:00");
891    /// let printer = SpanPrinter::new().hours_minutes_seconds(true).padding(0);
892    /// assert_eq!(printer.span_to_string(&1.hour()), "1:0:0");
893    ///
894    /// // In this case, under the default configuration, the padding
895    /// // for calendar units is 0 but the padding for time units is 2.
896    /// let printer = SpanPrinter::new().hours_minutes_seconds(true);
897    /// assert_eq!(printer.span_to_string(&1.day().hours(1)), "1d 01:00:00");
898    /// ```
899    #[inline]
900    pub const fn padding(self, digits: u8) -> SpanPrinter {
901        SpanPrinter { padding: Some(digits), ..self }
902    }
903
904    /// The precision to use when writing fractional unit values.
905    ///
906    /// This setting has no effect if fractional formatting isn't enabled.
907    /// Fractional formatting is only enabled when [`SpanPrinter::fractional`]
908    /// is set or if [`SpanPrinter::hours_minutes_seconds`] are enabled.
909    /// Neither are enabled by default.
910    ///
911    /// A precision of `Some(0)` implies that truncation of any fractional
912    /// component always occurs.
913    ///
914    /// The default value is `None`, which means the precision is automatically
915    /// determined from the value. If no fractional component is needed, then
916    /// none will be printed.
917    ///
918    /// Precision is capped to a maximum value of `9` (corresponding to the
919    /// maximum precision supported by Jiff).
920    ///
921    /// # Example
922    ///
923    /// ```
924    /// use jiff::{fmt::friendly::{FractionalUnit, SpanPrinter}, ToSpan};
925    ///
926    /// // No effect, because fractions aren't enabled.
927    /// let printer = SpanPrinter::new().precision(Some(2));
928    /// assert_eq!(printer.span_to_string(&1.hour()), "1h");
929    ///
930    /// // Precision setting takes effect!
931    /// let printer = SpanPrinter::new()
932    ///     .precision(Some(2))
933    ///     .fractional(Some(FractionalUnit::Hour));
934    /// assert_eq!(printer.span_to_string(&1.hour()), "1.00h");
935    ///
936    /// // The HH:MM:SS format automatically enables fractional
937    /// // second values.
938    /// let printer = SpanPrinter::new()
939    ///     // Truncate to millisecond precision.
940    ///     .precision(Some(3))
941    ///     .hours_minutes_seconds(true);
942    /// let span = 1.second().milliseconds(1).microseconds(1).nanoseconds(1);
943    /// assert_eq!(printer.span_to_string(&span), "00:00:01.001");
944    ///
945    /// // Same as above, but with the designator or "expanded"
946    /// // format. This requires explicitly enabling fractional
947    /// // units.
948    /// let printer = SpanPrinter::new()
949    ///     // Truncate to millisecond precision.
950    ///     .precision(Some(3))
951    ///     .fractional(Some(FractionalUnit::Second));
952    /// let span = 1.second().milliseconds(1).microseconds(1).nanoseconds(1);
953    /// assert_eq!(printer.span_to_string(&span), "1.001s");
954    /// ```
955    #[inline]
956    pub const fn precision(self, precision: Option<u8>) -> SpanPrinter {
957        SpanPrinter { precision, ..self }
958    }
959
960    /// Sets the unit to use when printing a duration that is zero.
961    ///
962    /// When [`SpanPrinter::fractional`] is set, then this setting is ignored
963    /// and the zero unit corresponds to the fractional unit specified.
964    ///
965    /// This defaults to [`Unit::Second`].
966    ///
967    /// # Example
968    ///
969    /// ```
970    /// use jiff::{fmt::friendly::{FractionalUnit, SpanPrinter}, ToSpan, Unit};
971    ///
972    /// // The default just always uses seconds.
973    /// let printer = SpanPrinter::new();
974    /// assert_eq!(printer.span_to_string(&0.years()), "0s");
975    ///
976    /// // We can set our own unit.
977    /// let printer = SpanPrinter::new().zero_unit(Unit::Year);
978    /// assert_eq!(printer.span_to_string(&0.years()), "0y");
979    ///
980    /// // But it's overridden if fractional units are set.
981    /// let printer = SpanPrinter::new()
982    ///     .zero_unit(Unit::Year)
983    ///     .fractional(Some(FractionalUnit::Minute));
984    /// assert_eq!(printer.span_to_string(&0.years()), "0m");
985    ///
986    /// // One use case for this option is if you're rounding
987    /// // spans and want the zero unit to reflect the smallest
988    /// // unit you're using.
989    /// let printer = SpanPrinter::new().zero_unit(Unit::Minute);
990    /// let span = 5.hours().minutes(30).seconds(59);
991    /// let rounded = span.round(Unit::Minute)?;
992    /// assert_eq!(printer.span_to_string(&rounded), "5h 31m");
993    ///
994    /// let span = 5.seconds();
995    /// let rounded = span.round(Unit::Minute)?;
996    /// assert_eq!(printer.span_to_string(&rounded), "0m");
997    ///
998    /// # Ok::<(), Box<dyn std::error::Error>>(())
999    /// ```
1000    ///
1001    /// The same applies for `SignedDuration`:
1002    ///
1003    /// ```
1004    /// use jiff::{fmt::friendly::SpanPrinter, SignedDuration, Unit};
1005    ///
1006    /// // The default just always uses seconds.
1007    /// let printer = SpanPrinter::new();
1008    /// assert_eq!(printer.duration_to_string(&SignedDuration::ZERO), "0s");
1009    ///
1010    /// // We can set our own unit.
1011    /// let printer = SpanPrinter::new().zero_unit(Unit::Minute);
1012    /// assert_eq!(printer.duration_to_string(&SignedDuration::ZERO), "0m");
1013    /// ```
1014    #[inline]
1015    pub const fn zero_unit(self, unit: Unit) -> SpanPrinter {
1016        SpanPrinter { zero_unit: unit, ..self }
1017    }
1018
1019    /// Format a `Span` into a string using the "friendly" format.
1020    ///
1021    /// This is a convenience routine for [`SpanPrinter::print_span`] with a
1022    /// `String`.
1023    ///
1024    /// # Example
1025    ///
1026    /// ```
1027    /// use jiff::{fmt::friendly::SpanPrinter, ToSpan};
1028    ///
1029    /// static PRINTER: SpanPrinter = SpanPrinter::new();
1030    ///
1031    /// let span = 3.years().months(5);
1032    /// assert_eq!(PRINTER.span_to_string(&span), "3y 5mo");
1033    /// ```
1034    #[cfg(any(test, feature = "alloc"))]
1035    pub fn span_to_string(&self, span: &Span) -> alloc::string::String {
1036        let mut buf = alloc::string::String::with_capacity(4);
1037        // OK because writing to `String` never fails.
1038        self.print_span(span, &mut buf).unwrap();
1039        buf
1040    }
1041
1042    /// Format a `SignedDuration` into a string using the "friendly" format.
1043    ///
1044    /// This balances the units of the duration up to at most hours
1045    /// automatically.
1046    ///
1047    /// This is a convenience routine for [`SpanPrinter::print_duration`] with
1048    /// a `String`.
1049    ///
1050    /// # Example
1051    ///
1052    /// ```
1053    /// use jiff::{fmt::friendly::{FractionalUnit, SpanPrinter}, SignedDuration};
1054    ///
1055    /// static PRINTER: SpanPrinter = SpanPrinter::new();
1056    ///
1057    /// let dur = SignedDuration::new(86_525, 123_000_789);
1058    /// assert_eq!(
1059    ///     PRINTER.duration_to_string(&dur),
1060    ///     "24h 2m 5s 123ms 789ns",
1061    /// );
1062    /// assert_eq!(
1063    ///     PRINTER.duration_to_string(&-dur),
1064    ///     "24h 2m 5s 123ms 789ns ago",
1065    /// );
1066    ///
1067    /// // Or, if you prefer fractional seconds:
1068    /// static PRINTER_FRACTIONAL: SpanPrinter = SpanPrinter::new()
1069    ///     .fractional(Some(FractionalUnit::Second));
1070    /// assert_eq!(
1071    ///     PRINTER_FRACTIONAL.duration_to_string(&-dur),
1072    ///     "24h 2m 5.123000789s ago",
1073    /// );
1074    /// ```
1075    #[cfg(any(test, feature = "alloc"))]
1076    pub fn duration_to_string(
1077        &self,
1078        duration: &SignedDuration,
1079    ) -> alloc::string::String {
1080        let mut buf = alloc::string::String::with_capacity(4);
1081        // OK because writing to `String` never fails.
1082        self.print_duration(duration, &mut buf).unwrap();
1083        buf
1084    }
1085
1086    /// Format a `std::time::Duration` into a string using the "friendly"
1087    /// format.
1088    ///
1089    /// This balances the units of the duration up to at most hours
1090    /// automatically.
1091    ///
1092    /// This is a convenience routine for
1093    /// [`SpanPrinter::print_unsigned_duration`] with a `String`.
1094    ///
1095    /// # Example
1096    ///
1097    /// ```
1098    /// use std::time::Duration;
1099    ///
1100    /// use jiff::fmt::friendly::{FractionalUnit, SpanPrinter};
1101    ///
1102    /// static PRINTER: SpanPrinter = SpanPrinter::new();
1103    ///
1104    /// let dur = Duration::new(86_525, 123_000_789);
1105    /// assert_eq!(
1106    ///     PRINTER.unsigned_duration_to_string(&dur),
1107    ///     "24h 2m 5s 123ms 789ns",
1108    /// );
1109    ///
1110    /// // Or, if you prefer fractional seconds:
1111    /// static PRINTER_FRACTIONAL: SpanPrinter = SpanPrinter::new()
1112    ///     .fractional(Some(FractionalUnit::Second));
1113    /// assert_eq!(
1114    ///     PRINTER_FRACTIONAL.unsigned_duration_to_string(&dur),
1115    ///     "24h 2m 5.123000789s",
1116    /// );
1117    /// ```
1118    #[cfg(any(test, feature = "alloc"))]
1119    pub fn unsigned_duration_to_string(
1120        &self,
1121        duration: &core::time::Duration,
1122    ) -> alloc::string::String {
1123        let mut buf = alloc::string::String::with_capacity(4);
1124        // OK because writing to `String` never fails.
1125        self.print_unsigned_duration(duration, &mut buf).unwrap();
1126        buf
1127    }
1128
1129    /// Print a `Span` to the given writer using the "friendly" format.
1130    ///
1131    /// # Errors
1132    ///
1133    /// This only returns an error when writing to the given [`Write`]
1134    /// implementation would fail. Some such implementations, like for `String`
1135    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
1136    /// cases, it would be appropriate to call `unwrap()` on the result.
1137    ///
1138    /// # Example
1139    ///
1140    /// ```
1141    /// use jiff::{fmt::friendly::SpanPrinter, ToSpan};
1142    ///
1143    /// static PRINTER: SpanPrinter = SpanPrinter::new();
1144    ///
1145    /// let span = 3.years().months(5);
1146    ///
1147    /// let mut buf = String::new();
1148    /// // Printing to a `String` can never fail.
1149    /// PRINTER.print_span(&span, &mut buf).unwrap();
1150    /// assert_eq!(buf, "3y 5mo");
1151    /// ```
1152    pub fn print_span<W: Write>(
1153        &self,
1154        span: &Span,
1155        mut wtr: W,
1156    ) -> Result<(), Error> {
1157        let mut buf = ArrayBuffer::<MAX_SPAN_LEN>::default();
1158        let mut bbuf = buf.as_borrowed();
1159        if self.hms {
1160            self.print_span_hms(span, &mut bbuf);
1161        } else {
1162            self.print_span_designators(span, &mut bbuf);
1163        }
1164        wtr.write_str(bbuf.filled())
1165    }
1166
1167    /// Print a `SignedDuration` to the given writer using the "friendly"
1168    /// format.
1169    ///
1170    /// This balances the units of the duration up to at most hours
1171    /// automatically.
1172    ///
1173    /// # Errors
1174    ///
1175    /// This only returns an error when writing to the given [`Write`]
1176    /// implementation would fail. Some such implementations, like for `String`
1177    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
1178    /// cases, it would be appropriate to call `unwrap()` on the result.
1179    ///
1180    /// # Example
1181    ///
1182    /// ```
1183    /// use jiff::{fmt::friendly::SpanPrinter, SignedDuration};
1184    ///
1185    /// static PRINTER: SpanPrinter = SpanPrinter::new();
1186    ///
1187    /// let dur = SignedDuration::new(86_525, 123_000_789);
1188    ///
1189    /// let mut buf = String::new();
1190    /// // Printing to a `String` can never fail.
1191    /// PRINTER.print_duration(&dur, &mut buf).unwrap();
1192    /// assert_eq!(buf, "24h 2m 5s 123ms 789ns");
1193    ///
1194    /// // Negative durations are supported.
1195    /// buf.clear();
1196    /// PRINTER.print_duration(&-dur, &mut buf).unwrap();
1197    /// assert_eq!(buf, "24h 2m 5s 123ms 789ns ago");
1198    /// ```
1199    pub fn print_duration<W: Write>(
1200        &self,
1201        duration: &SignedDuration,
1202        mut wtr: W,
1203    ) -> Result<(), Error> {
1204        let mut buf = ArrayBuffer::<MAX_SIGNED_DURATION_LEN>::default();
1205        let mut bbuf = buf.as_borrowed();
1206        if self.hms {
1207            self.print_signed_duration_hms(duration, &mut bbuf);
1208        } else {
1209            self.print_signed_duration_designators(duration, &mut bbuf);
1210        }
1211        wtr.write_str(bbuf.filled())
1212    }
1213
1214    /// Print a `std::time::Duration` to the given writer using the "friendly"
1215    /// format.
1216    ///
1217    /// This balances the units of the duration up to at most hours
1218    /// automatically.
1219    ///
1220    /// # Errors
1221    ///
1222    /// This only returns an error when writing to the given [`Write`]
1223    /// implementation would fail. Some such implementations, like for `String`
1224    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
1225    /// cases, it would be appropriate to call `unwrap()` on the result.
1226    ///
1227    /// # Example
1228    ///
1229    /// ```
1230    /// use std::time::Duration;
1231    ///
1232    /// use jiff::fmt::friendly::SpanPrinter;
1233    ///
1234    /// static PRINTER: SpanPrinter = SpanPrinter::new();
1235    ///
1236    /// let dur = Duration::new(86_525, 123_000_789);
1237    ///
1238    /// let mut buf = String::new();
1239    /// // Printing to a `String` can never fail.
1240    /// PRINTER.print_unsigned_duration(&dur, &mut buf).unwrap();
1241    /// assert_eq!(buf, "24h 2m 5s 123ms 789ns");
1242    /// ```
1243    pub fn print_unsigned_duration<W: Write>(
1244        &self,
1245        duration: &core::time::Duration,
1246        mut wtr: W,
1247    ) -> Result<(), Error> {
1248        let mut buf = ArrayBuffer::<MAX_UNSIGNED_DURATION_LEN>::default();
1249        let mut bbuf = buf.as_borrowed();
1250        if self.hms {
1251            self.print_unsigned_duration_hms(duration, &mut bbuf);
1252        } else {
1253            self.print_unsigned_duration_designators(duration, &mut bbuf);
1254        }
1255        wtr.write_str(bbuf.filled())
1256    }
1257
1258    fn print_span_designators(
1259        &self,
1260        span: &Span,
1261        bbuf: &mut BorrowedBuffer<'_>,
1262    ) {
1263        let mut wtr = DesignatorWriter::new(self, bbuf, false, span.signum());
1264        wtr.maybe_write_prefix_sign();
1265        match self.fractional {
1266            None => {
1267                self.print_span_designators_non_fraction(span, &mut wtr);
1268            }
1269            Some(unit) => {
1270                self.print_span_designators_fractional(span, unit, &mut wtr);
1271            }
1272        }
1273        wtr.maybe_write_zero();
1274        wtr.maybe_write_suffix_sign();
1275    }
1276
1277    fn print_span_designators_non_fraction<'p, 'w, 'd>(
1278        &self,
1279        span: &Span,
1280        wtr: &mut DesignatorWriter<'p, 'w, 'd>,
1281    ) {
1282        let units = span.units();
1283
1284        if units.contains(Unit::Year) {
1285            wtr.write(Unit::Year, span.get_years_unsigned().into());
1286        }
1287        if units.contains(Unit::Month) {
1288            wtr.write(Unit::Month, span.get_months_unsigned().into());
1289        }
1290        if units.contains(Unit::Week) {
1291            wtr.write(Unit::Week, span.get_weeks_unsigned().into());
1292        }
1293        if units.contains(Unit::Day) {
1294            wtr.write(Unit::Day, span.get_days_unsigned().into());
1295        }
1296        if units.contains(Unit::Hour) {
1297            wtr.write(Unit::Hour, span.get_hours_unsigned().into());
1298        }
1299        if units.contains(Unit::Minute) {
1300            wtr.write(Unit::Minute, span.get_minutes_unsigned());
1301        }
1302        if units.contains(Unit::Second) {
1303            wtr.write(Unit::Second, span.get_seconds_unsigned());
1304        }
1305        if units.contains(Unit::Millisecond) {
1306            wtr.write(Unit::Millisecond, span.get_milliseconds_unsigned());
1307        }
1308        if units.contains(Unit::Microsecond) {
1309            wtr.write(Unit::Microsecond, span.get_microseconds_unsigned());
1310        }
1311        if units.contains(Unit::Nanosecond) {
1312            wtr.write(Unit::Nanosecond, span.get_nanoseconds_unsigned());
1313        }
1314    }
1315
1316    fn print_span_calendar_designators_non_fraction<'p, 'w, 'd>(
1317        &self,
1318        span: &Span,
1319        wtr: &mut DesignatorWriter<'p, 'w, 'd>,
1320    ) {
1321        let units = span.units();
1322
1323        if units.contains(Unit::Year) {
1324            wtr.write(Unit::Year, span.get_years_unsigned().into());
1325        }
1326        if units.contains(Unit::Month) {
1327            wtr.write(Unit::Month, span.get_months_unsigned().into());
1328        }
1329        if units.contains(Unit::Week) {
1330            wtr.write(Unit::Week, span.get_weeks_unsigned().into());
1331        }
1332        if units.contains(Unit::Day) {
1333            wtr.write(Unit::Day, span.get_days_unsigned().into());
1334        }
1335    }
1336
1337    #[inline(never)]
1338    fn print_span_designators_fractional<'p, 'w, 'd>(
1339        &self,
1340        span: &Span,
1341        unit: FractionalUnit,
1342        wtr: &mut DesignatorWriter<'p, 'w, 'd>,
1343    ) {
1344        // OK because the biggest FractionalUnit is Hour, and there is always
1345        // a Unit bigger than hour.
1346        let split_at = Unit::from(unit).next().unwrap();
1347        let non_fractional = span.without_lower(split_at);
1348        let fractional = span.only_lower(split_at);
1349        self.print_span_designators_non_fraction(&non_fractional, wtr);
1350        wtr.write_fractional_duration(
1351            unit,
1352            &fractional.to_invariant_duration().unsigned_abs(),
1353        );
1354    }
1355
1356    fn print_span_hms(&self, span: &Span, bbuf: &mut BorrowedBuffer<'_>) {
1357        let has_cal = !span.units().only_calendar().is_empty();
1358        let mut wtr =
1359            DesignatorWriter::new(self, bbuf, has_cal, span.signum());
1360        let span = span.abs();
1361
1362        wtr.maybe_write_prefix_sign();
1363        if has_cal {
1364            self.print_span_calendar_designators_non_fraction(&span, &mut wtr);
1365            wtr.finish_preceding();
1366            // When spacing is disabled, then `finish_preceding` won't write
1367            // any spaces. But this would result in, e.g., `1yr15:00:00`, which
1368            // is just totally wrong. So detect that case here and insert a
1369            // space forcefully.
1370            if #[allow(non_exhaustive_omitted_patterns)] match self.spacing {
    Spacing::None => true,
    _ => false,
}matches!(self.spacing, Spacing::None) {
1371                wtr.bbuf.write_ascii_char(b' ');
1372            }
1373        }
1374
1375        let padding = self.padding.unwrap_or(2);
1376        wtr.bbuf.write_int_pad(span.get_hours_unsigned(), b'0', padding);
1377        wtr.bbuf.write_ascii_char(b':');
1378        wtr.bbuf.write_int_pad(span.get_minutes_unsigned(), b'0', padding);
1379        wtr.bbuf.write_ascii_char(b':');
1380        // You'd think we could do better here from a code size
1381        // perspective. But when I tried to inline the logic to
1382        // get a `SignedDuration` from just sub-minute units,
1383        // code size actually increased. ¯\_(ツ)_/¯
1384        let fp = FractionalPrinter::from_span_seconds(
1385            &span.only_lower(Unit::Minute),
1386            padding,
1387            self.precision,
1388        );
1389        fp.print(wtr.bbuf);
1390        wtr.maybe_write_suffix_sign();
1391    }
1392
1393    fn print_signed_duration_designators(
1394        &self,
1395        dur: &SignedDuration,
1396        bbuf: &mut BorrowedBuffer<'_>,
1397    ) {
1398        let mut wtr = DesignatorWriter::new(self, bbuf, false, dur.signum());
1399        wtr.maybe_write_prefix_sign();
1400        self.print_duration_designators(&dur.unsigned_abs(), &mut wtr);
1401        wtr.maybe_write_zero();
1402        wtr.maybe_write_suffix_sign();
1403    }
1404
1405    fn print_unsigned_duration_designators(
1406        &self,
1407        dur: &core::time::Duration,
1408        bbuf: &mut BorrowedBuffer<'_>,
1409    ) {
1410        let mut wtr = DesignatorWriter::new(self, bbuf, false, 1);
1411        wtr.maybe_write_prefix_sign();
1412        self.print_duration_designators(dur, &mut wtr);
1413        wtr.maybe_write_zero();
1414    }
1415
1416    fn print_duration_designators(
1417        &self,
1418        dur: &core::time::Duration,
1419        wtr: &mut DesignatorWriter<'_, '_, '_>,
1420    ) {
1421        match self.fractional {
1422            None => {
1423                let mut secs = dur.as_secs();
1424                wtr.write(Unit::Hour, secs / SECS_PER_HOUR);
1425                secs %= MINS_PER_HOUR * SECS_PER_MIN;
1426                wtr.write(Unit::Minute, secs / SECS_PER_MIN);
1427                wtr.write(Unit::Second, secs % SECS_PER_MIN);
1428                let mut nanos = dur.subsec_nanos();
1429                wtr.write(Unit::Millisecond, (nanos / NANOS_PER_MILLI).into());
1430                nanos %= NANOS_PER_MILLI;
1431                wtr.write(Unit::Microsecond, (nanos / NANOS_PER_MICRO).into());
1432                wtr.write(Unit::Nanosecond, (nanos % NANOS_PER_MICRO).into());
1433            }
1434            Some(FractionalUnit::Hour) => {
1435                wtr.write_fractional_duration(FractionalUnit::Hour, &dur);
1436            }
1437            Some(FractionalUnit::Minute) => {
1438                let mut secs = dur.as_secs();
1439                wtr.write(Unit::Hour, secs / SECS_PER_HOUR);
1440                secs %= MINS_PER_HOUR * SECS_PER_MIN;
1441
1442                let leftovers =
1443                    core::time::Duration::new(secs, dur.subsec_nanos());
1444                wtr.write_fractional_duration(
1445                    FractionalUnit::Minute,
1446                    &leftovers,
1447                );
1448            }
1449            Some(FractionalUnit::Second) => {
1450                let mut secs = dur.as_secs();
1451                wtr.write(Unit::Hour, secs / SECS_PER_HOUR);
1452                secs %= MINS_PER_HOUR * SECS_PER_MIN;
1453                wtr.write(Unit::Minute, secs / SECS_PER_MIN);
1454                secs %= SECS_PER_MIN;
1455
1456                let leftovers =
1457                    core::time::Duration::new(secs, dur.subsec_nanos());
1458                wtr.write_fractional_duration(
1459                    FractionalUnit::Second,
1460                    &leftovers,
1461                );
1462            }
1463            Some(FractionalUnit::Millisecond) => {
1464                let mut secs = dur.as_secs();
1465                wtr.write(Unit::Hour, secs / SECS_PER_HOUR);
1466                secs %= MINS_PER_HOUR * SECS_PER_MIN;
1467                wtr.write(Unit::Minute, secs / SECS_PER_MIN);
1468                wtr.write(Unit::Second, secs % SECS_PER_MIN);
1469
1470                let leftovers =
1471                    core::time::Duration::new(0, dur.subsec_nanos());
1472                wtr.write_fractional_duration(
1473                    FractionalUnit::Millisecond,
1474                    &leftovers,
1475                );
1476            }
1477            Some(FractionalUnit::Microsecond) => {
1478                let mut secs = dur.as_secs();
1479                wtr.write(Unit::Hour, secs / SECS_PER_HOUR);
1480                secs %= MINS_PER_HOUR * SECS_PER_MIN;
1481                wtr.write(Unit::Minute, secs / SECS_PER_MIN);
1482                wtr.write(Unit::Second, secs % SECS_PER_MIN);
1483                let mut nanos = dur.subsec_nanos();
1484                wtr.write(Unit::Millisecond, (nanos / NANOS_PER_MILLI).into());
1485                nanos %= NANOS_PER_MILLI;
1486
1487                let leftovers = core::time::Duration::new(0, nanos);
1488                wtr.write_fractional_duration(
1489                    FractionalUnit::Microsecond,
1490                    &leftovers,
1491                );
1492            }
1493        }
1494    }
1495
1496    fn print_signed_duration_hms(
1497        &self,
1498        dur: &SignedDuration,
1499        bbuf: &mut BorrowedBuffer<'_>,
1500    ) {
1501        if dur.is_negative() {
1502            if !#[allow(non_exhaustive_omitted_patterns)] match self.direction {
    Direction::Suffix => true,
    _ => false,
}matches!(self.direction, Direction::Suffix) {
1503                bbuf.write_ascii_char(b'-');
1504            }
1505        } else if let Direction::ForceSign = self.direction {
1506            bbuf.write_ascii_char(b'+');
1507        }
1508        self.print_duration_hms(&dur.unsigned_abs(), bbuf);
1509        if dur.is_negative() {
1510            if #[allow(non_exhaustive_omitted_patterns)] match self.direction {
    Direction::Suffix => true,
    _ => false,
}matches!(self.direction, Direction::Suffix) {
1511                bbuf.write_str(" ago");
1512            }
1513        }
1514    }
1515
1516    fn print_unsigned_duration_hms(
1517        &self,
1518        dur: &core::time::Duration,
1519        bbuf: &mut BorrowedBuffer<'_>,
1520    ) {
1521        if let Direction::ForceSign = self.direction {
1522            bbuf.write_ascii_char(b'+');
1523        }
1524        self.print_duration_hms(dur, bbuf);
1525    }
1526
1527    fn print_duration_hms(
1528        &self,
1529        udur: &core::time::Duration,
1530        bbuf: &mut BorrowedBuffer<'_>,
1531    ) {
1532        // N.B. It should be technically correct to convert a `SignedDuration`
1533        // (or `core::time::Duration`) to `Span` (since this process balances)
1534        // and then format the `Span` as-is. But this doesn't work because the
1535        // range of a `SignedDuration` (and `core::time::Duration`) is much
1536        // bigger.
1537
1538        let padding = self.padding.unwrap_or(2);
1539
1540        let mut secs = udur.as_secs();
1541        // OK because guaranteed to be bigger than i64::MIN.
1542        let hours = secs / (MINS_PER_HOUR * SECS_PER_MIN);
1543        secs %= MINS_PER_HOUR * SECS_PER_MIN;
1544        // OK because guaranteed to be bigger than i64::MIN.
1545        let minutes = secs / SECS_PER_MIN;
1546        // OK because guaranteed to be bigger than i64::MIN.
1547        secs = secs % SECS_PER_MIN;
1548
1549        bbuf.write_int_pad(hours, b'0', padding);
1550        bbuf.write_ascii_char(b':');
1551        bbuf.write_int_pad(minutes, b'0', padding);
1552        bbuf.write_ascii_char(b':');
1553        let fp = FractionalPrinter::from_duration_seconds(
1554            // OK because -999_999_999 <= nanos <= 999_999_999 and secs < 60.
1555            &core::time::Duration::new(secs, udur.subsec_nanos()),
1556            padding,
1557            self.precision,
1558        );
1559        fp.print(bbuf);
1560    }
1561}
1562
1563impl Default for SpanPrinter {
1564    fn default() -> SpanPrinter {
1565        SpanPrinter::new()
1566    }
1567}
1568
1569/// A type that represents the designator choice.
1570///
1571/// Basically, whether we want verbose, short or compact designators. This in
1572/// turn permits lookups based on `Unit`, which makes writing generic code for
1573/// writing designators a bit nicer and still fast.
1574#[derive(#[automatically_derived]impl ::core::clone::Clone for Designators {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        Designators {
            singular: ::core::clone::Clone::clone(&self.singular),
            plural: ::core::clone::Clone::clone(&self.plural),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Designators {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "Designators singular plural", &self.singular, &&self.plural)
    }
}Debug)]
1575struct Designators {
1576    singular: [&'static str; 10],
1577    plural: [&'static str; 10],
1578}
1579
1580impl Designators {
1581    const VERBOSE_SINGULAR: [&'static str; 10] = [
1582        "nanosecond",
1583        "microsecond",
1584        "millisecond",
1585        "second",
1586        "minute",
1587        "hour",
1588        "day",
1589        "week",
1590        "month",
1591        "year",
1592    ];
1593    const VERBOSE_PLURAL: [&'static str; 10] = [
1594        "nanoseconds",
1595        "microseconds",
1596        "milliseconds",
1597        "seconds",
1598        "minutes",
1599        "hours",
1600        "days",
1601        "weeks",
1602        "months",
1603        "years",
1604    ];
1605
1606    const SHORT_SINGULAR: [&'static str; 10] =
1607        ["nsec", "µsec", "msec", "sec", "min", "hr", "day", "wk", "mo", "yr"];
1608    const SHORT_PLURAL: [&'static str; 10] = [
1609        "nsecs", "µsecs", "msecs", "secs", "mins", "hrs", "days", "wks",
1610        "mos", "yrs",
1611    ];
1612
1613    const COMPACT: [&'static str; 10] =
1614        ["ns", "µs", "ms", "s", "m", "h", "d", "w", "mo", "y"];
1615
1616    const HUMAN_TIME_SINGULAR: [&'static str; 10] =
1617        ["ns", "us", "ms", "s", "m", "h", "d", "w", "month", "y"];
1618    const HUMAN_TIME_PLURAL: [&'static str; 10] =
1619        ["ns", "us", "ms", "s", "m", "h", "d", "w", "months", "y"];
1620
1621    const fn new(config: Designator) -> &'static Designators {
1622        match config {
1623            Designator::Verbose => &Designators {
1624                singular: Designators::VERBOSE_SINGULAR,
1625                plural: Designators::VERBOSE_PLURAL,
1626            },
1627            Designator::Short => &Designators {
1628                singular: Designators::SHORT_SINGULAR,
1629                plural: Designators::SHORT_PLURAL,
1630            },
1631            Designator::Compact => &Designators {
1632                singular: Designators::COMPACT,
1633                plural: Designators::COMPACT,
1634            },
1635            Designator::HumanTime => &Designators {
1636                singular: Designators::HUMAN_TIME_SINGULAR,
1637                plural: Designators::HUMAN_TIME_PLURAL,
1638            },
1639        }
1640    }
1641
1642    fn designator(&self, unit: impl Into<Unit>, plural: bool) -> &'static str {
1643        let unit = unit.into();
1644        let index = unit as usize;
1645        if plural { self.plural[index] } else { self.singular[index] }
1646    }
1647}
1648
1649/// An abstraction for writing the "designator" variant of the friendly format.
1650///
1651/// This takes care of computing some initial state and keeping track of some
1652/// mutable state that influences printing. For example, whether to write a
1653/// delimiter or not (one should only come after a unit that has been written).
1654#[derive(#[automatically_derived]impl<'p, 'w, 'd> ::core::fmt::Debug for
    DesignatorWriter<'p, 'w, 'd> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_fields_finish(f,
            "DesignatorWriter printer bbuf sign padding precision written_non_zero_unit",
            &[&self.printer, &self.bbuf, &self.sign, &self.padding,
                        &self.precision, &&self.written_non_zero_unit])
    }
}Debug)]
1655struct DesignatorWriter<'p, 'w, 'd> {
1656    printer: &'p SpanPrinter,
1657    bbuf: &'w mut BorrowedBuffer<'d>,
1658    sign: Option<DirectionSign>,
1659    padding: u8,
1660    precision: Option<u8>,
1661    written_non_zero_unit: bool,
1662}
1663
1664impl<'p, 'w, 'd> DesignatorWriter<'p, 'w, 'd> {
1665    fn new(
1666        printer: &'p SpanPrinter,
1667        bbuf: &'w mut BorrowedBuffer<'d>,
1668        has_calendar: bool,
1669        signum: i8,
1670    ) -> DesignatorWriter<'p, 'w, 'd> {
1671        let sign = printer.direction.sign(printer, has_calendar, signum);
1672        DesignatorWriter {
1673            printer,
1674            bbuf,
1675            sign,
1676            padding: printer.padding.unwrap_or(0),
1677            precision: printer.precision,
1678            written_non_zero_unit: false,
1679        }
1680    }
1681
1682    fn maybe_write_prefix_sign(&mut self) {
1683        if let Some(DirectionSign::Prefix(sign)) = self.sign {
1684            self.bbuf.write_ascii_char(sign);
1685        }
1686    }
1687
1688    fn maybe_write_suffix_sign(&mut self) {
1689        if let Some(DirectionSign::Suffix) = self.sign {
1690            self.bbuf.write_str(" ago");
1691        }
1692    }
1693
1694    fn maybe_write_zero(&mut self) {
1695        #[cold]
1696        #[inline(never)]
1697        fn imp(wtr: &mut DesignatorWriter<'_, '_, '_>) {
1698            wtr.bbuf.write_int_pad(0u64, b'0', wtr.padding);
1699            if let Some(byte) =
1700                wtr.printer.spacing.between_units_and_designators()
1701            {
1702                wtr.bbuf.write_ascii_char(byte);
1703            }
1704            // If a fractional unit is set, then we should use that unit
1705            // specifically to express "zero."
1706            let unit = wtr
1707                .printer
1708                .fractional
1709                .map(Unit::from)
1710                .unwrap_or(wtr.printer.zero_unit);
1711            wtr.bbuf.write_str(wtr.printer.designators.designator(unit, true));
1712        }
1713
1714        if !self.written_non_zero_unit {
1715            imp(self);
1716        }
1717    }
1718
1719    #[inline(never)]
1720    fn write(&mut self, unit: Unit, value: u64) {
1721        if value == 0 {
1722            return;
1723        }
1724        self.finish_preceding();
1725        self.written_non_zero_unit = true;
1726        self.bbuf.write_int_pad0(value, self.padding);
1727        if let Some(byte) =
1728            self.printer.spacing.between_units_and_designators()
1729        {
1730            self.bbuf.write_ascii_char(byte);
1731        }
1732        self.bbuf
1733            .write_str(self.printer.designators.designator(unit, value != 1));
1734    }
1735
1736    fn write_fractional_duration(
1737        &mut self,
1738        unit: FractionalUnit,
1739        duration: &core::time::Duration,
1740    ) {
1741        let fp = FractionalPrinter::from_duration(
1742            duration,
1743            unit,
1744            self.padding,
1745            self.precision,
1746        );
1747        if !fp.must_write_digits() {
1748            return;
1749        }
1750        self.finish_preceding();
1751        self.written_non_zero_unit = true;
1752        fp.print(&mut *self.bbuf);
1753        if let Some(byte) =
1754            self.printer.spacing.between_units_and_designators()
1755        {
1756            self.bbuf.write_ascii_char(byte);
1757        }
1758        self.bbuf.write_str(
1759            self.printer.designators.designator(unit, fp.is_plural()),
1760        );
1761    }
1762
1763    fn finish_preceding(&mut self) {
1764        if self.written_non_zero_unit {
1765            if self.printer.comma_after_designator {
1766                self.bbuf.write_ascii_char(b',');
1767            }
1768            if let Some(byte) = self.printer.spacing.between_units() {
1769                self.bbuf.write_ascii_char(byte);
1770            }
1771        }
1772    }
1773}
1774
1775/// A printer for a fraction with an integer and fraction component.
1776///
1777/// This also includes the formatter for the integer component and the
1778/// formatter for the fractional component.
1779struct FractionalPrinter {
1780    integer: u64,
1781    fraction: u32,
1782    padding: u8,
1783    precision: Option<u8>,
1784}
1785
1786impl FractionalPrinter {
1787    /// Build a fractional printer for the `Span` given. This includes the `.`.
1788    ///
1789    /// Callers must ensure that all units greater than `FractionalUnit` are
1790    /// zero in the span given.
1791    ///
1792    /// Note that the printer returned only prints a fractional component
1793    /// if necessary. For example, if the fractional component is zero and
1794    /// precision is `None`, or if `precision` is `Some(0)`, then no fractional
1795    /// component will be emitted.
1796    fn from_span_seconds(
1797        span: &Span,
1798        padding: u8,
1799        precision: Option<u8>,
1800    ) -> FractionalPrinter {
1801        FractionalPrinter::from_duration_seconds(
1802            &span.to_invariant_duration().unsigned_abs(),
1803            padding,
1804            precision,
1805        )
1806    }
1807
1808    /// Like `from_span_seconds`, but for `SignedDuration`.
1809    fn from_duration_seconds(
1810        dur: &core::time::Duration,
1811        padding: u8,
1812        precision: Option<u8>,
1813    ) -> FractionalPrinter {
1814        let integer = dur.as_secs();
1815        let fraction = u32::from(dur.subsec_nanos());
1816        FractionalPrinter { integer, fraction, padding, precision }
1817    }
1818
1819    /// Like `from_duration_seconds`, but for any fractional unit.
1820    fn from_duration(
1821        dur: &core::time::Duration,
1822        unit: FractionalUnit,
1823        padding: u8,
1824        precision: Option<u8>,
1825    ) -> FractionalPrinter {
1826        match unit {
1827            FractionalUnit::Hour => {
1828                let integer = dur.as_secs() / SECS_PER_HOUR;
1829                let mut fraction = dur.as_nanos() % NANOS_PER_HOUR;
1830                // Drop precision since we're only allowed 9 decimal places.
1831                fraction /= u128::from(SECS_PER_HOUR);
1832                // OK because NANOS_PER_HOUR / SECS_PER_HOUR fits in a u32.
1833                let fraction = u32::try_from(fraction).unwrap();
1834                FractionalPrinter { integer, fraction, padding, precision }
1835            }
1836            FractionalUnit::Minute => {
1837                let integer = dur.as_secs() / SECS_PER_MIN;
1838                let mut fraction = dur.as_nanos() % NANOS_PER_MIN;
1839                // Drop precision since we're only allowed 9 decimal places.
1840                fraction /= u128::from(SECS_PER_MIN);
1841                // OK because NANOS_PER_MIN fits in an u32.
1842                let fraction = u32::try_from(fraction).unwrap();
1843                FractionalPrinter { integer, fraction, padding, precision }
1844            }
1845            FractionalUnit::Second => {
1846                let integer = dur.as_secs();
1847                let fraction = u32::from(dur.subsec_nanos());
1848                FractionalPrinter { integer, fraction, padding, precision }
1849            }
1850            FractionalUnit::Millisecond => {
1851                // Unwrap is OK, but this is subtle. For printing a
1852                // SignedDuration, as_millis() can never return anything
1853                // bigger than 1 second, because the duration given is reduced
1854                // in a balanced fashion before hitting this routine. But
1855                // for printing a Span, it can, since spans can be totally
1856                // unbalanced. But Spans have limits on their units such that
1857                // each will fit into an i64. So this is also okay in that case
1858                // too.
1859                let integer = u64::try_from(dur.as_millis()).unwrap();
1860                let fraction =
1861                    u32::from((dur.subsec_nanos() % NANOS_PER_MILLI) * 1_000);
1862                FractionalPrinter { integer, fraction, padding, precision }
1863            }
1864            FractionalUnit::Microsecond => {
1865                // Unwrap is OK, but this is subtle. For printing a
1866                // SignedDuration, as_millis() can never return anything
1867                // bigger than 1 second, because the duration given is reduced
1868                // in a balanced fashion before hitting this routine. But
1869                // for printing a Span, it can, since spans can be totally
1870                // unbalanced. But Spans have limits on their units such that
1871                // each will fit into an i64. So this is also okay in that case
1872                // too.
1873                let integer = u64::try_from(dur.as_micros()).unwrap();
1874                let fraction = u32::from(
1875                    (dur.subsec_nanos() % NANOS_PER_MICRO) * 1_000_000,
1876                );
1877                FractionalPrinter { integer, fraction, padding, precision }
1878            }
1879        }
1880    }
1881
1882    /// Returns true if both the integer and fractional component are zero.
1883    fn is_zero(&self) -> bool {
1884        self.integer == 0 && self.fraction == 0
1885    }
1886
1887    /// Returns true if this integer/fraction should be considered plural
1888    /// when choosing what designator to use.
1889    fn is_plural(&self) -> bool {
1890        self.integer != 1
1891            || (self.fraction != 0 && !self.has_zero_fixed_precision())
1892    }
1893
1894    /// Returns true if and only if this printer must write some kind of number
1895    /// when `print` is called.
1896    ///
1897    /// The only case where this returns `false` is when both the integer and
1898    /// fractional component are zero *and* the precision is fixed to a number
1899    /// greater than zero.
1900    fn must_write_digits(&self) -> bool {
1901        !self.is_zero() || self.has_non_zero_fixed_precision()
1902    }
1903
1904    /// Returns true if and only if at least one digit will be written for the
1905    /// given value.
1906    ///
1907    /// This is useful for callers that need to know whether to write
1908    /// a decimal separator, e.g., `.`, before the digits.
1909    fn will_write_digits(&self) -> bool {
1910        self.precision.map_or_else(|| self.fraction != 0, |p| p > 0)
1911    }
1912
1913    /// Returns true if and only if this formatter has an explicit non-zero
1914    /// precision setting.
1915    ///
1916    /// This is useful for determining whether something like `0.000` needs to
1917    /// be written in the case of a `precision=Some(3)` setting and a zero
1918    /// value.
1919    fn has_non_zero_fixed_precision(&self) -> bool {
1920        self.precision.map_or(false, |p| p > 0)
1921    }
1922
1923    /// Returns true if and only if this formatter has fixed zero precision.
1924    /// That is, no matter what is given as input, a fraction is never written.
1925    fn has_zero_fixed_precision(&self) -> bool {
1926        self.precision.map_or(false, |p| p == 0)
1927    }
1928
1929    /// Prints the integer and optional fractional component.
1930    ///
1931    /// This will always print the integer, even if it's zero. Therefore, if
1932    /// the caller wants to omit printing zero, the caller should do their own
1933    /// conditional logic.
1934    fn print(&self, bbuf: &mut BorrowedBuffer<'_>) {
1935        bbuf.write_int_pad(self.integer, b'0', self.padding);
1936        if self.will_write_digits() {
1937            bbuf.write_ascii_char(b'.');
1938            bbuf.write_fraction(self.precision, self.fraction);
1939        }
1940    }
1941}
1942
1943#[cfg(feature = "alloc")]
1944#[cfg(test)]
1945mod tests {
1946    use crate::ToSpan;
1947
1948    use super::*;
1949
1950    #[test]
1951    fn print_span_designator_default() {
1952        let printer = || SpanPrinter::new();
1953        let p = |span| printer().span_to_string(&span);
1954
1955        insta::assert_snapshot!(p(1.second()), @"1s");
1956        insta::assert_snapshot!(p(2.seconds()), @"2s");
1957        insta::assert_snapshot!(p(10.seconds()), @"10s");
1958        insta::assert_snapshot!(p(1.minute().seconds(40)), @"1m 40s");
1959
1960        insta::assert_snapshot!(p(1.minute()), @"1m");
1961        insta::assert_snapshot!(p(2.minutes()), @"2m");
1962        insta::assert_snapshot!(p(10.minutes()), @"10m");
1963        insta::assert_snapshot!(p(1.hour().minutes(40)), @"1h 40m");
1964
1965        insta::assert_snapshot!(p(1.hour()), @"1h");
1966        insta::assert_snapshot!(p(2.hours()), @"2h");
1967        insta::assert_snapshot!(p(10.hours()), @"10h");
1968        insta::assert_snapshot!(p(100.hours()), @"100h");
1969
1970        insta::assert_snapshot!(
1971            p(1.hour().minutes(1).seconds(1)),
1972            @"1h 1m 1s",
1973        );
1974        insta::assert_snapshot!(
1975            p(2.hours().minutes(2).seconds(2)),
1976            @"2h 2m 2s",
1977        );
1978        insta::assert_snapshot!(
1979            p(10.hours().minutes(10).seconds(10)),
1980            @"10h 10m 10s",
1981        );
1982        insta::assert_snapshot!(
1983            p(100.hours().minutes(100).seconds(100)),
1984            @"100h 100m 100s",
1985        );
1986
1987        insta::assert_snapshot!(p(-1.hour()), @"1h ago");
1988        insta::assert_snapshot!(p(-1.hour().seconds(30)), @"1h 30s ago");
1989
1990        insta::assert_snapshot!(
1991            p(1.second().milliseconds(2000)),
1992            @"1s 2000ms",
1993        );
1994    }
1995
1996    #[test]
1997    fn print_span_designator_verbose() {
1998        let printer = || SpanPrinter::new().designator(Designator::Verbose);
1999        let p = |span| printer().span_to_string(&span);
2000
2001        insta::assert_snapshot!(p(1.second()), @"1second");
2002        insta::assert_snapshot!(p(2.seconds()), @"2seconds");
2003        insta::assert_snapshot!(p(10.seconds()), @"10seconds");
2004        insta::assert_snapshot!(p(1.minute().seconds(40)), @"1minute 40seconds");
2005
2006        insta::assert_snapshot!(p(1.minute()), @"1minute");
2007        insta::assert_snapshot!(p(2.minutes()), @"2minutes");
2008        insta::assert_snapshot!(p(10.minutes()), @"10minutes");
2009        insta::assert_snapshot!(p(1.hour().minutes(40)), @"1hour 40minutes");
2010
2011        insta::assert_snapshot!(p(1.hour()), @"1hour");
2012        insta::assert_snapshot!(p(2.hours()), @"2hours");
2013        insta::assert_snapshot!(p(10.hours()), @"10hours");
2014        insta::assert_snapshot!(p(100.hours()), @"100hours");
2015
2016        insta::assert_snapshot!(
2017            p(1.hour().minutes(1).seconds(1)),
2018            @"1hour 1minute 1second",
2019        );
2020        insta::assert_snapshot!(
2021            p(2.hours().minutes(2).seconds(2)),
2022            @"2hours 2minutes 2seconds",
2023        );
2024        insta::assert_snapshot!(
2025            p(10.hours().minutes(10).seconds(10)),
2026            @"10hours 10minutes 10seconds",
2027        );
2028        insta::assert_snapshot!(
2029            p(100.hours().minutes(100).seconds(100)),
2030            @"100hours 100minutes 100seconds",
2031        );
2032
2033        insta::assert_snapshot!(p(-1.hour()), @"1hour ago");
2034        insta::assert_snapshot!(p(-1.hour().seconds(30)), @"1hour 30seconds ago");
2035    }
2036
2037    #[test]
2038    fn print_span_designator_short() {
2039        let printer = || SpanPrinter::new().designator(Designator::Short);
2040        let p = |span| printer().span_to_string(&span);
2041
2042        insta::assert_snapshot!(p(1.second()), @"1sec");
2043        insta::assert_snapshot!(p(2.seconds()), @"2secs");
2044        insta::assert_snapshot!(p(10.seconds()), @"10secs");
2045        insta::assert_snapshot!(p(1.minute().seconds(40)), @"1min 40secs");
2046
2047        insta::assert_snapshot!(p(1.minute()), @"1min");
2048        insta::assert_snapshot!(p(2.minutes()), @"2mins");
2049        insta::assert_snapshot!(p(10.minutes()), @"10mins");
2050        insta::assert_snapshot!(p(1.hour().minutes(40)), @"1hr 40mins");
2051
2052        insta::assert_snapshot!(p(1.hour()), @"1hr");
2053        insta::assert_snapshot!(p(2.hours()), @"2hrs");
2054        insta::assert_snapshot!(p(10.hours()), @"10hrs");
2055        insta::assert_snapshot!(p(100.hours()), @"100hrs");
2056
2057        insta::assert_snapshot!(
2058            p(1.hour().minutes(1).seconds(1)),
2059            @"1hr 1min 1sec",
2060        );
2061        insta::assert_snapshot!(
2062            p(2.hours().minutes(2).seconds(2)),
2063            @"2hrs 2mins 2secs",
2064        );
2065        insta::assert_snapshot!(
2066            p(10.hours().minutes(10).seconds(10)),
2067            @"10hrs 10mins 10secs",
2068        );
2069        insta::assert_snapshot!(
2070            p(100.hours().minutes(100).seconds(100)),
2071            @"100hrs 100mins 100secs",
2072        );
2073
2074        insta::assert_snapshot!(p(-1.hour()), @"1hr ago");
2075        insta::assert_snapshot!(p(-1.hour().seconds(30)), @"1hr 30secs ago");
2076    }
2077
2078    #[test]
2079    fn print_span_designator_compact() {
2080        let printer = || SpanPrinter::new().designator(Designator::Compact);
2081        let p = |span| printer().span_to_string(&span);
2082
2083        insta::assert_snapshot!(p(1.second()), @"1s");
2084        insta::assert_snapshot!(p(2.seconds()), @"2s");
2085        insta::assert_snapshot!(p(10.seconds()), @"10s");
2086        insta::assert_snapshot!(p(1.minute().seconds(40)), @"1m 40s");
2087
2088        insta::assert_snapshot!(p(1.minute()), @"1m");
2089        insta::assert_snapshot!(p(2.minutes()), @"2m");
2090        insta::assert_snapshot!(p(10.minutes()), @"10m");
2091        insta::assert_snapshot!(p(1.hour().minutes(40)), @"1h 40m");
2092
2093        insta::assert_snapshot!(p(1.hour()), @"1h");
2094        insta::assert_snapshot!(p(2.hours()), @"2h");
2095        insta::assert_snapshot!(p(10.hours()), @"10h");
2096        insta::assert_snapshot!(p(100.hours()), @"100h");
2097
2098        insta::assert_snapshot!(
2099            p(1.hour().minutes(1).seconds(1)),
2100            @"1h 1m 1s",
2101        );
2102        insta::assert_snapshot!(
2103            p(2.hours().minutes(2).seconds(2)),
2104            @"2h 2m 2s",
2105        );
2106        insta::assert_snapshot!(
2107            p(10.hours().minutes(10).seconds(10)),
2108            @"10h 10m 10s",
2109        );
2110        insta::assert_snapshot!(
2111            p(100.hours().minutes(100).seconds(100)),
2112            @"100h 100m 100s",
2113        );
2114
2115        insta::assert_snapshot!(p(-1.hour()), @"1h ago");
2116        insta::assert_snapshot!(p(-1.hour().seconds(30)), @"1h 30s ago");
2117    }
2118
2119    #[test]
2120    fn print_span_designator_direction_force() {
2121        let printer = || SpanPrinter::new().direction(Direction::ForceSign);
2122        let p = |span| printer().span_to_string(&span);
2123
2124        insta::assert_snapshot!(p(1.second()), @"+1s");
2125        insta::assert_snapshot!(p(2.seconds()), @"+2s");
2126        insta::assert_snapshot!(p(10.seconds()), @"+10s");
2127        insta::assert_snapshot!(p(1.minute().seconds(40)), @"+1m 40s");
2128
2129        insta::assert_snapshot!(p(1.minute()), @"+1m");
2130        insta::assert_snapshot!(p(2.minutes()), @"+2m");
2131        insta::assert_snapshot!(p(10.minutes()), @"+10m");
2132        insta::assert_snapshot!(p(1.hour().minutes(40)), @"+1h 40m");
2133
2134        insta::assert_snapshot!(p(1.hour()), @"+1h");
2135        insta::assert_snapshot!(p(2.hours()), @"+2h");
2136        insta::assert_snapshot!(p(10.hours()), @"+10h");
2137        insta::assert_snapshot!(p(100.hours()), @"+100h");
2138
2139        insta::assert_snapshot!(
2140            p(1.hour().minutes(1).seconds(1)),
2141            @"+1h 1m 1s",
2142        );
2143        insta::assert_snapshot!(
2144            p(2.hours().minutes(2).seconds(2)),
2145            @"+2h 2m 2s",
2146        );
2147        insta::assert_snapshot!(
2148            p(10.hours().minutes(10).seconds(10)),
2149            @"+10h 10m 10s",
2150        );
2151        insta::assert_snapshot!(
2152            p(100.hours().minutes(100).seconds(100)),
2153            @"+100h 100m 100s",
2154        );
2155
2156        insta::assert_snapshot!(p(-1.hour()), @"-1h");
2157        insta::assert_snapshot!(p(-1.hour().seconds(30)), @"-1h 30s");
2158    }
2159
2160    #[test]
2161    fn print_span_designator_padding() {
2162        let printer = || SpanPrinter::new().padding(2);
2163        let p = |span| printer().span_to_string(&span);
2164
2165        insta::assert_snapshot!(p(1.second()), @"01s");
2166        insta::assert_snapshot!(p(2.seconds()), @"02s");
2167        insta::assert_snapshot!(p(10.seconds()), @"10s");
2168        insta::assert_snapshot!(p(1.minute().seconds(40)), @"01m 40s");
2169
2170        insta::assert_snapshot!(p(1.minute()), @"01m");
2171        insta::assert_snapshot!(p(2.minutes()), @"02m");
2172        insta::assert_snapshot!(p(10.minutes()), @"10m");
2173        insta::assert_snapshot!(p(1.hour().minutes(40)), @"01h 40m");
2174
2175        insta::assert_snapshot!(p(1.hour()), @"01h");
2176        insta::assert_snapshot!(p(2.hours()), @"02h");
2177        insta::assert_snapshot!(p(10.hours()), @"10h");
2178        insta::assert_snapshot!(p(100.hours()), @"100h");
2179
2180        insta::assert_snapshot!(
2181            p(1.hour().minutes(1).seconds(1)),
2182            @"01h 01m 01s",
2183        );
2184        insta::assert_snapshot!(
2185            p(2.hours().minutes(2).seconds(2)),
2186            @"02h 02m 02s",
2187        );
2188        insta::assert_snapshot!(
2189            p(10.hours().minutes(10).seconds(10)),
2190            @"10h 10m 10s",
2191        );
2192        insta::assert_snapshot!(
2193            p(100.hours().minutes(100).seconds(100)),
2194            @"100h 100m 100s",
2195        );
2196
2197        insta::assert_snapshot!(p(-1.hour()), @"01h ago");
2198        insta::assert_snapshot!(p(-1.hour().seconds(30)), @"01h 30s ago");
2199    }
2200
2201    #[test]
2202    fn print_span_designator_spacing_none() {
2203        let printer = || SpanPrinter::new().spacing(Spacing::None);
2204        let p = |span| printer().span_to_string(&span);
2205
2206        insta::assert_snapshot!(p(1.second()), @"1s");
2207        insta::assert_snapshot!(p(2.seconds()), @"2s");
2208        insta::assert_snapshot!(p(10.seconds()), @"10s");
2209        insta::assert_snapshot!(p(1.minute().seconds(40)), @"1m40s");
2210
2211        insta::assert_snapshot!(p(1.minute()), @"1m");
2212        insta::assert_snapshot!(p(2.minutes()), @"2m");
2213        insta::assert_snapshot!(p(10.minutes()), @"10m");
2214        insta::assert_snapshot!(p(1.hour().minutes(40)), @"1h40m");
2215
2216        insta::assert_snapshot!(p(1.hour()), @"1h");
2217        insta::assert_snapshot!(p(2.hours()), @"2h");
2218        insta::assert_snapshot!(p(10.hours()), @"10h");
2219        insta::assert_snapshot!(p(100.hours()), @"100h");
2220
2221        insta::assert_snapshot!(
2222            p(1.hour().minutes(1).seconds(1)),
2223            @"1h1m1s",
2224        );
2225        insta::assert_snapshot!(
2226            p(2.hours().minutes(2).seconds(2)),
2227            @"2h2m2s",
2228        );
2229        insta::assert_snapshot!(
2230            p(10.hours().minutes(10).seconds(10)),
2231            @"10h10m10s",
2232        );
2233        insta::assert_snapshot!(
2234            p(100.hours().minutes(100).seconds(100)),
2235            @"100h100m100s",
2236        );
2237
2238        insta::assert_snapshot!(p(-1.hour()), @"-1h");
2239        insta::assert_snapshot!(p(-1.hour().seconds(30)), @"-1h30s");
2240    }
2241
2242    #[test]
2243    fn print_span_designator_spacing_more() {
2244        let printer =
2245            || SpanPrinter::new().spacing(Spacing::BetweenUnitsAndDesignators);
2246        let p = |span| printer().span_to_string(&span);
2247
2248        insta::assert_snapshot!(p(1.second()), @"1 s");
2249        insta::assert_snapshot!(p(2.seconds()), @"2 s");
2250        insta::assert_snapshot!(p(10.seconds()), @"10 s");
2251        insta::assert_snapshot!(p(1.minute().seconds(40)), @"1 m 40 s");
2252
2253        insta::assert_snapshot!(p(1.minute()), @"1 m");
2254        insta::assert_snapshot!(p(2.minutes()), @"2 m");
2255        insta::assert_snapshot!(p(10.minutes()), @"10 m");
2256        insta::assert_snapshot!(p(1.hour().minutes(40)), @"1 h 40 m");
2257
2258        insta::assert_snapshot!(p(1.hour()), @"1 h");
2259        insta::assert_snapshot!(p(2.hours()), @"2 h");
2260        insta::assert_snapshot!(p(10.hours()), @"10 h");
2261        insta::assert_snapshot!(p(100.hours()), @"100 h");
2262
2263        insta::assert_snapshot!(
2264            p(1.hour().minutes(1).seconds(1)),
2265            @"1 h 1 m 1 s",
2266        );
2267        insta::assert_snapshot!(
2268            p(2.hours().minutes(2).seconds(2)),
2269            @"2 h 2 m 2 s",
2270        );
2271        insta::assert_snapshot!(
2272            p(10.hours().minutes(10).seconds(10)),
2273            @"10 h 10 m 10 s",
2274        );
2275        insta::assert_snapshot!(
2276            p(100.hours().minutes(100).seconds(100)),
2277            @"100 h 100 m 100 s",
2278        );
2279
2280        insta::assert_snapshot!(p(-1.hour()), @"1 h ago");
2281        insta::assert_snapshot!(p(-1.hour().seconds(30)), @"1 h 30 s ago");
2282    }
2283
2284    #[test]
2285    fn print_span_designator_spacing_comma() {
2286        let printer = || {
2287            SpanPrinter::new()
2288                .comma_after_designator(true)
2289                .spacing(Spacing::BetweenUnitsAndDesignators)
2290        };
2291        let p = |span| printer().span_to_string(&span);
2292
2293        insta::assert_snapshot!(p(1.second()), @"1 s");
2294        insta::assert_snapshot!(p(2.seconds()), @"2 s");
2295        insta::assert_snapshot!(p(10.seconds()), @"10 s");
2296        insta::assert_snapshot!(p(1.minute().seconds(40)), @"1 m, 40 s");
2297
2298        insta::assert_snapshot!(p(1.minute()), @"1 m");
2299        insta::assert_snapshot!(p(2.minutes()), @"2 m");
2300        insta::assert_snapshot!(p(10.minutes()), @"10 m");
2301        insta::assert_snapshot!(p(1.hour().minutes(40)), @"1 h, 40 m");
2302
2303        insta::assert_snapshot!(p(1.hour()), @"1 h");
2304        insta::assert_snapshot!(p(2.hours()), @"2 h");
2305        insta::assert_snapshot!(p(10.hours()), @"10 h");
2306        insta::assert_snapshot!(p(100.hours()), @"100 h");
2307
2308        insta::assert_snapshot!(
2309            p(1.hour().minutes(1).seconds(1)),
2310            @"1 h, 1 m, 1 s",
2311        );
2312        insta::assert_snapshot!(
2313            p(2.hours().minutes(2).seconds(2)),
2314            @"2 h, 2 m, 2 s",
2315        );
2316        insta::assert_snapshot!(
2317            p(10.hours().minutes(10).seconds(10)),
2318            @"10 h, 10 m, 10 s",
2319        );
2320        insta::assert_snapshot!(
2321            p(100.hours().minutes(100).seconds(100)),
2322            @"100 h, 100 m, 100 s",
2323        );
2324
2325        insta::assert_snapshot!(p(-1.hour()), @"1 h ago");
2326        insta::assert_snapshot!(p(-1.hour().seconds(30)), @"1 h, 30 s ago");
2327    }
2328
2329    #[test]
2330    fn print_span_designator_fractional_hour() {
2331        let printer =
2332            || SpanPrinter::new().fractional(Some(FractionalUnit::Hour));
2333        let p = |span| printer().span_to_string(&span);
2334        let pp = |precision, span| {
2335            printer().precision(Some(precision)).span_to_string(&span)
2336        };
2337
2338        insta::assert_snapshot!(p(1.hour()), @"1h");
2339        insta::assert_snapshot!(pp(0, 1.hour()), @"1h");
2340        insta::assert_snapshot!(pp(1, 1.hour()), @"1.0h");
2341        insta::assert_snapshot!(pp(2, 1.hour()), @"1.00h");
2342
2343        insta::assert_snapshot!(p(1.hour().minutes(30)), @"1.5h");
2344        insta::assert_snapshot!(pp(0, 1.hour().minutes(30)), @"1h");
2345        insta::assert_snapshot!(pp(1, 1.hour().minutes(30)), @"1.5h");
2346        insta::assert_snapshot!(pp(2, 1.hour().minutes(30)), @"1.50h");
2347
2348        insta::assert_snapshot!(p(1.hour().minutes(3)), @"1.05h");
2349        insta::assert_snapshot!(p(1.hour().minutes(3).nanoseconds(1)), @"1.05h");
2350        insta::assert_snapshot!(p(1.second()), @"0.000277777h");
2351        // precision loss!
2352        insta::assert_snapshot!(p(1.second().nanoseconds(1)), @"0.000277777h");
2353        insta::assert_snapshot!(p(0.seconds()), @"0h");
2354        // precision loss!
2355        insta::assert_snapshot!(p(1.nanosecond()), @"0h");
2356    }
2357
2358    #[test]
2359    fn print_span_designator_fractional_minute() {
2360        let printer =
2361            || SpanPrinter::new().fractional(Some(FractionalUnit::Minute));
2362        let p = |span| printer().span_to_string(&span);
2363        let pp = |precision, span| {
2364            printer().precision(Some(precision)).span_to_string(&span)
2365        };
2366
2367        insta::assert_snapshot!(p(1.hour()), @"1h");
2368        insta::assert_snapshot!(p(1.hour().minutes(30)), @"1h 30m");
2369
2370        insta::assert_snapshot!(p(1.minute()), @"1m");
2371        insta::assert_snapshot!(pp(0, 1.minute()), @"1m");
2372        insta::assert_snapshot!(pp(1, 1.minute()), @"1.0m");
2373        insta::assert_snapshot!(pp(2, 1.minute()), @"1.00m");
2374
2375        insta::assert_snapshot!(p(1.minute().seconds(30)), @"1.5m");
2376        insta::assert_snapshot!(pp(0, 1.minute().seconds(30)), @"1m");
2377        insta::assert_snapshot!(pp(1, 1.minute().seconds(30)), @"1.5m");
2378        insta::assert_snapshot!(pp(2, 1.minute().seconds(30)), @"1.50m");
2379
2380        insta::assert_snapshot!(p(1.hour().nanoseconds(1)), @"1h");
2381        insta::assert_snapshot!(p(1.minute().seconds(3)), @"1.05m");
2382        insta::assert_snapshot!(p(1.minute().seconds(3).nanoseconds(1)), @"1.05m");
2383        insta::assert_snapshot!(p(1.second()), @"0.016666666m");
2384        // precision loss!
2385        insta::assert_snapshot!(p(1.second().nanoseconds(1)), @"0.016666666m");
2386        insta::assert_snapshot!(p(0.seconds()), @"0m");
2387        // precision loss!
2388        insta::assert_snapshot!(p(1.nanosecond()), @"0m");
2389    }
2390
2391    #[test]
2392    fn print_span_designator_fractional_second() {
2393        let printer =
2394            || SpanPrinter::new().fractional(Some(FractionalUnit::Second));
2395        let p = |span| printer().span_to_string(&span);
2396        let pp = |precision, span| {
2397            printer().precision(Some(precision)).span_to_string(&span)
2398        };
2399
2400        insta::assert_snapshot!(p(1.hour()), @"1h");
2401        insta::assert_snapshot!(p(1.hour().minutes(30)), @"1h 30m");
2402
2403        insta::assert_snapshot!(p(1.second()), @"1s");
2404        insta::assert_snapshot!(pp(0, 1.second()), @"1s");
2405        insta::assert_snapshot!(pp(1, 1.second()), @"1.0s");
2406        insta::assert_snapshot!(pp(2, 1.second()), @"1.00s");
2407
2408        insta::assert_snapshot!(p(1.second().milliseconds(500)), @"1.5s");
2409        insta::assert_snapshot!(pp(0, 1.second().milliseconds(500)), @"1s");
2410        insta::assert_snapshot!(pp(1, 1.second().milliseconds(500)), @"1.5s");
2411        insta::assert_snapshot!(pp(2, 1.second().milliseconds(500)), @"1.50s");
2412
2413        insta::assert_snapshot!(p(1.second().nanoseconds(1)), @"1.000000001s");
2414        insta::assert_snapshot!(p(1.nanosecond()), @"0.000000001s");
2415        insta::assert_snapshot!(p(0.seconds()), @"0s");
2416
2417        insta::assert_snapshot!(p(1.second().milliseconds(2000)), @"3s");
2418    }
2419
2420    #[test]
2421    fn print_span_designator_fractional_millisecond() {
2422        let printer = || {
2423            SpanPrinter::new().fractional(Some(FractionalUnit::Millisecond))
2424        };
2425        let p = |span| printer().span_to_string(&span);
2426        let pp = |precision, span| {
2427            printer().precision(Some(precision)).span_to_string(&span)
2428        };
2429
2430        insta::assert_snapshot!(p(1.hour()), @"1h");
2431        insta::assert_snapshot!(p(1.hour().minutes(30)), @"1h 30m");
2432        insta::assert_snapshot!(
2433            p(1.hour().minutes(30).seconds(10)),
2434            @"1h 30m 10s",
2435        );
2436
2437        insta::assert_snapshot!(p(1.second()), @"1s");
2438        insta::assert_snapshot!(pp(0, 1.second()), @"1s");
2439        insta::assert_snapshot!(pp(1, 1.second()), @"1s 0.0ms");
2440        insta::assert_snapshot!(pp(2, 1.second()), @"1s 0.00ms");
2441
2442        insta::assert_snapshot!(p(1.second().milliseconds(500)), @"1s 500ms");
2443        insta::assert_snapshot!(
2444            pp(0, 1.second().milliseconds(1).microseconds(500)),
2445            @"1s 1ms",
2446        );
2447        insta::assert_snapshot!(
2448            pp(1, 1.second().milliseconds(1).microseconds(500)),
2449            @"1s 1.5ms",
2450        );
2451        insta::assert_snapshot!(
2452            pp(2, 1.second().milliseconds(1).microseconds(500)),
2453            @"1s 1.50ms",
2454        );
2455
2456        insta::assert_snapshot!(p(1.millisecond().nanoseconds(1)), @"1.000001ms");
2457        insta::assert_snapshot!(p(1.nanosecond()), @"0.000001ms");
2458        insta::assert_snapshot!(p(0.seconds()), @"0ms");
2459    }
2460
2461    #[test]
2462    fn print_span_designator_fractional_microsecond() {
2463        let printer = || {
2464            SpanPrinter::new().fractional(Some(FractionalUnit::Microsecond))
2465        };
2466        let p = |span| printer().span_to_string(&span);
2467        let pp = |precision, span| {
2468            printer().precision(Some(precision)).span_to_string(&span)
2469        };
2470
2471        insta::assert_snapshot!(p(1.hour()), @"1h");
2472        insta::assert_snapshot!(p(1.hour().minutes(30)), @"1h 30m");
2473        insta::assert_snapshot!(
2474            p(1.hour().minutes(30).seconds(10)),
2475            @"1h 30m 10s",
2476        );
2477
2478        insta::assert_snapshot!(p(1.second()), @"1s");
2479        insta::assert_snapshot!(pp(0, 1.second()), @"1s");
2480        insta::assert_snapshot!(pp(1, 1.second()), @"1s 0.0µs");
2481        insta::assert_snapshot!(pp(2, 1.second()), @"1s 0.00µs");
2482
2483        insta::assert_snapshot!(p(1.second().milliseconds(500)), @"1s 500ms");
2484        insta::assert_snapshot!(
2485            pp(0, 1.second().milliseconds(1).microseconds(500)),
2486            @"1s 1ms 500µs",
2487        );
2488        insta::assert_snapshot!(
2489            pp(1, 1.second().milliseconds(1).microseconds(500)),
2490            @"1s 1ms 500.0µs",
2491        );
2492        insta::assert_snapshot!(
2493            pp(2, 1.second().milliseconds(1).microseconds(500)),
2494            @"1s 1ms 500.00µs",
2495        );
2496
2497        insta::assert_snapshot!(
2498            p(1.millisecond().nanoseconds(1)),
2499            @"1ms 0.001µs",
2500        );
2501        insta::assert_snapshot!(p(1.nanosecond()), @"0.001µs");
2502        insta::assert_snapshot!(p(0.second()), @"0µs");
2503    }
2504
2505    #[test]
2506    fn print_signed_duration_designator_default() {
2507        let printer = || SpanPrinter::new();
2508        let p = |secs| {
2509            printer().duration_to_string(&SignedDuration::from_secs(secs))
2510        };
2511
2512        insta::assert_snapshot!(p(1), @"1s");
2513        insta::assert_snapshot!(p(2), @"2s");
2514        insta::assert_snapshot!(p(10), @"10s");
2515        insta::assert_snapshot!(p(100), @"1m 40s");
2516
2517        insta::assert_snapshot!(p(1 * 60), @"1m");
2518        insta::assert_snapshot!(p(2 * 60), @"2m");
2519        insta::assert_snapshot!(p(10 * 60), @"10m");
2520        insta::assert_snapshot!(p(100 * 60), @"1h 40m");
2521
2522        insta::assert_snapshot!(p(1 * 60 * 60), @"1h");
2523        insta::assert_snapshot!(p(2 * 60 * 60), @"2h");
2524        insta::assert_snapshot!(p(10 * 60 * 60), @"10h");
2525        insta::assert_snapshot!(p(100 * 60 * 60), @"100h");
2526
2527        insta::assert_snapshot!(
2528            p(60 * 60 + 60 + 1),
2529            @"1h 1m 1s",
2530        );
2531        insta::assert_snapshot!(
2532            p(2 * 60 * 60 + 2 * 60 + 2),
2533            @"2h 2m 2s",
2534        );
2535        insta::assert_snapshot!(
2536            p(10 * 60 * 60 + 10 * 60 + 10),
2537            @"10h 10m 10s",
2538        );
2539        insta::assert_snapshot!(
2540            p(100 * 60 * 60 + 100 * 60 + 100),
2541            @"101h 41m 40s",
2542        );
2543
2544        insta::assert_snapshot!(p(-1 * 60 * 60), @"1h ago");
2545        insta::assert_snapshot!(p(-1 * 60 * 60 - 30), @"1h 30s ago");
2546    }
2547
2548    #[test]
2549    fn print_signed_duration_designator_verbose() {
2550        let printer = || SpanPrinter::new().designator(Designator::Verbose);
2551        let p = |secs| {
2552            printer().duration_to_string(&SignedDuration::from_secs(secs))
2553        };
2554
2555        insta::assert_snapshot!(p(1), @"1second");
2556        insta::assert_snapshot!(p(2), @"2seconds");
2557        insta::assert_snapshot!(p(10), @"10seconds");
2558        insta::assert_snapshot!(p(100), @"1minute 40seconds");
2559
2560        insta::assert_snapshot!(p(1 * 60), @"1minute");
2561        insta::assert_snapshot!(p(2 * 60), @"2minutes");
2562        insta::assert_snapshot!(p(10 * 60), @"10minutes");
2563        insta::assert_snapshot!(p(100 * 60), @"1hour 40minutes");
2564
2565        insta::assert_snapshot!(p(1 * 60 * 60), @"1hour");
2566        insta::assert_snapshot!(p(2 * 60 * 60), @"2hours");
2567        insta::assert_snapshot!(p(10 * 60 * 60), @"10hours");
2568        insta::assert_snapshot!(p(100 * 60 * 60), @"100hours");
2569
2570        insta::assert_snapshot!(
2571            p(60 * 60 + 60 + 1),
2572            @"1hour 1minute 1second",
2573        );
2574        insta::assert_snapshot!(
2575            p(2 * 60 * 60 + 2 * 60 + 2),
2576            @"2hours 2minutes 2seconds",
2577        );
2578        insta::assert_snapshot!(
2579            p(10 * 60 * 60 + 10 * 60 + 10),
2580            @"10hours 10minutes 10seconds",
2581        );
2582        insta::assert_snapshot!(
2583            p(100 * 60 * 60 + 100 * 60 + 100),
2584            @"101hours 41minutes 40seconds",
2585        );
2586
2587        insta::assert_snapshot!(p(-1 * 60 * 60), @"1hour ago");
2588        insta::assert_snapshot!(p(-1 * 60 * 60 - 30), @"1hour 30seconds ago");
2589    }
2590
2591    #[test]
2592    fn print_signed_duration_designator_short() {
2593        let printer = || SpanPrinter::new().designator(Designator::Short);
2594        let p = |secs| {
2595            printer().duration_to_string(&SignedDuration::from_secs(secs))
2596        };
2597
2598        insta::assert_snapshot!(p(1), @"1sec");
2599        insta::assert_snapshot!(p(2), @"2secs");
2600        insta::assert_snapshot!(p(10), @"10secs");
2601        insta::assert_snapshot!(p(100), @"1min 40secs");
2602
2603        insta::assert_snapshot!(p(1 * 60), @"1min");
2604        insta::assert_snapshot!(p(2 * 60), @"2mins");
2605        insta::assert_snapshot!(p(10 * 60), @"10mins");
2606        insta::assert_snapshot!(p(100 * 60), @"1hr 40mins");
2607
2608        insta::assert_snapshot!(p(1 * 60 * 60), @"1hr");
2609        insta::assert_snapshot!(p(2 * 60 * 60), @"2hrs");
2610        insta::assert_snapshot!(p(10 * 60 * 60), @"10hrs");
2611        insta::assert_snapshot!(p(100 * 60 * 60), @"100hrs");
2612
2613        insta::assert_snapshot!(
2614            p(60 * 60 + 60 + 1),
2615            @"1hr 1min 1sec",
2616        );
2617        insta::assert_snapshot!(
2618            p(2 * 60 * 60 + 2 * 60 + 2),
2619            @"2hrs 2mins 2secs",
2620        );
2621        insta::assert_snapshot!(
2622            p(10 * 60 * 60 + 10 * 60 + 10),
2623            @"10hrs 10mins 10secs",
2624        );
2625        insta::assert_snapshot!(
2626            p(100 * 60 * 60 + 100 * 60 + 100),
2627            @"101hrs 41mins 40secs",
2628        );
2629
2630        insta::assert_snapshot!(p(-1 * 60 * 60), @"1hr ago");
2631        insta::assert_snapshot!(p(-1 * 60 * 60 - 30), @"1hr 30secs ago");
2632    }
2633
2634    #[test]
2635    fn print_signed_duration_designator_compact() {
2636        let printer = || SpanPrinter::new().designator(Designator::Compact);
2637        let p = |secs| {
2638            printer().duration_to_string(&SignedDuration::from_secs(secs))
2639        };
2640
2641        insta::assert_snapshot!(p(1), @"1s");
2642        insta::assert_snapshot!(p(2), @"2s");
2643        insta::assert_snapshot!(p(10), @"10s");
2644        insta::assert_snapshot!(p(100), @"1m 40s");
2645
2646        insta::assert_snapshot!(p(1 * 60), @"1m");
2647        insta::assert_snapshot!(p(2 * 60), @"2m");
2648        insta::assert_snapshot!(p(10 * 60), @"10m");
2649        insta::assert_snapshot!(p(100 * 60), @"1h 40m");
2650
2651        insta::assert_snapshot!(p(1 * 60 * 60), @"1h");
2652        insta::assert_snapshot!(p(2 * 60 * 60), @"2h");
2653        insta::assert_snapshot!(p(10 * 60 * 60), @"10h");
2654        insta::assert_snapshot!(p(100 * 60 * 60), @"100h");
2655
2656        insta::assert_snapshot!(
2657            p(60 * 60 + 60 + 1),
2658            @"1h 1m 1s",
2659        );
2660        insta::assert_snapshot!(
2661            p(2 * 60 * 60 + 2 * 60 + 2),
2662            @"2h 2m 2s",
2663        );
2664        insta::assert_snapshot!(
2665            p(10 * 60 * 60 + 10 * 60 + 10),
2666            @"10h 10m 10s",
2667        );
2668        insta::assert_snapshot!(
2669            p(100 * 60 * 60 + 100 * 60 + 100),
2670            @"101h 41m 40s",
2671        );
2672
2673        insta::assert_snapshot!(p(-1 * 60 * 60), @"1h ago");
2674        insta::assert_snapshot!(p(-1 * 60 * 60 - 30), @"1h 30s ago");
2675    }
2676
2677    #[test]
2678    fn print_signed_duration_designator_direction_force() {
2679        let printer = || SpanPrinter::new().direction(Direction::ForceSign);
2680        let p = |secs| {
2681            printer().duration_to_string(&SignedDuration::from_secs(secs))
2682        };
2683
2684        insta::assert_snapshot!(p(1), @"+1s");
2685        insta::assert_snapshot!(p(2), @"+2s");
2686        insta::assert_snapshot!(p(10), @"+10s");
2687        insta::assert_snapshot!(p(100), @"+1m 40s");
2688
2689        insta::assert_snapshot!(p(1 * 60), @"+1m");
2690        insta::assert_snapshot!(p(2 * 60), @"+2m");
2691        insta::assert_snapshot!(p(10 * 60), @"+10m");
2692        insta::assert_snapshot!(p(100 * 60), @"+1h 40m");
2693
2694        insta::assert_snapshot!(p(1 * 60 * 60), @"+1h");
2695        insta::assert_snapshot!(p(2 * 60 * 60), @"+2h");
2696        insta::assert_snapshot!(p(10 * 60 * 60), @"+10h");
2697        insta::assert_snapshot!(p(100 * 60 * 60), @"+100h");
2698
2699        insta::assert_snapshot!(
2700            p(60 * 60 + 60 + 1),
2701            @"+1h 1m 1s",
2702        );
2703        insta::assert_snapshot!(
2704            p(2 * 60 * 60 + 2 * 60 + 2),
2705            @"+2h 2m 2s",
2706        );
2707        insta::assert_snapshot!(
2708            p(10 * 60 * 60 + 10 * 60 + 10),
2709            @"+10h 10m 10s",
2710        );
2711        insta::assert_snapshot!(
2712            p(100 * 60 * 60 + 100 * 60 + 100),
2713            @"+101h 41m 40s",
2714        );
2715
2716        insta::assert_snapshot!(p(-1 * 60 * 60), @"-1h");
2717        insta::assert_snapshot!(p(-1 * 60 * 60 - 30), @"-1h 30s");
2718    }
2719
2720    #[test]
2721    fn print_signed_duration_designator_padding() {
2722        let printer = || SpanPrinter::new().padding(2);
2723        let p = |secs| {
2724            printer().duration_to_string(&SignedDuration::from_secs(secs))
2725        };
2726
2727        insta::assert_snapshot!(p(1), @"01s");
2728        insta::assert_snapshot!(p(2), @"02s");
2729        insta::assert_snapshot!(p(10), @"10s");
2730        insta::assert_snapshot!(p(100), @"01m 40s");
2731
2732        insta::assert_snapshot!(p(1 * 60), @"01m");
2733        insta::assert_snapshot!(p(2 * 60), @"02m");
2734        insta::assert_snapshot!(p(10 * 60), @"10m");
2735        insta::assert_snapshot!(p(100 * 60), @"01h 40m");
2736
2737        insta::assert_snapshot!(p(1 * 60 * 60), @"01h");
2738        insta::assert_snapshot!(p(2 * 60 * 60), @"02h");
2739        insta::assert_snapshot!(p(10 * 60 * 60), @"10h");
2740        insta::assert_snapshot!(p(100 * 60 * 60), @"100h");
2741
2742        insta::assert_snapshot!(
2743            p(60 * 60 + 60 + 1),
2744            @"01h 01m 01s",
2745        );
2746        insta::assert_snapshot!(
2747            p(2 * 60 * 60 + 2 * 60 + 2),
2748            @"02h 02m 02s",
2749        );
2750        insta::assert_snapshot!(
2751            p(10 * 60 * 60 + 10 * 60 + 10),
2752            @"10h 10m 10s",
2753        );
2754        insta::assert_snapshot!(
2755            p(100 * 60 * 60 + 100 * 60 + 100),
2756            @"101h 41m 40s",
2757        );
2758
2759        insta::assert_snapshot!(p(-1 * 60 * 60), @"01h ago");
2760        insta::assert_snapshot!(p(-1 * 60 * 60 - 30), @"01h 30s ago");
2761    }
2762
2763    #[test]
2764    fn print_signed_duration_designator_spacing_none() {
2765        let printer = || SpanPrinter::new().spacing(Spacing::None);
2766        let p = |secs| {
2767            printer().duration_to_string(&SignedDuration::from_secs(secs))
2768        };
2769
2770        insta::assert_snapshot!(p(1), @"1s");
2771        insta::assert_snapshot!(p(2), @"2s");
2772        insta::assert_snapshot!(p(10), @"10s");
2773        insta::assert_snapshot!(p(100), @"1m40s");
2774
2775        insta::assert_snapshot!(p(1 * 60), @"1m");
2776        insta::assert_snapshot!(p(2 * 60), @"2m");
2777        insta::assert_snapshot!(p(10 * 60), @"10m");
2778        insta::assert_snapshot!(p(100 * 60), @"1h40m");
2779
2780        insta::assert_snapshot!(p(1 * 60 * 60), @"1h");
2781        insta::assert_snapshot!(p(2 * 60 * 60), @"2h");
2782        insta::assert_snapshot!(p(10 * 60 * 60), @"10h");
2783        insta::assert_snapshot!(p(100 * 60 * 60), @"100h");
2784
2785        insta::assert_snapshot!(
2786            p(60 * 60 + 60 + 1),
2787            @"1h1m1s",
2788        );
2789        insta::assert_snapshot!(
2790            p(2 * 60 * 60 + 2 * 60 + 2),
2791            @"2h2m2s",
2792        );
2793        insta::assert_snapshot!(
2794            p(10 * 60 * 60 + 10 * 60 + 10),
2795            @"10h10m10s",
2796        );
2797        insta::assert_snapshot!(
2798            p(100 * 60 * 60 + 100 * 60 + 100),
2799            @"101h41m40s",
2800        );
2801
2802        insta::assert_snapshot!(p(-1 * 60 * 60), @"-1h");
2803        insta::assert_snapshot!(p(-1 * 60 * 60 - 30), @"-1h30s");
2804    }
2805
2806    #[test]
2807    fn print_signed_duration_designator_spacing_more() {
2808        let printer =
2809            || SpanPrinter::new().spacing(Spacing::BetweenUnitsAndDesignators);
2810        let p = |secs| {
2811            printer().duration_to_string(&SignedDuration::from_secs(secs))
2812        };
2813
2814        insta::assert_snapshot!(p(1), @"1 s");
2815        insta::assert_snapshot!(p(2), @"2 s");
2816        insta::assert_snapshot!(p(10), @"10 s");
2817        insta::assert_snapshot!(p(100), @"1 m 40 s");
2818
2819        insta::assert_snapshot!(p(1 * 60), @"1 m");
2820        insta::assert_snapshot!(p(2 * 60), @"2 m");
2821        insta::assert_snapshot!(p(10 * 60), @"10 m");
2822        insta::assert_snapshot!(p(100 * 60), @"1 h 40 m");
2823
2824        insta::assert_snapshot!(p(1 * 60 * 60), @"1 h");
2825        insta::assert_snapshot!(p(2 * 60 * 60), @"2 h");
2826        insta::assert_snapshot!(p(10 * 60 * 60), @"10 h");
2827        insta::assert_snapshot!(p(100 * 60 * 60), @"100 h");
2828
2829        insta::assert_snapshot!(
2830            p(60 * 60 + 60 + 1),
2831            @"1 h 1 m 1 s",
2832        );
2833        insta::assert_snapshot!(
2834            p(2 * 60 * 60 + 2 * 60 + 2),
2835            @"2 h 2 m 2 s",
2836        );
2837        insta::assert_snapshot!(
2838            p(10 * 60 * 60 + 10 * 60 + 10),
2839            @"10 h 10 m 10 s",
2840        );
2841        insta::assert_snapshot!(
2842            p(100 * 60 * 60 + 100 * 60 + 100),
2843            @"101 h 41 m 40 s",
2844        );
2845
2846        insta::assert_snapshot!(p(-1 * 60 * 60), @"1 h ago");
2847        insta::assert_snapshot!(p(-1 * 60 * 60 - 30), @"1 h 30 s ago");
2848    }
2849
2850    #[test]
2851    fn print_signed_duration_designator_spacing_comma() {
2852        let printer = || {
2853            SpanPrinter::new()
2854                .comma_after_designator(true)
2855                .spacing(Spacing::BetweenUnitsAndDesignators)
2856        };
2857        let p = |secs| {
2858            printer().duration_to_string(&SignedDuration::from_secs(secs))
2859        };
2860
2861        insta::assert_snapshot!(p(1), @"1 s");
2862        insta::assert_snapshot!(p(2), @"2 s");
2863        insta::assert_snapshot!(p(10), @"10 s");
2864        insta::assert_snapshot!(p(100), @"1 m, 40 s");
2865
2866        insta::assert_snapshot!(p(1 * 60), @"1 m");
2867        insta::assert_snapshot!(p(2 * 60), @"2 m");
2868        insta::assert_snapshot!(p(10 * 60), @"10 m");
2869        insta::assert_snapshot!(p(100 * 60), @"1 h, 40 m");
2870
2871        insta::assert_snapshot!(p(1 * 60 * 60), @"1 h");
2872        insta::assert_snapshot!(p(2 * 60 * 60), @"2 h");
2873        insta::assert_snapshot!(p(10 * 60 * 60), @"10 h");
2874        insta::assert_snapshot!(p(100 * 60 * 60), @"100 h");
2875
2876        insta::assert_snapshot!(
2877            p(60 * 60 + 60 + 1),
2878            @"1 h, 1 m, 1 s",
2879        );
2880        insta::assert_snapshot!(
2881            p(2 * 60 * 60 + 2 * 60 + 2),
2882            @"2 h, 2 m, 2 s",
2883        );
2884        insta::assert_snapshot!(
2885            p(10 * 60 * 60 + 10 * 60 + 10),
2886            @"10 h, 10 m, 10 s",
2887        );
2888        insta::assert_snapshot!(
2889            p(100 * 60 * 60 + 100 * 60 + 100),
2890            @"101 h, 41 m, 40 s",
2891        );
2892
2893        insta::assert_snapshot!(p(-1 * 60 * 60), @"1 h ago");
2894        insta::assert_snapshot!(p(-1 * 60 * 60 - 30), @"1 h, 30 s ago");
2895    }
2896
2897    #[test]
2898    fn print_signed_duration_designator_fractional_hour() {
2899        let printer =
2900            || SpanPrinter::new().fractional(Some(FractionalUnit::Hour));
2901        let p = |secs, nanos| {
2902            printer().duration_to_string(&SignedDuration::new(secs, nanos))
2903        };
2904        let pp = |precision, secs, nanos| {
2905            printer()
2906                .precision(Some(precision))
2907                .duration_to_string(&SignedDuration::new(secs, nanos))
2908        };
2909
2910        insta::assert_snapshot!(p(1 * 60 * 60, 0), @"1h");
2911        insta::assert_snapshot!(pp(0, 1 * 60 * 60, 0), @"1h");
2912        insta::assert_snapshot!(pp(1, 1 * 60 * 60, 0), @"1.0h");
2913        insta::assert_snapshot!(pp(2, 1 * 60 * 60, 0), @"1.00h");
2914
2915        insta::assert_snapshot!(p(1 * 60 * 60 + 30 * 60, 0), @"1.5h");
2916        insta::assert_snapshot!(pp(0, 1 * 60 * 60 + 30 * 60, 0), @"1h");
2917        insta::assert_snapshot!(pp(1, 1 * 60 * 60 + 30 * 60, 0), @"1.5h");
2918        insta::assert_snapshot!(pp(2, 1 * 60 * 60 + 30 * 60, 0), @"1.50h");
2919
2920        insta::assert_snapshot!(p(1 * 60 * 60 + 3 * 60, 0), @"1.05h");
2921        insta::assert_snapshot!(p(1 * 60 * 60 + 3 * 60, 1), @"1.05h");
2922        insta::assert_snapshot!(p(1, 0), @"0.000277777h");
2923        // precision loss!
2924        insta::assert_snapshot!(p(1, 1), @"0.000277777h");
2925        insta::assert_snapshot!(p(0, 0), @"0h");
2926        // precision loss!
2927        insta::assert_snapshot!(p(0, 1), @"0h");
2928
2929        insta::assert_snapshot!(
2930            printer().duration_to_string(&SignedDuration::MIN),
2931            @"2562047788015215.502499999h ago",
2932        );
2933    }
2934
2935    #[test]
2936    fn print_signed_duration_designator_fractional_minute() {
2937        let printer =
2938            || SpanPrinter::new().fractional(Some(FractionalUnit::Minute));
2939        let p = |secs, nanos| {
2940            printer().duration_to_string(&SignedDuration::new(secs, nanos))
2941        };
2942        let pp = |precision, secs, nanos| {
2943            printer()
2944                .precision(Some(precision))
2945                .duration_to_string(&SignedDuration::new(secs, nanos))
2946        };
2947
2948        insta::assert_snapshot!(p(1 * 60 * 60, 0), @"1h");
2949        insta::assert_snapshot!(p(1 * 60 * 60 + 30 * 60, 0), @"1h 30m");
2950
2951        insta::assert_snapshot!(p(60, 0), @"1m");
2952        insta::assert_snapshot!(pp(0, 60, 0), @"1m");
2953        insta::assert_snapshot!(pp(1, 60, 0), @"1.0m");
2954        insta::assert_snapshot!(pp(2, 60, 0), @"1.00m");
2955
2956        insta::assert_snapshot!(p(90, 0), @"1.5m");
2957        insta::assert_snapshot!(pp(0, 90, 0), @"1m");
2958        insta::assert_snapshot!(pp(1, 90, 0), @"1.5m");
2959        insta::assert_snapshot!(pp(2, 90, 0), @"1.50m");
2960
2961        insta::assert_snapshot!(p(1 * 60 * 60, 1), @"1h");
2962        insta::assert_snapshot!(p(63, 0), @"1.05m");
2963        insta::assert_snapshot!(p(63, 1), @"1.05m");
2964        insta::assert_snapshot!(p(1, 0), @"0.016666666m");
2965        // precision loss!
2966        insta::assert_snapshot!(p(1, 1), @"0.016666666m");
2967        insta::assert_snapshot!(p(0, 0), @"0m");
2968        // precision loss!
2969        insta::assert_snapshot!(p(0, 1), @"0m");
2970
2971        insta::assert_snapshot!(
2972            printer().duration_to_string(&SignedDuration::MIN),
2973            @"2562047788015215h 30.149999999m ago",
2974        );
2975    }
2976
2977    #[test]
2978    fn print_signed_duration_designator_fractional_second() {
2979        let printer =
2980            || SpanPrinter::new().fractional(Some(FractionalUnit::Second));
2981        let p = |secs, nanos| {
2982            printer().duration_to_string(&SignedDuration::new(secs, nanos))
2983        };
2984        let pp = |precision, secs, nanos| {
2985            printer()
2986                .precision(Some(precision))
2987                .duration_to_string(&SignedDuration::new(secs, nanos))
2988        };
2989
2990        insta::assert_snapshot!(p(1 * 60 * 60, 0), @"1h");
2991        insta::assert_snapshot!(p(1 * 60 * 60 + 30 * 60, 0), @"1h 30m");
2992
2993        insta::assert_snapshot!(p(1, 0), @"1s");
2994        insta::assert_snapshot!(pp(0, 1, 0), @"1s");
2995        insta::assert_snapshot!(pp(1, 1, 0), @"1.0s");
2996        insta::assert_snapshot!(pp(2, 1, 0), @"1.00s");
2997
2998        insta::assert_snapshot!(p(1, 500_000_000), @"1.5s");
2999        insta::assert_snapshot!(pp(0, 1, 500_000_000), @"1s");
3000        insta::assert_snapshot!(pp(1, 1, 500_000_000), @"1.5s");
3001        insta::assert_snapshot!(pp(2, 1, 500_000_000), @"1.50s");
3002
3003        insta::assert_snapshot!(p(1, 1), @"1.000000001s");
3004        insta::assert_snapshot!(p(0, 1), @"0.000000001s");
3005        insta::assert_snapshot!(p(0, 0), @"0s");
3006
3007        insta::assert_snapshot!(
3008            printer().duration_to_string(&SignedDuration::MIN),
3009            @"2562047788015215h 30m 8.999999999s ago",
3010        );
3011    }
3012
3013    #[test]
3014    fn print_signed_duration_designator_fractional_millisecond() {
3015        let printer = || {
3016            SpanPrinter::new().fractional(Some(FractionalUnit::Millisecond))
3017        };
3018        let p = |secs, nanos| {
3019            printer().duration_to_string(&SignedDuration::new(secs, nanos))
3020        };
3021        let pp = |precision, secs, nanos| {
3022            printer()
3023                .precision(Some(precision))
3024                .duration_to_string(&SignedDuration::new(secs, nanos))
3025        };
3026
3027        insta::assert_snapshot!(p(1 * 60 * 60, 0), @"1h");
3028        insta::assert_snapshot!(p(1 * 60 * 60 + 30 * 60, 0), @"1h 30m");
3029        insta::assert_snapshot!(
3030            p(1 * 60 * 60 + 30 * 60 + 10, 0),
3031            @"1h 30m 10s",
3032        );
3033
3034        insta::assert_snapshot!(p(1, 0), @"1s");
3035        insta::assert_snapshot!(pp(0, 1, 0), @"1s");
3036        insta::assert_snapshot!(pp(1, 1, 0), @"1s 0.0ms");
3037        insta::assert_snapshot!(pp(2, 1, 0), @"1s 0.00ms");
3038
3039        insta::assert_snapshot!(p(1, 500_000_000), @"1s 500ms");
3040        insta::assert_snapshot!(pp(0, 1, 1_500_000), @"1s 1ms");
3041        insta::assert_snapshot!(pp(1, 1, 1_500_000), @"1s 1.5ms");
3042        insta::assert_snapshot!(pp(2, 1, 1_500_000), @"1s 1.50ms");
3043
3044        insta::assert_snapshot!(p(0, 1_000_001), @"1.000001ms");
3045        insta::assert_snapshot!(p(0, 0_000_001), @"0.000001ms");
3046        insta::assert_snapshot!(p(0, 0), @"0ms");
3047
3048        insta::assert_snapshot!(
3049            printer().duration_to_string(&SignedDuration::MIN),
3050            @"2562047788015215h 30m 8s 999.999999ms ago",
3051        );
3052    }
3053
3054    #[test]
3055    fn print_signed_duration_designator_fractional_microsecond() {
3056        let printer = || {
3057            SpanPrinter::new().fractional(Some(FractionalUnit::Microsecond))
3058        };
3059        let p = |secs, nanos| {
3060            printer().duration_to_string(&SignedDuration::new(secs, nanos))
3061        };
3062        let pp = |precision, secs, nanos| {
3063            printer()
3064                .precision(Some(precision))
3065                .duration_to_string(&SignedDuration::new(secs, nanos))
3066        };
3067
3068        insta::assert_snapshot!(p(1 * 60 * 60, 0), @"1h");
3069        insta::assert_snapshot!(p(1 * 60 * 60 + 30 * 60, 0), @"1h 30m");
3070        insta::assert_snapshot!(
3071            p(1 * 60 * 60 + 30 * 60 + 10, 0),
3072            @"1h 30m 10s",
3073        );
3074
3075        insta::assert_snapshot!(p(1, 0), @"1s");
3076        insta::assert_snapshot!(pp(0, 1, 0), @"1s");
3077        insta::assert_snapshot!(pp(1, 1, 0), @"1s 0.0µs");
3078        insta::assert_snapshot!(pp(2, 1, 0), @"1s 0.00µs");
3079
3080        insta::assert_snapshot!(p(1, 500_000_000), @"1s 500ms");
3081        insta::assert_snapshot!(pp(0, 1, 1_500_000), @"1s 1ms 500µs");
3082        insta::assert_snapshot!(pp(1, 1, 1_500_000), @"1s 1ms 500.0µs");
3083        insta::assert_snapshot!(pp(2, 1, 1_500_000), @"1s 1ms 500.00µs");
3084
3085        insta::assert_snapshot!(p(0, 1_000_001), @"1ms 0.001µs");
3086        insta::assert_snapshot!(p(0, 0_000_001), @"0.001µs");
3087        insta::assert_snapshot!(p(0, 0), @"0µs");
3088
3089        insta::assert_snapshot!(
3090            printer().duration_to_string(&SignedDuration::MIN),
3091            @"2562047788015215h 30m 8s 999ms 999.999µs ago",
3092        );
3093    }
3094
3095    #[test]
3096    fn print_unsigned_duration_designator_default() {
3097        let printer = || SpanPrinter::new();
3098        let p = |secs| {
3099            printer().unsigned_duration_to_string(
3100                &core::time::Duration::from_secs(secs),
3101            )
3102        };
3103
3104        insta::assert_snapshot!(p(1), @"1s");
3105        insta::assert_snapshot!(p(2), @"2s");
3106        insta::assert_snapshot!(p(10), @"10s");
3107        insta::assert_snapshot!(p(100), @"1m 40s");
3108
3109        insta::assert_snapshot!(p(1 * 60), @"1m");
3110        insta::assert_snapshot!(p(2 * 60), @"2m");
3111        insta::assert_snapshot!(p(10 * 60), @"10m");
3112        insta::assert_snapshot!(p(100 * 60), @"1h 40m");
3113
3114        insta::assert_snapshot!(p(1 * 60 * 60), @"1h");
3115        insta::assert_snapshot!(p(2 * 60 * 60), @"2h");
3116        insta::assert_snapshot!(p(10 * 60 * 60), @"10h");
3117        insta::assert_snapshot!(p(100 * 60 * 60), @"100h");
3118
3119        insta::assert_snapshot!(
3120            p(60 * 60 + 60 + 1),
3121            @"1h 1m 1s",
3122        );
3123        insta::assert_snapshot!(
3124            p(2 * 60 * 60 + 2 * 60 + 2),
3125            @"2h 2m 2s",
3126        );
3127        insta::assert_snapshot!(
3128            p(10 * 60 * 60 + 10 * 60 + 10),
3129            @"10h 10m 10s",
3130        );
3131        insta::assert_snapshot!(
3132            p(100 * 60 * 60 + 100 * 60 + 100),
3133            @"101h 41m 40s",
3134        );
3135    }
3136
3137    #[test]
3138    fn print_unsigned_duration_designator_verbose() {
3139        let printer = || SpanPrinter::new().designator(Designator::Verbose);
3140        let p = |secs| {
3141            printer().unsigned_duration_to_string(
3142                &core::time::Duration::from_secs(secs),
3143            )
3144        };
3145
3146        insta::assert_snapshot!(p(1), @"1second");
3147        insta::assert_snapshot!(p(2), @"2seconds");
3148        insta::assert_snapshot!(p(10), @"10seconds");
3149        insta::assert_snapshot!(p(100), @"1minute 40seconds");
3150
3151        insta::assert_snapshot!(p(1 * 60), @"1minute");
3152        insta::assert_snapshot!(p(2 * 60), @"2minutes");
3153        insta::assert_snapshot!(p(10 * 60), @"10minutes");
3154        insta::assert_snapshot!(p(100 * 60), @"1hour 40minutes");
3155
3156        insta::assert_snapshot!(p(1 * 60 * 60), @"1hour");
3157        insta::assert_snapshot!(p(2 * 60 * 60), @"2hours");
3158        insta::assert_snapshot!(p(10 * 60 * 60), @"10hours");
3159        insta::assert_snapshot!(p(100 * 60 * 60), @"100hours");
3160
3161        insta::assert_snapshot!(
3162            p(60 * 60 + 60 + 1),
3163            @"1hour 1minute 1second",
3164        );
3165        insta::assert_snapshot!(
3166            p(2 * 60 * 60 + 2 * 60 + 2),
3167            @"2hours 2minutes 2seconds",
3168        );
3169        insta::assert_snapshot!(
3170            p(10 * 60 * 60 + 10 * 60 + 10),
3171            @"10hours 10minutes 10seconds",
3172        );
3173        insta::assert_snapshot!(
3174            p(100 * 60 * 60 + 100 * 60 + 100),
3175            @"101hours 41minutes 40seconds",
3176        );
3177    }
3178
3179    #[test]
3180    fn print_unsigned_duration_designator_short() {
3181        let printer = || SpanPrinter::new().designator(Designator::Short);
3182        let p = |secs| {
3183            printer().unsigned_duration_to_string(
3184                &core::time::Duration::from_secs(secs),
3185            )
3186        };
3187
3188        insta::assert_snapshot!(p(1), @"1sec");
3189        insta::assert_snapshot!(p(2), @"2secs");
3190        insta::assert_snapshot!(p(10), @"10secs");
3191        insta::assert_snapshot!(p(100), @"1min 40secs");
3192
3193        insta::assert_snapshot!(p(1 * 60), @"1min");
3194        insta::assert_snapshot!(p(2 * 60), @"2mins");
3195        insta::assert_snapshot!(p(10 * 60), @"10mins");
3196        insta::assert_snapshot!(p(100 * 60), @"1hr 40mins");
3197
3198        insta::assert_snapshot!(p(1 * 60 * 60), @"1hr");
3199        insta::assert_snapshot!(p(2 * 60 * 60), @"2hrs");
3200        insta::assert_snapshot!(p(10 * 60 * 60), @"10hrs");
3201        insta::assert_snapshot!(p(100 * 60 * 60), @"100hrs");
3202
3203        insta::assert_snapshot!(
3204            p(60 * 60 + 60 + 1),
3205            @"1hr 1min 1sec",
3206        );
3207        insta::assert_snapshot!(
3208            p(2 * 60 * 60 + 2 * 60 + 2),
3209            @"2hrs 2mins 2secs",
3210        );
3211        insta::assert_snapshot!(
3212            p(10 * 60 * 60 + 10 * 60 + 10),
3213            @"10hrs 10mins 10secs",
3214        );
3215        insta::assert_snapshot!(
3216            p(100 * 60 * 60 + 100 * 60 + 100),
3217            @"101hrs 41mins 40secs",
3218        );
3219    }
3220
3221    #[test]
3222    fn print_unsigned_duration_designator_compact() {
3223        let printer = || SpanPrinter::new().designator(Designator::Compact);
3224        let p = |secs| {
3225            printer().unsigned_duration_to_string(
3226                &core::time::Duration::from_secs(secs),
3227            )
3228        };
3229
3230        insta::assert_snapshot!(p(1), @"1s");
3231        insta::assert_snapshot!(p(2), @"2s");
3232        insta::assert_snapshot!(p(10), @"10s");
3233        insta::assert_snapshot!(p(100), @"1m 40s");
3234
3235        insta::assert_snapshot!(p(1 * 60), @"1m");
3236        insta::assert_snapshot!(p(2 * 60), @"2m");
3237        insta::assert_snapshot!(p(10 * 60), @"10m");
3238        insta::assert_snapshot!(p(100 * 60), @"1h 40m");
3239
3240        insta::assert_snapshot!(p(1 * 60 * 60), @"1h");
3241        insta::assert_snapshot!(p(2 * 60 * 60), @"2h");
3242        insta::assert_snapshot!(p(10 * 60 * 60), @"10h");
3243        insta::assert_snapshot!(p(100 * 60 * 60), @"100h");
3244
3245        insta::assert_snapshot!(
3246            p(60 * 60 + 60 + 1),
3247            @"1h 1m 1s",
3248        );
3249        insta::assert_snapshot!(
3250            p(2 * 60 * 60 + 2 * 60 + 2),
3251            @"2h 2m 2s",
3252        );
3253        insta::assert_snapshot!(
3254            p(10 * 60 * 60 + 10 * 60 + 10),
3255            @"10h 10m 10s",
3256        );
3257        insta::assert_snapshot!(
3258            p(100 * 60 * 60 + 100 * 60 + 100),
3259            @"101h 41m 40s",
3260        );
3261    }
3262
3263    #[test]
3264    fn print_unsigned_duration_designator_direction_force() {
3265        let printer = || SpanPrinter::new().direction(Direction::ForceSign);
3266        let p = |secs| {
3267            printer().unsigned_duration_to_string(
3268                &core::time::Duration::from_secs(secs),
3269            )
3270        };
3271
3272        insta::assert_snapshot!(p(1), @"+1s");
3273        insta::assert_snapshot!(p(2), @"+2s");
3274        insta::assert_snapshot!(p(10), @"+10s");
3275        insta::assert_snapshot!(p(100), @"+1m 40s");
3276
3277        insta::assert_snapshot!(p(1 * 60), @"+1m");
3278        insta::assert_snapshot!(p(2 * 60), @"+2m");
3279        insta::assert_snapshot!(p(10 * 60), @"+10m");
3280        insta::assert_snapshot!(p(100 * 60), @"+1h 40m");
3281
3282        insta::assert_snapshot!(p(1 * 60 * 60), @"+1h");
3283        insta::assert_snapshot!(p(2 * 60 * 60), @"+2h");
3284        insta::assert_snapshot!(p(10 * 60 * 60), @"+10h");
3285        insta::assert_snapshot!(p(100 * 60 * 60), @"+100h");
3286
3287        insta::assert_snapshot!(
3288            p(60 * 60 + 60 + 1),
3289            @"+1h 1m 1s",
3290        );
3291        insta::assert_snapshot!(
3292            p(2 * 60 * 60 + 2 * 60 + 2),
3293            @"+2h 2m 2s",
3294        );
3295        insta::assert_snapshot!(
3296            p(10 * 60 * 60 + 10 * 60 + 10),
3297            @"+10h 10m 10s",
3298        );
3299        insta::assert_snapshot!(
3300            p(100 * 60 * 60 + 100 * 60 + 100),
3301            @"+101h 41m 40s",
3302        );
3303    }
3304
3305    #[test]
3306    fn print_unsigned_duration_designator_padding() {
3307        let printer = || SpanPrinter::new().padding(2);
3308        let p = |secs| {
3309            printer().unsigned_duration_to_string(
3310                &core::time::Duration::from_secs(secs),
3311            )
3312        };
3313
3314        insta::assert_snapshot!(p(1), @"01s");
3315        insta::assert_snapshot!(p(2), @"02s");
3316        insta::assert_snapshot!(p(10), @"10s");
3317        insta::assert_snapshot!(p(100), @"01m 40s");
3318
3319        insta::assert_snapshot!(p(1 * 60), @"01m");
3320        insta::assert_snapshot!(p(2 * 60), @"02m");
3321        insta::assert_snapshot!(p(10 * 60), @"10m");
3322        insta::assert_snapshot!(p(100 * 60), @"01h 40m");
3323
3324        insta::assert_snapshot!(p(1 * 60 * 60), @"01h");
3325        insta::assert_snapshot!(p(2 * 60 * 60), @"02h");
3326        insta::assert_snapshot!(p(10 * 60 * 60), @"10h");
3327        insta::assert_snapshot!(p(100 * 60 * 60), @"100h");
3328
3329        insta::assert_snapshot!(
3330            p(60 * 60 + 60 + 1),
3331            @"01h 01m 01s",
3332        );
3333        insta::assert_snapshot!(
3334            p(2 * 60 * 60 + 2 * 60 + 2),
3335            @"02h 02m 02s",
3336        );
3337        insta::assert_snapshot!(
3338            p(10 * 60 * 60 + 10 * 60 + 10),
3339            @"10h 10m 10s",
3340        );
3341        insta::assert_snapshot!(
3342            p(100 * 60 * 60 + 100 * 60 + 100),
3343            @"101h 41m 40s",
3344        );
3345    }
3346
3347    #[test]
3348    fn print_unsigned_duration_designator_spacing_none() {
3349        let printer = || SpanPrinter::new().spacing(Spacing::None);
3350        let p = |secs| {
3351            printer().unsigned_duration_to_string(
3352                &core::time::Duration::from_secs(secs),
3353            )
3354        };
3355
3356        insta::assert_snapshot!(p(1), @"1s");
3357        insta::assert_snapshot!(p(2), @"2s");
3358        insta::assert_snapshot!(p(10), @"10s");
3359        insta::assert_snapshot!(p(100), @"1m40s");
3360
3361        insta::assert_snapshot!(p(1 * 60), @"1m");
3362        insta::assert_snapshot!(p(2 * 60), @"2m");
3363        insta::assert_snapshot!(p(10 * 60), @"10m");
3364        insta::assert_snapshot!(p(100 * 60), @"1h40m");
3365
3366        insta::assert_snapshot!(p(1 * 60 * 60), @"1h");
3367        insta::assert_snapshot!(p(2 * 60 * 60), @"2h");
3368        insta::assert_snapshot!(p(10 * 60 * 60), @"10h");
3369        insta::assert_snapshot!(p(100 * 60 * 60), @"100h");
3370
3371        insta::assert_snapshot!(
3372            p(60 * 60 + 60 + 1),
3373            @"1h1m1s",
3374        );
3375        insta::assert_snapshot!(
3376            p(2 * 60 * 60 + 2 * 60 + 2),
3377            @"2h2m2s",
3378        );
3379        insta::assert_snapshot!(
3380            p(10 * 60 * 60 + 10 * 60 + 10),
3381            @"10h10m10s",
3382        );
3383        insta::assert_snapshot!(
3384            p(100 * 60 * 60 + 100 * 60 + 100),
3385            @"101h41m40s",
3386        );
3387    }
3388
3389    #[test]
3390    fn print_unsigned_duration_designator_spacing_more() {
3391        let printer =
3392            || SpanPrinter::new().spacing(Spacing::BetweenUnitsAndDesignators);
3393        let p = |secs| {
3394            printer().unsigned_duration_to_string(
3395                &core::time::Duration::from_secs(secs),
3396            )
3397        };
3398
3399        insta::assert_snapshot!(p(1), @"1 s");
3400        insta::assert_snapshot!(p(2), @"2 s");
3401        insta::assert_snapshot!(p(10), @"10 s");
3402        insta::assert_snapshot!(p(100), @"1 m 40 s");
3403
3404        insta::assert_snapshot!(p(1 * 60), @"1 m");
3405        insta::assert_snapshot!(p(2 * 60), @"2 m");
3406        insta::assert_snapshot!(p(10 * 60), @"10 m");
3407        insta::assert_snapshot!(p(100 * 60), @"1 h 40 m");
3408
3409        insta::assert_snapshot!(p(1 * 60 * 60), @"1 h");
3410        insta::assert_snapshot!(p(2 * 60 * 60), @"2 h");
3411        insta::assert_snapshot!(p(10 * 60 * 60), @"10 h");
3412        insta::assert_snapshot!(p(100 * 60 * 60), @"100 h");
3413
3414        insta::assert_snapshot!(
3415            p(60 * 60 + 60 + 1),
3416            @"1 h 1 m 1 s",
3417        );
3418        insta::assert_snapshot!(
3419            p(2 * 60 * 60 + 2 * 60 + 2),
3420            @"2 h 2 m 2 s",
3421        );
3422        insta::assert_snapshot!(
3423            p(10 * 60 * 60 + 10 * 60 + 10),
3424            @"10 h 10 m 10 s",
3425        );
3426        insta::assert_snapshot!(
3427            p(100 * 60 * 60 + 100 * 60 + 100),
3428            @"101 h 41 m 40 s",
3429        );
3430    }
3431
3432    #[test]
3433    fn print_unsigned_duration_designator_spacing_comma() {
3434        let printer = || {
3435            SpanPrinter::new()
3436                .comma_after_designator(true)
3437                .spacing(Spacing::BetweenUnitsAndDesignators)
3438        };
3439        let p = |secs| {
3440            printer().unsigned_duration_to_string(
3441                &core::time::Duration::from_secs(secs),
3442            )
3443        };
3444
3445        insta::assert_snapshot!(p(1), @"1 s");
3446        insta::assert_snapshot!(p(2), @"2 s");
3447        insta::assert_snapshot!(p(10), @"10 s");
3448        insta::assert_snapshot!(p(100), @"1 m, 40 s");
3449
3450        insta::assert_snapshot!(p(1 * 60), @"1 m");
3451        insta::assert_snapshot!(p(2 * 60), @"2 m");
3452        insta::assert_snapshot!(p(10 * 60), @"10 m");
3453        insta::assert_snapshot!(p(100 * 60), @"1 h, 40 m");
3454
3455        insta::assert_snapshot!(p(1 * 60 * 60), @"1 h");
3456        insta::assert_snapshot!(p(2 * 60 * 60), @"2 h");
3457        insta::assert_snapshot!(p(10 * 60 * 60), @"10 h");
3458        insta::assert_snapshot!(p(100 * 60 * 60), @"100 h");
3459
3460        insta::assert_snapshot!(
3461            p(60 * 60 + 60 + 1),
3462            @"1 h, 1 m, 1 s",
3463        );
3464        insta::assert_snapshot!(
3465            p(2 * 60 * 60 + 2 * 60 + 2),
3466            @"2 h, 2 m, 2 s",
3467        );
3468        insta::assert_snapshot!(
3469            p(10 * 60 * 60 + 10 * 60 + 10),
3470            @"10 h, 10 m, 10 s",
3471        );
3472        insta::assert_snapshot!(
3473            p(100 * 60 * 60 + 100 * 60 + 100),
3474            @"101 h, 41 m, 40 s",
3475        );
3476    }
3477
3478    #[test]
3479    fn print_unsigned_duration_designator_fractional_hour() {
3480        let printer =
3481            || SpanPrinter::new().fractional(Some(FractionalUnit::Hour));
3482        let p = |secs, nanos| {
3483            printer().unsigned_duration_to_string(&core::time::Duration::new(
3484                secs, nanos,
3485            ))
3486        };
3487        let pp = |precision, secs, nanos| {
3488            printer()
3489                .precision(Some(precision))
3490                .duration_to_string(&SignedDuration::new(secs, nanos))
3491        };
3492
3493        insta::assert_snapshot!(p(1 * 60 * 60, 0), @"1h");
3494        insta::assert_snapshot!(pp(0, 1 * 60 * 60, 0), @"1h");
3495        insta::assert_snapshot!(pp(1, 1 * 60 * 60, 0), @"1.0h");
3496        insta::assert_snapshot!(pp(2, 1 * 60 * 60, 0), @"1.00h");
3497
3498        insta::assert_snapshot!(p(1 * 60 * 60 + 30 * 60, 0), @"1.5h");
3499        insta::assert_snapshot!(pp(0, 1 * 60 * 60 + 30 * 60, 0), @"1h");
3500        insta::assert_snapshot!(pp(1, 1 * 60 * 60 + 30 * 60, 0), @"1.5h");
3501        insta::assert_snapshot!(pp(2, 1 * 60 * 60 + 30 * 60, 0), @"1.50h");
3502
3503        insta::assert_snapshot!(p(1 * 60 * 60 + 3 * 60, 0), @"1.05h");
3504        insta::assert_snapshot!(p(1 * 60 * 60 + 3 * 60, 1), @"1.05h");
3505        insta::assert_snapshot!(p(1, 0), @"0.000277777h");
3506        // precision loss!
3507        insta::assert_snapshot!(p(1, 1), @"0.000277777h");
3508        insta::assert_snapshot!(p(0, 0), @"0h");
3509        // precision loss!
3510        insta::assert_snapshot!(p(0, 1), @"0h");
3511    }
3512
3513    #[test]
3514    fn print_unsigned_duration_designator_fractional_minute() {
3515        let printer =
3516            || SpanPrinter::new().fractional(Some(FractionalUnit::Minute));
3517        let p = |secs, nanos| {
3518            printer().unsigned_duration_to_string(&core::time::Duration::new(
3519                secs, nanos,
3520            ))
3521        };
3522        let pp = |precision, secs, nanos| {
3523            printer()
3524                .precision(Some(precision))
3525                .duration_to_string(&SignedDuration::new(secs, nanos))
3526        };
3527
3528        insta::assert_snapshot!(p(1 * 60 * 60, 0), @"1h");
3529        insta::assert_snapshot!(p(1 * 60 * 60 + 30 * 60, 0), @"1h 30m");
3530
3531        insta::assert_snapshot!(p(60, 0), @"1m");
3532        insta::assert_snapshot!(pp(0, 60, 0), @"1m");
3533        insta::assert_snapshot!(pp(1, 60, 0), @"1.0m");
3534        insta::assert_snapshot!(pp(2, 60, 0), @"1.00m");
3535
3536        insta::assert_snapshot!(p(90, 0), @"1.5m");
3537        insta::assert_snapshot!(pp(0, 90, 0), @"1m");
3538        insta::assert_snapshot!(pp(1, 90, 0), @"1.5m");
3539        insta::assert_snapshot!(pp(2, 90, 0), @"1.50m");
3540
3541        insta::assert_snapshot!(p(1 * 60 * 60, 1), @"1h");
3542        insta::assert_snapshot!(p(63, 0), @"1.05m");
3543        insta::assert_snapshot!(p(63, 1), @"1.05m");
3544        insta::assert_snapshot!(p(1, 0), @"0.016666666m");
3545        // precision loss!
3546        insta::assert_snapshot!(p(1, 1), @"0.016666666m");
3547        insta::assert_snapshot!(p(0, 0), @"0m");
3548        // precision loss!
3549        insta::assert_snapshot!(p(0, 1), @"0m");
3550    }
3551
3552    #[test]
3553    fn print_unsigned_duration_designator_fractional_second() {
3554        let printer =
3555            || SpanPrinter::new().fractional(Some(FractionalUnit::Second));
3556        let p = |secs, nanos| {
3557            printer().unsigned_duration_to_string(&core::time::Duration::new(
3558                secs, nanos,
3559            ))
3560        };
3561        let pp = |precision, secs, nanos| {
3562            printer()
3563                .precision(Some(precision))
3564                .duration_to_string(&SignedDuration::new(secs, nanos))
3565        };
3566
3567        insta::assert_snapshot!(p(1 * 60 * 60, 0), @"1h");
3568        insta::assert_snapshot!(p(1 * 60 * 60 + 30 * 60, 0), @"1h 30m");
3569
3570        insta::assert_snapshot!(p(1, 0), @"1s");
3571        insta::assert_snapshot!(pp(0, 1, 0), @"1s");
3572        insta::assert_snapshot!(pp(1, 1, 0), @"1.0s");
3573        insta::assert_snapshot!(pp(2, 1, 0), @"1.00s");
3574
3575        insta::assert_snapshot!(p(1, 500_000_000), @"1.5s");
3576        insta::assert_snapshot!(pp(0, 1, 500_000_000), @"1s");
3577        insta::assert_snapshot!(pp(1, 1, 500_000_000), @"1.5s");
3578        insta::assert_snapshot!(pp(2, 1, 500_000_000), @"1.50s");
3579
3580        insta::assert_snapshot!(p(1, 1), @"1.000000001s");
3581        insta::assert_snapshot!(p(0, 1), @"0.000000001s");
3582        insta::assert_snapshot!(p(0, 0), @"0s");
3583    }
3584
3585    #[test]
3586    fn print_unsigned_duration_designator_fractional_millisecond() {
3587        let printer = || {
3588            SpanPrinter::new().fractional(Some(FractionalUnit::Millisecond))
3589        };
3590        let p = |secs, nanos| {
3591            printer().unsigned_duration_to_string(&core::time::Duration::new(
3592                secs, nanos,
3593            ))
3594        };
3595        let pp = |precision, secs, nanos| {
3596            printer()
3597                .precision(Some(precision))
3598                .duration_to_string(&SignedDuration::new(secs, nanos))
3599        };
3600
3601        insta::assert_snapshot!(p(1 * 60 * 60, 0), @"1h");
3602        insta::assert_snapshot!(p(1 * 60 * 60 + 30 * 60, 0), @"1h 30m");
3603        insta::assert_snapshot!(
3604            p(1 * 60 * 60 + 30 * 60 + 10, 0),
3605            @"1h 30m 10s",
3606        );
3607
3608        insta::assert_snapshot!(p(1, 0), @"1s");
3609        insta::assert_snapshot!(pp(0, 1, 0), @"1s");
3610        insta::assert_snapshot!(pp(1, 1, 0), @"1s 0.0ms");
3611        insta::assert_snapshot!(pp(2, 1, 0), @"1s 0.00ms");
3612
3613        insta::assert_snapshot!(p(1, 500_000_000), @"1s 500ms");
3614        insta::assert_snapshot!(pp(0, 1, 1_500_000), @"1s 1ms");
3615        insta::assert_snapshot!(pp(1, 1, 1_500_000), @"1s 1.5ms");
3616        insta::assert_snapshot!(pp(2, 1, 1_500_000), @"1s 1.50ms");
3617
3618        insta::assert_snapshot!(p(0, 1_000_001), @"1.000001ms");
3619        insta::assert_snapshot!(p(0, 0_000_001), @"0.000001ms");
3620        insta::assert_snapshot!(p(0, 0), @"0ms");
3621    }
3622
3623    #[test]
3624    fn print_unsigned_duration_designator_fractional_microsecond() {
3625        let printer = || {
3626            SpanPrinter::new().fractional(Some(FractionalUnit::Microsecond))
3627        };
3628        let p = |secs, nanos| {
3629            printer().unsigned_duration_to_string(&core::time::Duration::new(
3630                secs, nanos,
3631            ))
3632        };
3633        let pp = |precision, secs, nanos| {
3634            printer().precision(Some(precision)).unsigned_duration_to_string(
3635                &core::time::Duration::new(secs, nanos),
3636            )
3637        };
3638
3639        insta::assert_snapshot!(p(1 * 60 * 60, 0), @"1h");
3640        insta::assert_snapshot!(p(1 * 60 * 60 + 30 * 60, 0), @"1h 30m");
3641        insta::assert_snapshot!(
3642            p(1 * 60 * 60 + 30 * 60 + 10, 0),
3643            @"1h 30m 10s",
3644        );
3645
3646        insta::assert_snapshot!(p(1, 0), @"1s");
3647        insta::assert_snapshot!(pp(0, 1, 0), @"1s");
3648        insta::assert_snapshot!(pp(1, 1, 0), @"1s 0.0µs");
3649        insta::assert_snapshot!(pp(2, 1, 0), @"1s 0.00µs");
3650
3651        insta::assert_snapshot!(p(1, 500_000_000), @"1s 500ms");
3652        insta::assert_snapshot!(pp(0, 1, 1_500_000), @"1s 1ms 500µs");
3653        insta::assert_snapshot!(pp(1, 1, 1_500_000), @"1s 1ms 500.0µs");
3654        insta::assert_snapshot!(pp(2, 1, 1_500_000), @"1s 1ms 500.00µs");
3655
3656        insta::assert_snapshot!(p(0, 1_000_001), @"1ms 0.001µs");
3657        insta::assert_snapshot!(p(0, 0_000_001), @"0.001µs");
3658        insta::assert_snapshot!(p(0, 0), @"0µs");
3659    }
3660
3661    #[test]
3662    fn print_span_hms() {
3663        let printer = || SpanPrinter::new().hours_minutes_seconds(true);
3664        let p = |span| printer().span_to_string(&span);
3665
3666        insta::assert_snapshot!(p(1.second()), @"00:00:01");
3667        insta::assert_snapshot!(p(2.seconds()), @"00:00:02");
3668        insta::assert_snapshot!(p(10.seconds()), @"00:00:10");
3669        insta::assert_snapshot!(p(100.seconds()), @"00:00:100");
3670
3671        insta::assert_snapshot!(p(1.minute()), @"00:01:00");
3672        insta::assert_snapshot!(p(2.minutes()), @"00:02:00");
3673        insta::assert_snapshot!(p(10.minutes()), @"00:10:00");
3674        insta::assert_snapshot!(p(100.minutes()), @"00:100:00");
3675
3676        insta::assert_snapshot!(p(1.hour()), @"01:00:00");
3677        insta::assert_snapshot!(p(2.hours()), @"02:00:00");
3678        insta::assert_snapshot!(p(10.hours()), @"10:00:00");
3679        insta::assert_snapshot!(p(100.hours()), @"100:00:00");
3680
3681        insta::assert_snapshot!(
3682            p(1.hour().minutes(1).seconds(1)),
3683            @"01:01:01",
3684        );
3685        insta::assert_snapshot!(
3686            p(2.hours().minutes(2).seconds(2)),
3687            @"02:02:02",
3688        );
3689        insta::assert_snapshot!(
3690            p(10.hours().minutes(10).seconds(10)),
3691            @"10:10:10",
3692        );
3693        insta::assert_snapshot!(
3694            p(100.hours().minutes(100).seconds(100)),
3695            @"100:100:100",
3696        );
3697
3698        insta::assert_snapshot!(
3699            p(1.day().hours(1).minutes(1).seconds(1)),
3700            @"1d 01:01:01",
3701        );
3702        insta::assert_snapshot!(
3703            p(1.day()),
3704            @"1d 00:00:00",
3705        );
3706        insta::assert_snapshot!(
3707            p(1.day().seconds(2)),
3708            @"1d 00:00:02",
3709        );
3710    }
3711
3712    #[test]
3713    fn print_span_hms_fmt() {
3714        let printer = || {
3715            SpanPrinter::new()
3716                .hours_minutes_seconds(true)
3717                .comma_after_designator(true)
3718                .spacing(Spacing::BetweenUnitsAndDesignators)
3719        };
3720        let p = |span| printer().span_to_string(&span);
3721
3722        insta::assert_snapshot!(
3723            p(1.day().hours(1).minutes(1).seconds(1)),
3724            @"1 d, 01:01:01",
3725        );
3726        insta::assert_snapshot!(
3727            p(1.year().months(1).weeks(1).days(1).hours(1).minutes(1).seconds(1)),
3728            @"1 y, 1 mo, 1 w, 1 d, 01:01:01",
3729        );
3730        insta::assert_snapshot!(
3731            p(1.day().hours(1).minutes(1).seconds(1).nanoseconds(1)),
3732            @"1 d, 01:01:01.000000001",
3733        );
3734    }
3735
3736    #[test]
3737    fn print_span_hms_sign() {
3738        let printer = |direction| {
3739            SpanPrinter::new().hours_minutes_seconds(true).direction(direction)
3740        };
3741        let p = |direction, span| printer(direction).span_to_string(&span);
3742
3743        insta::assert_snapshot!(
3744            p(Direction::Auto, 1.hour()),
3745            @"01:00:00",
3746        );
3747        insta::assert_snapshot!(
3748            p(Direction::Sign, 1.hour()),
3749            @"01:00:00",
3750        );
3751        insta::assert_snapshot!(
3752            p(Direction::ForceSign, 1.hour()),
3753            @"+01:00:00",
3754        );
3755        insta::assert_snapshot!(
3756            p(Direction::Suffix, 1.hour()),
3757            @"01:00:00",
3758        );
3759        insta::assert_snapshot!(
3760            p(Direction::Auto, -1.hour()),
3761            @"-01:00:00",
3762        );
3763        insta::assert_snapshot!(
3764            p(Direction::Sign, -1.hour()),
3765            @"-01:00:00",
3766        );
3767        insta::assert_snapshot!(
3768            p(Direction::ForceSign, -1.hour()),
3769            @"-01:00:00",
3770        );
3771        insta::assert_snapshot!(
3772            p(Direction::Suffix, -1.hour()),
3773            @"01:00:00 ago",
3774        );
3775
3776        insta::assert_snapshot!(
3777            p(Direction::Auto, 1.day().hours(1)),
3778            @"1d 01:00:00",
3779        );
3780        insta::assert_snapshot!(
3781            p(Direction::Sign, 1.day().hours(1)),
3782            @"1d 01:00:00",
3783        );
3784        insta::assert_snapshot!(
3785            p(Direction::ForceSign, 1.day().hours(1)),
3786            @"+1d 01:00:00",
3787        );
3788        insta::assert_snapshot!(
3789            p(Direction::Suffix, 1.day().hours(1)),
3790            @"1d 01:00:00",
3791        );
3792        // This is the main change from above. With non-zero
3793        // calendar units, the default for expressing a negative
3794        // sign switches to a suffix in the HH:MM:SS format.
3795        insta::assert_snapshot!(
3796            p(Direction::Auto, -1.day().hours(1)),
3797            @"1d 01:00:00 ago",
3798        );
3799        insta::assert_snapshot!(
3800            p(Direction::Sign, -1.day().hours(1)),
3801            @"-1d 01:00:00",
3802        );
3803        insta::assert_snapshot!(
3804            p(Direction::ForceSign, -1.day().hours(1)),
3805            @"-1d 01:00:00",
3806        );
3807        insta::assert_snapshot!(
3808            p(Direction::Suffix, -1.day().hours(1)),
3809            @"1d 01:00:00 ago",
3810        );
3811    }
3812
3813    #[test]
3814    fn print_span_hms_fraction_auto() {
3815        let printer = || SpanPrinter::new().hours_minutes_seconds(true);
3816        let p = |span| printer().span_to_string(&span);
3817
3818        insta::assert_snapshot!(p(1.nanosecond()), @"00:00:00.000000001");
3819        insta::assert_snapshot!(p(-1.nanosecond()), @"-00:00:00.000000001");
3820        insta::assert_snapshot!(
3821            printer().direction(Direction::ForceSign).span_to_string(&1.nanosecond()),
3822            @"+00:00:00.000000001",
3823        );
3824
3825        insta::assert_snapshot!(
3826            p(1.second().nanoseconds(123)),
3827            @"00:00:01.000000123",
3828        );
3829        insta::assert_snapshot!(
3830            p(1.second().milliseconds(123)),
3831            @"00:00:01.123",
3832        );
3833        insta::assert_snapshot!(
3834            p(1.second().milliseconds(1_123)),
3835            @"00:00:02.123",
3836        );
3837        insta::assert_snapshot!(
3838            p(1.second().milliseconds(61_123)),
3839            @"00:00:62.123",
3840        );
3841    }
3842
3843    #[test]
3844    fn print_span_hms_fraction_fixed_precision() {
3845        let printer = || SpanPrinter::new().hours_minutes_seconds(true);
3846        let p = |precision, span| {
3847            printer().precision(Some(precision)).span_to_string(&span)
3848        };
3849
3850        insta::assert_snapshot!(p(3, 1.second()), @"00:00:01.000");
3851        insta::assert_snapshot!(
3852            p(3, 1.second().milliseconds(1)),
3853            @"00:00:01.001",
3854        );
3855        insta::assert_snapshot!(
3856            p(3, 1.second().milliseconds(123)),
3857            @"00:00:01.123",
3858        );
3859        insta::assert_snapshot!(
3860            p(3, 1.second().milliseconds(100)),
3861            @"00:00:01.100",
3862        );
3863
3864        insta::assert_snapshot!(p(0, 1.second()), @"00:00:01");
3865        insta::assert_snapshot!(p(0, 1.second().milliseconds(1)), @"00:00:01");
3866        insta::assert_snapshot!(
3867            p(1, 1.second().milliseconds(999)),
3868            @"00:00:01.9",
3869        );
3870    }
3871
3872    #[test]
3873    fn print_signed_duration_hms() {
3874        let printer = || SpanPrinter::new().hours_minutes_seconds(true);
3875        let p = |secs| {
3876            printer().duration_to_string(&SignedDuration::from_secs(secs))
3877        };
3878
3879        // Note the differences with `Span`, since with a `SignedDuration`,
3880        // all units are balanced.
3881
3882        insta::assert_snapshot!(p(1), @"00:00:01");
3883        insta::assert_snapshot!(p(2), @"00:00:02");
3884        insta::assert_snapshot!(p(10), @"00:00:10");
3885        insta::assert_snapshot!(p(100), @"00:01:40");
3886
3887        insta::assert_snapshot!(p(1 * 60), @"00:01:00");
3888        insta::assert_snapshot!(p(2 * 60), @"00:02:00");
3889        insta::assert_snapshot!(p(10 * 60), @"00:10:00");
3890        insta::assert_snapshot!(p(100 * 60), @"01:40:00");
3891
3892        insta::assert_snapshot!(p(1 * 60 * 60), @"01:00:00");
3893        insta::assert_snapshot!(p(2 * 60 * 60), @"02:00:00");
3894        insta::assert_snapshot!(p(10 * 60 * 60), @"10:00:00");
3895        insta::assert_snapshot!(p(100 * 60 * 60), @"100:00:00");
3896
3897        insta::assert_snapshot!(
3898            p(60 * 60 + 60 + 1),
3899            @"01:01:01",
3900        );
3901        insta::assert_snapshot!(
3902            p(2 * 60 * 60 + 2 * 60 + 2),
3903            @"02:02:02",
3904        );
3905        insta::assert_snapshot!(
3906            p(10 * 60 * 60 + 10 * 60 + 10),
3907            @"10:10:10",
3908        );
3909        insta::assert_snapshot!(
3910            p(100 * 60 * 60 + 100 * 60 + 100),
3911            @"101:41:40",
3912        );
3913    }
3914
3915    #[test]
3916    fn print_signed_duration_hms_sign() {
3917        let printer = |direction| {
3918            SpanPrinter::new().hours_minutes_seconds(true).direction(direction)
3919        };
3920        let p = |direction, secs| {
3921            printer(direction)
3922                .duration_to_string(&SignedDuration::from_secs(secs))
3923        };
3924
3925        insta::assert_snapshot!(p(Direction::Auto, 1), @"00:00:01");
3926        insta::assert_snapshot!(p(Direction::Sign, 1), @"00:00:01");
3927        insta::assert_snapshot!(p(Direction::ForceSign, 1), @"+00:00:01");
3928        insta::assert_snapshot!(p(Direction::Suffix, 1), @"00:00:01");
3929
3930        insta::assert_snapshot!(p(Direction::Auto, -1), @"-00:00:01");
3931        insta::assert_snapshot!(p(Direction::Sign, -1), @"-00:00:01");
3932        insta::assert_snapshot!(p(Direction::ForceSign, -1), @"-00:00:01");
3933        insta::assert_snapshot!(p(Direction::Suffix, -1), @"00:00:01 ago");
3934    }
3935
3936    #[test]
3937    fn print_signed_duration_hms_fraction_auto() {
3938        let printer = || SpanPrinter::new().hours_minutes_seconds(true);
3939        let p = |secs, nanos| {
3940            printer().duration_to_string(&SignedDuration::new(secs, nanos))
3941        };
3942
3943        insta::assert_snapshot!(p(0, 1), @"00:00:00.000000001");
3944        insta::assert_snapshot!(p(0, -1), @"-00:00:00.000000001");
3945        insta::assert_snapshot!(
3946            printer().direction(Direction::ForceSign).duration_to_string(
3947                &SignedDuration::new(0, 1),
3948            ),
3949            @"+00:00:00.000000001",
3950        );
3951
3952        insta::assert_snapshot!(
3953            p(1, 123),
3954            @"00:00:01.000000123",
3955        );
3956        insta::assert_snapshot!(
3957            p(1, 123_000_000),
3958            @"00:00:01.123",
3959        );
3960        insta::assert_snapshot!(
3961            p(1, 1_123_000_000),
3962            @"00:00:02.123",
3963        );
3964        insta::assert_snapshot!(
3965            p(61, 1_123_000_000),
3966            @"00:01:02.123",
3967        );
3968    }
3969
3970    #[test]
3971    fn print_signed_duration_hms_fraction_fixed_precision() {
3972        let printer = || SpanPrinter::new().hours_minutes_seconds(true);
3973        let p = |precision, secs, nanos| {
3974            printer()
3975                .precision(Some(precision))
3976                .duration_to_string(&SignedDuration::new(secs, nanos))
3977        };
3978
3979        insta::assert_snapshot!(p(3, 1, 0), @"00:00:01.000");
3980        insta::assert_snapshot!(
3981            p(3, 1, 1_000_000),
3982            @"00:00:01.001",
3983        );
3984        insta::assert_snapshot!(
3985            p(3, 1, 123_000_000),
3986            @"00:00:01.123",
3987        );
3988        insta::assert_snapshot!(
3989            p(3, 1, 100_000_000),
3990            @"00:00:01.100",
3991        );
3992
3993        insta::assert_snapshot!(p(0, 1, 0), @"00:00:01");
3994        insta::assert_snapshot!(p(0, 1, 1_000_000), @"00:00:01");
3995        insta::assert_snapshot!(
3996            p(1, 1, 999_000_000),
3997            @"00:00:01.9",
3998        );
3999    }
4000
4001    #[test]
4002    fn print_unsigned_duration_hms() {
4003        let printer = || SpanPrinter::new().hours_minutes_seconds(true);
4004        let p = |secs| {
4005            printer().unsigned_duration_to_string(
4006                &core::time::Duration::from_secs(secs),
4007            )
4008        };
4009
4010        // Note the differences with `Span`, since with a `Duration`,
4011        // all units are balanced.
4012
4013        insta::assert_snapshot!(p(1), @"00:00:01");
4014        insta::assert_snapshot!(p(2), @"00:00:02");
4015        insta::assert_snapshot!(p(10), @"00:00:10");
4016        insta::assert_snapshot!(p(100), @"00:01:40");
4017
4018        insta::assert_snapshot!(p(1 * 60), @"00:01:00");
4019        insta::assert_snapshot!(p(2 * 60), @"00:02:00");
4020        insta::assert_snapshot!(p(10 * 60), @"00:10:00");
4021        insta::assert_snapshot!(p(100 * 60), @"01:40:00");
4022
4023        insta::assert_snapshot!(p(1 * 60 * 60), @"01:00:00");
4024        insta::assert_snapshot!(p(2 * 60 * 60), @"02:00:00");
4025        insta::assert_snapshot!(p(10 * 60 * 60), @"10:00:00");
4026        insta::assert_snapshot!(p(100 * 60 * 60), @"100:00:00");
4027
4028        insta::assert_snapshot!(
4029            p(60 * 60 + 60 + 1),
4030            @"01:01:01",
4031        );
4032        insta::assert_snapshot!(
4033            p(2 * 60 * 60 + 2 * 60 + 2),
4034            @"02:02:02",
4035        );
4036        insta::assert_snapshot!(
4037            p(10 * 60 * 60 + 10 * 60 + 10),
4038            @"10:10:10",
4039        );
4040        insta::assert_snapshot!(
4041            p(100 * 60 * 60 + 100 * 60 + 100),
4042            @"101:41:40",
4043        );
4044    }
4045
4046    #[test]
4047    fn print_unsigned_duration_hms_sign() {
4048        let printer = |direction| {
4049            SpanPrinter::new().hours_minutes_seconds(true).direction(direction)
4050        };
4051        let p = |direction, secs| {
4052            printer(direction).unsigned_duration_to_string(
4053                &core::time::Duration::from_secs(secs),
4054            )
4055        };
4056
4057        insta::assert_snapshot!(p(Direction::Auto, 1), @"00:00:01");
4058        insta::assert_snapshot!(p(Direction::Sign, 1), @"00:00:01");
4059        insta::assert_snapshot!(p(Direction::ForceSign, 1), @"+00:00:01");
4060        insta::assert_snapshot!(p(Direction::Suffix, 1), @"00:00:01");
4061    }
4062
4063    #[test]
4064    fn print_unsigned_duration_hms_fraction_auto() {
4065        let printer = || SpanPrinter::new().hours_minutes_seconds(true);
4066        let p = |secs, nanos| {
4067            printer().unsigned_duration_to_string(&core::time::Duration::new(
4068                secs, nanos,
4069            ))
4070        };
4071
4072        insta::assert_snapshot!(p(0, 1), @"00:00:00.000000001");
4073        insta::assert_snapshot!(
4074            printer().direction(Direction::ForceSign).duration_to_string(
4075                &SignedDuration::new(0, 1),
4076            ),
4077            @"+00:00:00.000000001",
4078        );
4079
4080        insta::assert_snapshot!(
4081            p(1, 123),
4082            @"00:00:01.000000123",
4083        );
4084        insta::assert_snapshot!(
4085            p(1, 123_000_000),
4086            @"00:00:01.123",
4087        );
4088        insta::assert_snapshot!(
4089            p(1, 1_123_000_000),
4090            @"00:00:02.123",
4091        );
4092        insta::assert_snapshot!(
4093            p(61, 1_123_000_000),
4094            @"00:01:02.123",
4095        );
4096    }
4097
4098    #[test]
4099    fn print_unsigned_duration_hms_fraction_fixed_precision() {
4100        let printer = || SpanPrinter::new().hours_minutes_seconds(true);
4101        let p = |precision, secs, nanos| {
4102            printer().precision(Some(precision)).unsigned_duration_to_string(
4103                &core::time::Duration::new(secs, nanos),
4104            )
4105        };
4106
4107        insta::assert_snapshot!(p(3, 1, 0), @"00:00:01.000");
4108        insta::assert_snapshot!(
4109            p(3, 1, 1_000_000),
4110            @"00:00:01.001",
4111        );
4112        insta::assert_snapshot!(
4113            p(3, 1, 123_000_000),
4114            @"00:00:01.123",
4115        );
4116        insta::assert_snapshot!(
4117            p(3, 1, 100_000_000),
4118            @"00:00:01.100",
4119        );
4120
4121        insta::assert_snapshot!(p(0, 1, 0), @"00:00:01");
4122        insta::assert_snapshot!(p(0, 1, 1_000_000), @"00:00:01");
4123        insta::assert_snapshot!(
4124            p(1, 1, 999_000_000),
4125            @"00:00:01.9",
4126        );
4127    }
4128
4129    /// Tests that we can write the maximal string successfully.
4130    ///
4131    /// This test doesn't guarantee that we'll always attempt the true
4132    /// maximum. The maximums here were determined by human inspection.
4133    #[test]
4134    fn maximums() {
4135        let p = SpanPrinter::new()
4136            .padding(u8::MAX)
4137            .designator(Designator::Verbose)
4138            .spacing(Spacing::BetweenUnitsAndDesignators)
4139            .comma_after_designator(true);
4140
4141        let span = -19_998
4142            .year()
4143            .months(239_976)
4144            .weeks(1_043_497)
4145            .days(7_304_484)
4146            .hours(175_307_616)
4147            .minutes(10_518_456_960i64)
4148            .seconds(631_107_417_600i64)
4149            .milliseconds(631_107_417_600_000i64)
4150            .microseconds(631_107_416_600_000_000i64)
4151            .nanoseconds(9_223_372_036_854_775_807i64);
4152        insta::assert_snapshot!(
4153            p.span_to_string(&span),
4154            @"00000000000000019998 years, 00000000000000239976 months, 00000000000001043497 weeks, 00000000000007304484 days, 00000000000175307616 hours, 00000000010518456960 minutes, 00000000631107417600 seconds, 00000631107417600000 milliseconds, 00631107416600000000 microseconds, 09223372036854775807 nanoseconds ago",
4155        );
4156
4157        let sdur = SignedDuration::MAX;
4158        insta::assert_snapshot!(
4159            p.duration_to_string(&sdur),
4160            @"00002562047788015215 hours, 00000000000000000030 minutes, 00000000000000000007 seconds, 00000000000000000999 milliseconds, 00000000000000000999 microseconds, 00000000000000000999 nanoseconds",
4161        );
4162
4163        let udur =
4164            core::time::Duration::MAX - core::time::Duration::from_secs(16);
4165        insta::assert_snapshot!(
4166            p.unsigned_duration_to_string(&udur),
4167            @"00005124095576030430 hours, 00000000000000000059 minutes, 00000000000000000059 seconds, 00000000000000000999 milliseconds, 00000000000000000999 microseconds, 00000000000000000999 nanoseconds",
4168        );
4169
4170        let p = p.direction(Direction::ForceSign);
4171        insta::assert_snapshot!(
4172            p.unsigned_duration_to_string(&udur),
4173            @"+00005124095576030430 hours, 00000000000000000059 minutes, 00000000000000000059 seconds, 00000000000000000999 milliseconds, 00000000000000000999 microseconds, 00000000000000000999 nanoseconds",
4174        );
4175    }
4176}