Skip to main content

jiff/
span.rs

1use core::{cmp::Ordering, time::Duration as UnsignedDuration};
2
3use crate::{
4    civil::{Date, DateTime, Time},
5    duration::{Duration, SDuration},
6    error::{span::Error as E, unit::UnitConfigError, Error, ErrorContext},
7    fmt::{friendly, temporal},
8    tz::TimeZone,
9    util::{b, borrow::DumbCow, round::Increment},
10    RoundMode, SignedDuration, Timestamp, Zoned,
11};
12
13/// A macro helper, only used in tests, for comparing spans for equality.
14#[cfg(test)]
15macro_rules! span_eq {
16    ($span1:expr, $span2:expr $(,)?) => {{
17        assert_eq!($span1.fieldwise(), $span2.fieldwise());
18    }};
19    ($span1:expr, $span2:expr, $($tt:tt)*) => {{
20        assert_eq!($span1.fieldwise(), $span2.fieldwise(), $($tt)*);
21    }};
22}
23
24#[cfg(test)]
25pub(crate) use span_eq;
26
27/// A span of time represented via a mixture of calendar and clock units.
28///
29/// A span represents a duration of time in units of years, months, weeks,
30/// days, hours, minutes, seconds, milliseconds, microseconds and nanoseconds.
31/// Spans are used to as inputs to routines like
32/// [`Zoned::checked_add`] and [`Date::saturating_sub`],
33/// and are also outputs from routines like
34/// [`Timestamp::since`] and [`DateTime::until`].
35///
36/// # Range of spans
37///
38/// Except for nanoseconds, each unit can represent the full span of time
39/// expressible via any combination of datetime supported by Jiff. For example:
40///
41/// ```
42/// use jiff::{civil::{DateTime, DateTimeDifference}, ToSpan, Unit};
43///
44/// let options = DateTimeDifference::new(DateTime::MAX).largest(Unit::Year);
45/// assert_eq!(DateTime::MIN.until(options)?.get_years(), 19_998);
46///
47/// let options = options.largest(Unit::Day);
48/// assert_eq!(DateTime::MIN.until(options)?.get_days(), 7_304_483);
49///
50/// let options = options.largest(Unit::Microsecond);
51/// assert_eq!(
52///     DateTime::MIN.until(options)?.get_microseconds(),
53///     631_107_417_599_999_999i64,
54/// );
55///
56/// let options = options.largest(Unit::Nanosecond);
57/// // Span is too big, overflow!
58/// assert!(DateTime::MIN.until(options).is_err());
59///
60/// # Ok::<(), Box<dyn std::error::Error>>(())
61/// ```
62///
63/// # Building spans
64///
65/// A default or empty span corresponds to a duration of zero time:
66///
67/// ```
68/// use jiff::Span;
69///
70/// assert!(Span::new().is_zero());
71/// assert!(Span::default().is_zero());
72/// ```
73///
74/// Spans are `Copy` types that have mutator methods on them for creating new
75/// spans:
76///
77/// ```
78/// use jiff::Span;
79///
80/// let span = Span::new().days(5).hours(8).minutes(1);
81/// assert_eq!(span.to_string(), "P5DT8H1M");
82/// ```
83///
84/// But Jiff provides a [`ToSpan`] trait that defines extension methods on
85/// primitive signed integers to make span creation terser:
86///
87/// ```
88/// use jiff::ToSpan;
89///
90/// let span = 5.days().hours(8).minutes(1);
91/// assert_eq!(span.to_string(), "P5DT8H1M");
92/// // singular units on integers can be used too:
93/// let span = 1.day().hours(8).minutes(1);
94/// assert_eq!(span.to_string(), "P1DT8H1M");
95/// ```
96///
97/// # Negative spans
98///
99/// A span may be negative. All of these are equivalent:
100///
101/// ```
102/// use jiff::{Span, ToSpan};
103///
104/// let span = -Span::new().days(5);
105/// assert_eq!(span.to_string(), "-P5D");
106///
107/// let span = Span::new().days(5).negate();
108/// assert_eq!(span.to_string(), "-P5D");
109///
110/// let span = Span::new().days(-5);
111/// assert_eq!(span.to_string(), "-P5D");
112///
113/// let span = -Span::new().days(-5).negate();
114/// assert_eq!(span.to_string(), "-P5D");
115///
116/// let span = -5.days();
117/// assert_eq!(span.to_string(), "-P5D");
118///
119/// let span = (-5).days();
120/// assert_eq!(span.to_string(), "-P5D");
121///
122/// let span = -(5.days());
123/// assert_eq!(span.to_string(), "-P5D");
124/// ```
125///
126/// The sign of a span applies to the entire span. When a span is negative,
127/// then all of its units are negative:
128///
129/// ```
130/// use jiff::ToSpan;
131///
132/// let span = -5.days().hours(10).minutes(1);
133/// assert_eq!(span.get_days(), -5);
134/// assert_eq!(span.get_hours(), -10);
135/// assert_eq!(span.get_minutes(), -1);
136/// ```
137///
138/// And if any of a span's units are negative, then the entire span is regarded
139/// as negative:
140///
141/// ```
142/// use jiff::ToSpan;
143///
144/// // It's the same thing.
145/// let span = (-5).days().hours(-10).minutes(-1);
146/// assert_eq!(span.get_days(), -5);
147/// assert_eq!(span.get_hours(), -10);
148/// assert_eq!(span.get_minutes(), -1);
149///
150/// // Still the same. All negative.
151/// let span = 5.days().hours(-10).minutes(1);
152/// assert_eq!(span.get_days(), -5);
153/// assert_eq!(span.get_hours(), -10);
154/// assert_eq!(span.get_minutes(), -1);
155///
156/// // But this is not! The negation in front applies
157/// // to the entire span, which was already negative
158/// // by virtue of at least one of its units being
159/// // negative. So the negation operator in front turns
160/// // the span positive.
161/// let span = -5.days().hours(-10).minutes(-1);
162/// assert_eq!(span.get_days(), 5);
163/// assert_eq!(span.get_hours(), 10);
164/// assert_eq!(span.get_minutes(), 1);
165/// ```
166///
167/// You can also ask for the absolute value of a span:
168///
169/// ```
170/// use jiff::Span;
171///
172/// let span = Span::new().days(5).hours(10).minutes(1).negate().abs();
173/// assert_eq!(span.get_days(), 5);
174/// assert_eq!(span.get_hours(), 10);
175/// assert_eq!(span.get_minutes(), 1);
176/// ```
177///
178/// # Parsing and printing
179///
180/// The `Span` type provides convenient trait implementations of
181/// [`std::str::FromStr`] and [`std::fmt::Display`]:
182///
183/// ```
184/// use jiff::{Span, ToSpan};
185///
186/// let span: Span = "P2m10dT2h30m".parse()?;
187/// // By default, capital unit designator labels are used.
188/// // This can be changed with `jiff::fmt::temporal::SpanPrinter::lowercase`.
189/// assert_eq!(span.to_string(), "P2M10DT2H30M");
190///
191/// // Or use the "friendly" format by invoking the `Display` alternate:
192/// assert_eq!(format!("{span:#}"), "2mo 10d 2h 30m");
193///
194/// // Parsing automatically supports both the ISO 8601 and "friendly"
195/// // formats. Note that we use `Span::fieldwise` to create a `Span` that
196/// // compares based on each field. To compare based on total duration, use
197/// // `Span::compare` or `Span::total`.
198/// let span: Span = "2mo 10d 2h 30m".parse()?;
199/// assert_eq!(span, 2.months().days(10).hours(2).minutes(30).fieldwise());
200/// let span: Span = "2 months, 10 days, 2 hours, 30 minutes".parse()?;
201/// assert_eq!(span, 2.months().days(10).hours(2).minutes(30).fieldwise());
202///
203/// # Ok::<(), Box<dyn std::error::Error>>(())
204/// ```
205///
206/// The format supported is a variation (nearly a subset) of the duration
207/// format specified in [ISO 8601] _and_ a Jiff-specific "friendly" format.
208/// Here are more examples:
209///
210/// ```
211/// use jiff::{Span, ToSpan};
212///
213/// let spans = [
214///     // ISO 8601
215///     ("P40D", 40.days()),
216///     ("P1y1d", 1.year().days(1)),
217///     ("P3dT4h59m", 3.days().hours(4).minutes(59)),
218///     ("PT2H30M", 2.hours().minutes(30)),
219///     ("P1m", 1.month()),
220///     ("P1w", 1.week()),
221///     ("P1w4d", 1.week().days(4)),
222///     ("PT1m", 1.minute()),
223///     ("PT0.0021s", 2.milliseconds().microseconds(100)),
224///     ("PT0s", 0.seconds()),
225///     ("P0d", 0.seconds()),
226///     (
227///         "P1y1m1dT1h1m1.1s",
228///         1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
229///     ),
230///     // Jiff's "friendly" format
231///     ("40d", 40.days()),
232///     ("40 days", 40.days()),
233///     ("1y1d", 1.year().days(1)),
234///     ("1yr 1d", 1.year().days(1)),
235///     ("3d4h59m", 3.days().hours(4).minutes(59)),
236///     ("3 days, 4 hours, 59 minutes", 3.days().hours(4).minutes(59)),
237///     ("3d 4h 59m", 3.days().hours(4).minutes(59)),
238///     ("2h30m", 2.hours().minutes(30)),
239///     ("2h 30m", 2.hours().minutes(30)),
240///     ("1mo", 1.month()),
241///     ("1w", 1.week()),
242///     ("1 week", 1.week()),
243///     ("1w4d", 1.week().days(4)),
244///     ("1 wk 4 days", 1.week().days(4)),
245///     ("1m", 1.minute()),
246///     ("0.0021s", 2.milliseconds().microseconds(100)),
247///     ("0s", 0.seconds()),
248///     ("0d", 0.seconds()),
249///     ("0 days", 0.seconds()),
250///     (
251///         "1y1mo1d1h1m1.1s",
252///         1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
253///     ),
254///     (
255///         "1yr 1mo 1day 1hr 1min 1.1sec",
256///         1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
257///     ),
258///     (
259///         "1 year, 1 month, 1 day, 1 hour, 1 minute 1.1 seconds",
260///         1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
261///     ),
262///     (
263///         "1 year, 1 month, 1 day, 01:01:01.1",
264///         1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
265///     ),
266/// ];
267/// for (string, span) in spans {
268///     let parsed: Span = string.parse()?;
269///     assert_eq!(
270///         span.fieldwise(),
271///         parsed.fieldwise(),
272///         "result of parsing {string:?}",
273///     );
274/// }
275///
276/// # Ok::<(), Box<dyn std::error::Error>>(())
277/// ```
278///
279/// For more details, see the [`fmt::temporal`](temporal) and
280/// [`fmt::friendly`](friendly) modules.
281///
282/// [ISO 8601]: https://www.iso.org/iso-8601-date-and-time-format.html
283///
284/// # Comparisons
285///
286/// A `Span` does not implement the `PartialEq` or `Eq` traits. These traits
287/// were implemented in an earlier version of Jiff, but they made it too
288/// easy to introduce bugs. For example, `120.minutes()` and `2.hours()`
289/// always correspond to the same total duration, but they have different
290/// representations in memory and so didn't compare equivalent.
291///
292/// The reason why the `PartialEq` and `Eq` trait implementations do not do
293/// comparisons with total duration is because it is fundamentally impossible
294/// to do such comparisons without a reference date in all cases.
295///
296/// However, it is undeniably occasionally useful to do comparisons based
297/// on the component fields, so long as such use cases can tolerate two
298/// different spans comparing unequal even when their total durations are
299/// equivalent. For example, many of the tests in Jiff (including the tests in
300/// the documentation) work by comparing a `Span` to an expected result. This
301/// is a good demonstration of when fieldwise comparisons are appropriate.
302///
303/// To do fieldwise comparisons with a span, use the [`Span::fieldwise`]
304/// method. This method creates a [`SpanFieldwise`], which is just a `Span`
305/// that implements `PartialEq` and `Eq` in a fieldwise manner. In other words,
306/// it's a speed bump to ensure this is the kind of comparison you actually
307/// want. For example:
308///
309/// ```
310/// use jiff::ToSpan;
311///
312/// assert_ne!(1.hour().fieldwise(), 60.minutes().fieldwise());
313/// // These also work since you only need one fieldwise span to do a compare:
314/// assert_ne!(1.hour(), 60.minutes().fieldwise());
315/// assert_ne!(1.hour().fieldwise(), 60.minutes());
316/// ```
317///
318/// This is because doing true comparisons requires arithmetic and a relative
319/// datetime in the general case, and which can fail due to overflow. This
320/// operation is provided via [`Span::compare`]:
321///
322/// ```
323/// use jiff::{civil::date, ToSpan};
324///
325/// // This doesn't need a reference date since it's only using time units.
326/// assert_eq!(1.hour().compare(60.minutes())?, std::cmp::Ordering::Equal);
327/// // But if you have calendar units, then you need a
328/// // reference date at minimum:
329/// assert!(1.month().compare(30.days()).is_err());
330/// assert_eq!(
331///     1.month().compare((30.days(), date(2025, 6, 1)))?,
332///     std::cmp::Ordering::Equal,
333/// );
334/// // A month can be a differing number of days!
335/// assert_eq!(
336///     1.month().compare((30.days(), date(2025, 7, 1)))?,
337///     std::cmp::Ordering::Greater,
338/// );
339///
340/// # Ok::<(), Box<dyn std::error::Error>>(())
341/// ```
342///
343/// # Arithmetic
344///
345/// Spans can be added or subtracted via [`Span::checked_add`] and
346/// [`Span::checked_sub`]:
347///
348/// ```
349/// use jiff::{Span, ToSpan};
350///
351/// let span1 = 2.hours().minutes(20);
352/// let span2: Span = "PT89400s".parse()?;
353/// assert_eq!(span1.checked_add(span2)?, 27.hours().minutes(10).fieldwise());
354///
355/// # Ok::<(), Box<dyn std::error::Error>>(())
356/// ```
357///
358/// When your spans involve calendar units, a relative datetime must be
359/// provided. (Because, for example, 1 month from March 1 is 31 days, but
360/// 1 month from April 1 is 30 days.)
361///
362/// ```
363/// use jiff::{civil::date, Span, ToSpan};
364///
365/// let span1 = 2.years().months(6).days(20);
366/// let span2 = 400.days();
367/// assert_eq!(
368///     span1.checked_add((span2, date(2023, 1, 1)))?,
369///     3.years().months(7).days(24).fieldwise(),
370/// );
371/// // The span changes when a leap year isn't included!
372/// assert_eq!(
373///     span1.checked_add((span2, date(2025, 1, 1)))?,
374///     3.years().months(7).days(23).fieldwise(),
375/// );
376///
377/// # Ok::<(), Box<dyn std::error::Error>>(())
378/// ```
379///
380/// # Rounding and balancing
381///
382/// Unlike datetimes, multiple distinct `Span` values can actually correspond
383/// to the same duration of time. For example, all of the following correspond
384/// to the same duration:
385///
386/// * 2 hours, 30 minutes
387/// * 150 minutes
388/// * 1 hour, 90 minutes
389///
390/// The first is said to be balanced. That is, its biggest non-zero unit cannot
391/// be expressed in an integer number of units bigger than hours. But the
392/// second is unbalanced because 150 minutes can be split up into hours and
393/// minutes. We call this sort of span a "top-heavy" unbalanced span. The third
394/// span is also unbalanced, but it's "bottom-heavy" and rarely used. Jiff
395/// will generally only produce spans of the first two types. In particular,
396/// most `Span` producing APIs accept a "largest" [`Unit`] parameter, and the
397/// result can be said to be a span "balanced up to the largest unit provided."
398///
399/// Balanced and unbalanced spans can be switched between as needed via
400/// the [`Span::round`] API by providing a rounding configuration with
401/// [`SpanRound::largest`]` set:
402///
403/// ```
404/// use jiff::{SpanRound, ToSpan, Unit};
405///
406/// let span = 2.hours().minutes(30);
407/// let unbalanced = span.round(SpanRound::new().largest(Unit::Minute))?;
408/// assert_eq!(unbalanced, 150.minutes().fieldwise());
409/// let balanced = unbalanced.round(SpanRound::new().largest(Unit::Hour))?;
410/// assert_eq!(balanced, 2.hours().minutes(30).fieldwise());
411///
412/// # Ok::<(), Box<dyn std::error::Error>>(())
413/// ```
414///
415/// Balancing can also be done as part of computing spans from two datetimes:
416///
417/// ```
418/// use jiff::{civil::date, ToSpan, Unit};
419///
420/// let zdt1 = date(2024, 7, 7).at(15, 23, 0, 0).in_tz("America/New_York")?;
421/// let zdt2 = date(2024, 11, 5).at(8, 0, 0, 0).in_tz("America/New_York")?;
422///
423/// // To make arithmetic reversible, the default largest unit for spans of
424/// // time computed from zoned datetimes is hours:
425/// assert_eq!(zdt1.until(&zdt2)?, 2_897.hour().minutes(37).fieldwise());
426/// // But we can ask for the span to be balanced up to years:
427/// assert_eq!(
428///     zdt1.until((Unit::Year, &zdt2))?,
429///     3.months().days(28).hours(16).minutes(37).fieldwise(),
430/// );
431///
432/// # Ok::<(), Box<dyn std::error::Error>>(())
433/// ```
434///
435/// While the [`Span::round`] API does balancing, it also, of course, does
436/// rounding as well. Rounding occurs when the smallest unit is set to
437/// something bigger than [`Unit::Nanosecond`]:
438///
439/// ```
440/// use jiff::{ToSpan, Unit};
441///
442/// let span = 2.hours().minutes(30);
443/// assert_eq!(span.round(Unit::Hour)?, 3.hours().fieldwise());
444///
445/// # Ok::<(), Box<dyn std::error::Error>>(())
446/// ```
447///
448/// When rounding spans with calendar units (years, months or weeks), then a
449/// relative datetime is required:
450///
451/// ```
452/// use jiff::{civil::date, SpanRound, ToSpan, Unit};
453///
454/// let span = 10.years().months(11);
455/// let options = SpanRound::new()
456///     .smallest(Unit::Year)
457///     .relative(date(2024, 1, 1));
458/// assert_eq!(span.round(options)?, 11.years().fieldwise());
459///
460/// # Ok::<(), Box<dyn std::error::Error>>(())
461/// ```
462///
463/// # Days are not always 24 hours!
464///
465/// That is, a `Span` is made up of uniform and non-uniform units.
466///
467/// A uniform unit is a unit whose elapsed duration is always the same.
468/// A non-uniform unit is a unit whose elapsed duration is not always the same.
469/// There are two things that can impact the length of a non-uniform unit:
470/// the calendar date and the time zone.
471///
472/// Years and months are always considered non-uniform units. For example,
473/// 1 month from `2024-04-01` is 30 days, while 1 month from `2024-05-01` is
474/// 31 days. Similarly for years because of leap years.
475///
476/// Hours, minutes, seconds, milliseconds, microseconds and nanoseconds are
477/// always considered uniform units.
478///
479/// Days are only considered non-uniform when in the presence of a zone aware
480/// datetime. A day can be more or less than 24 hours, and it can be balanced
481/// up and down, but only when a relative zoned datetime is given. This
482/// typically happens because of DST (daylight saving time), but can also occur
483/// because of other time zone transitions too.
484///
485/// ```
486/// use jiff::{civil::date, SpanRound, ToSpan, Unit};
487///
488/// // 2024-03-10 in New York was 23 hours long,
489/// // because of a jump to DST at 2am.
490/// let zdt = date(2024, 3, 9).at(21, 0, 0, 0).in_tz("America/New_York")?;
491/// // Goes from days to hours:
492/// assert_eq!(
493///     1.day().round(SpanRound::new().largest(Unit::Hour).relative(&zdt))?,
494///     23.hours().fieldwise(),
495/// );
496/// // Goes from hours to days:
497/// assert_eq!(
498///     23.hours().round(SpanRound::new().largest(Unit::Day).relative(&zdt))?,
499///     1.day().fieldwise(),
500/// );
501/// // 24 hours is more than 1 day starting at this time:
502/// assert_eq!(
503///     24.hours().round(SpanRound::new().largest(Unit::Day).relative(&zdt))?,
504///     1.day().hours(1).fieldwise(),
505/// );
506///
507/// # Ok::<(), Box<dyn std::error::Error>>(())
508/// ```
509///
510/// And similarly, days can be longer than 24 hours:
511///
512/// ```
513/// use jiff::{civil::date, SpanRound, ToSpan, Unit};
514///
515/// // 2024-11-03 in New York was 25 hours long,
516/// // because of a repetition of the 1 o'clock AM hour.
517/// let zdt = date(2024, 11, 2).at(21, 0, 0, 0).in_tz("America/New_York")?;
518/// // Goes from days to hours:
519/// assert_eq!(
520///     1.day().round(SpanRound::new().largest(Unit::Hour).relative(&zdt))?,
521///     25.hours().fieldwise(),
522/// );
523/// // Goes from hours to days:
524/// assert_eq!(
525///     25.hours().round(SpanRound::new().largest(Unit::Day).relative(&zdt))?,
526///     1.day().fieldwise(),
527/// );
528/// // 24 hours is less than 1 day starting at this time,
529/// // so it stays in units of hours even though we ask
530/// // for days (because 24 isn't enough hours to make
531/// // 1 day):
532/// assert_eq!(
533///     24.hours().round(SpanRound::new().largest(Unit::Day).relative(&zdt))?,
534///     24.hours().fieldwise(),
535/// );
536///
537/// # Ok::<(), Box<dyn std::error::Error>>(())
538/// ```
539///
540/// The APIs on `Span` will otherwise treat days as non-uniform unless a
541/// relative civil date is given, or there is an explicit opt-in to invariant
542/// 24-hour days. For example:
543///
544/// ```
545/// use jiff::{civil, SpanRelativeTo, ToSpan, Unit};
546///
547/// let span = 1.day();
548///
549/// // An error because days aren't always 24 hours:
550/// assert_eq!(
551///     span.total(Unit::Hour).unwrap_err().to_string(),
552///     "using unit 'day' in a span or configuration requires that either \
553///      a relative reference time be given or \
554///      `jiff::SpanRelativeTo::days_are_24_hours()` is used to indicate \
555///      invariant 24-hour days, but neither were provided",
556/// );
557/// // Opt into invariant 24 hour days without a relative date:
558/// let marker = SpanRelativeTo::days_are_24_hours();
559/// let hours = span.total((Unit::Hour, marker))?;
560/// assert_eq!(hours, 24.0);
561/// // Or use a relative civil date, and all days are 24 hours:
562/// let date = civil::date(2020, 1, 1);
563/// let hours = span.total((Unit::Hour, date))?;
564/// assert_eq!(hours, 24.0);
565///
566/// # Ok::<(), Box<dyn std::error::Error>>(())
567/// ```
568///
569/// In Jiff, all weeks are 7 days. And generally speaking, weeks only appear in
570/// a `Span` if they were explicitly put there by the caller or if they were
571/// explicitly requested by the caller in an API. For example:
572///
573/// ```
574/// use jiff::{civil::date, ToSpan, Unit};
575///
576/// let dt1 = date(2024, 1, 1).at(0, 0, 0, 0);
577/// let dt2 = date(2024, 7, 16).at(0, 0, 0, 0);
578/// // Default units go up to days.
579/// assert_eq!(dt1.until(dt2)?, 197.days().fieldwise());
580/// // No weeks, even though we requested up to year.
581/// assert_eq!(dt1.until((Unit::Year, dt2))?, 6.months().days(15).fieldwise());
582/// // We get weeks only when we ask for them.
583/// assert_eq!(dt1.until((Unit::Week, dt2))?, 28.weeks().days(1).fieldwise());
584///
585/// # Ok::<(), Box<dyn std::error::Error>>(())
586/// ```
587///
588/// # Integration with [`std::time::Duration`] and [`SignedDuration`]
589///
590/// While Jiff primarily uses a `Span` for doing arithmetic on datetimes,
591/// one can convert between a `Span` and a [`std::time::Duration`] or a
592/// [`SignedDuration`]. The main difference between them is that a `Span`
593/// always keeps tracks of its individual units, and a `Span` can represent
594/// non-uniform units like months. In contrast, `Duration` and `SignedDuration`
595/// are always an exact elapsed amount of time. They don't distinguish between
596/// `120 seconds` and `2 minutes`. And they can't represent the concept of
597/// "months" because a month doesn't have a single fixed amount of time.
598///
599/// However, an exact duration is still useful in certain contexts. Beyond
600/// that, it serves as an interoperability point due to the presence of an
601/// unsigned exact duration type in the standard library. Because of that,
602/// Jiff provides `TryFrom` trait implementations for converting to and from a
603/// `std::time::Duration` (and, of course, a `SignedDuration`). For example, to
604/// convert from a `std::time::Duration` to a `Span`:
605///
606/// ```
607/// use std::time::Duration;
608///
609/// use jiff::{Span, ToSpan};
610///
611/// let duration = Duration::new(86_400, 123_456_789);
612/// let span = Span::try_from(duration)?;
613/// // A duration-to-span conversion always results in a span with
614/// // non-zero units no bigger than seconds.
615/// assert_eq!(
616///     span.fieldwise(),
617///     86_400.seconds().milliseconds(123).microseconds(456).nanoseconds(789),
618/// );
619///
620/// // Note that the conversion is fallible! For example:
621/// assert!(Span::try_from(Duration::from_secs(u64::MAX)).is_err());
622/// // At present, a Jiff `Span` can only represent a range of time equal to
623/// // the range of time expressible via minimum and maximum Jiff timestamps.
624/// // Which is roughly -9999-01-01 to 9999-12-31, or ~20,000 years.
625/// assert!(Span::try_from(Duration::from_secs(999_999_999_999)).is_err());
626///
627/// # Ok::<(), Box<dyn std::error::Error>>(())
628/// ```
629///
630/// And to convert from a `Span` to a `std::time::Duration`:
631///
632/// ```
633/// use std::time::Duration;
634///
635/// use jiff::{Span, ToSpan};
636///
637/// let span = 86_400.seconds()
638///     .milliseconds(123)
639///     .microseconds(456)
640///     .nanoseconds(789);
641/// let duration = Duration::try_from(span)?;
642/// assert_eq!(duration, Duration::new(86_400, 123_456_789));
643///
644/// # Ok::<(), Box<dyn std::error::Error>>(())
645/// ```
646///
647/// Note that an error will occur when converting a `Span` to a
648/// `std::time::Duration` using the `TryFrom` trait implementation with units
649/// bigger than hours:
650///
651/// ```
652/// use std::time::Duration;
653///
654/// use jiff::ToSpan;
655///
656/// let span = 2.days().hours(10);
657/// assert_eq!(
658///     Duration::try_from(span).unwrap_err().to_string(),
659///     "failed to convert span to duration without relative datetime \
660///      (must use `jiff::Span::to_duration` instead): using unit 'day' \
661///      in a span or configuration requires that either a relative \
662///      reference time be given or \
663///      `jiff::SpanRelativeTo::days_are_24_hours()` is used to indicate \
664///      invariant 24-hour days, but neither were provided",
665/// );
666///
667/// # Ok::<(), Box<dyn std::error::Error>>(())
668/// ```
669///
670/// Similar code can be written for `SignedDuration` as well.
671///
672/// If you need to convert such spans, then as the error suggests, you'll need
673/// to use [`Span::to_duration`] with a relative date.
674///
675/// And note that since a `Span` is signed and a `std::time::Duration` is unsigned,
676/// converting a negative `Span` to `std::time::Duration` will always fail. One can use
677/// [`Span::signum`] to get the sign of the span and [`Span::abs`] to make the
678/// span positive before converting it to a `Duration`:
679///
680/// ```
681/// use std::time::Duration;
682///
683/// use jiff::{Span, ToSpan};
684///
685/// let span = -86_400.seconds().nanoseconds(1);
686/// let (sign, duration) = (span.signum(), Duration::try_from(span.abs())?);
687/// assert_eq!((sign, duration), (-1, Duration::new(86_400, 1)));
688///
689/// # Ok::<(), Box<dyn std::error::Error>>(())
690/// ```
691///
692/// Or, consider using Jiff's own [`SignedDuration`] instead:
693///
694/// ```
695/// # // See: https://github.com/rust-lang/rust/pull/121364
696/// # #![allow(unknown_lints, ambiguous_negative_literals)]
697/// use jiff::{SignedDuration, Span, ToSpan};
698///
699/// let span = -86_400.seconds().nanoseconds(1);
700/// let duration = SignedDuration::try_from(span)?;
701/// assert_eq!(duration, SignedDuration::new(-86_400, -1));
702///
703/// # Ok::<(), Box<dyn std::error::Error>>(())
704/// ```
705#[derive(Clone, Copy, Default)]
706pub struct Span {
707    sign: b::Sign,
708    units: UnitSet,
709    years: i16,
710    months: i32,
711    weeks: i32,
712    days: i32,
713    hours: i32,
714    minutes: i64,
715    seconds: i64,
716    milliseconds: i64,
717    microseconds: i64,
718    nanoseconds: i64,
719}
720
721/// Infallible routines for setting units on a `Span`.
722///
723/// These are useful when the units are determined by the programmer or when
724/// they have been validated elsewhere. In general, use these routines when
725/// constructing an invalid `Span` should be considered a bug in the program.
726impl Span {
727    /// Creates a new span representing a zero duration. That is, a duration
728    /// in which no time has passed.
729    pub fn new() -> Span {
730        Span::default()
731    }
732
733    /// Set the number of years on this span. The value may be negative.
734    ///
735    /// The fallible version of this method is [`Span::try_years`].
736    ///
737    /// # Panics
738    ///
739    /// This panics when the number of years is too small or too big.
740    /// The minimum value is `-19,998`.
741    /// The maximum value is `19,998`.
742    #[inline]
743    pub fn years<I: Into<i64>>(self, years: I) -> Span {
744        self.try_years(years).expect("value for years is out of bounds")
745    }
746
747    /// Set the number of months on this span. The value may be negative.
748    ///
749    /// The fallible version of this method is [`Span::try_months`].
750    ///
751    /// # Panics
752    ///
753    /// This panics when the number of months is too small or too big.
754    /// The minimum value is `-239,976`.
755    /// The maximum value is `239,976`.
756    #[inline]
757    pub fn months<I: Into<i64>>(self, months: I) -> Span {
758        self.try_months(months).expect("value for months is out of bounds")
759    }
760
761    /// Set the number of weeks on this span. The value may be negative.
762    ///
763    /// The fallible version of this method is [`Span::try_weeks`].
764    ///
765    /// # Panics
766    ///
767    /// This panics when the number of weeks is too small or too big.
768    /// The minimum value is `-1,043,497`.
769    /// The maximum value is `1_043_497`.
770    #[inline]
771    pub fn weeks<I: Into<i64>>(self, weeks: I) -> Span {
772        self.try_weeks(weeks).expect("value for weeks is out of bounds")
773    }
774
775    /// Set the number of days on this span. The value may be negative.
776    ///
777    /// The fallible version of this method is [`Span::try_days`].
778    ///
779    /// # Panics
780    ///
781    /// This panics when the number of days is too small or too big.
782    /// The minimum value is `-7,304,484`.
783    /// The maximum value is `7,304,484`.
784    #[inline]
785    pub fn days<I: Into<i64>>(self, days: I) -> Span {
786        self.try_days(days).expect("value for days is out of bounds")
787    }
788
789    /// Set the number of hours on this span. The value may be negative.
790    ///
791    /// The fallible version of this method is [`Span::try_hours`].
792    ///
793    /// # Panics
794    ///
795    /// This panics when the number of hours is too small or too big.
796    /// The minimum value is `-175,307,616`.
797    /// The maximum value is `175,307,616`.
798    #[inline]
799    pub fn hours<I: Into<i64>>(self, hours: I) -> Span {
800        self.try_hours(hours).expect("value for hours is out of bounds")
801    }
802
803    /// Set the number of minutes on this span. The value may be negative.
804    ///
805    /// The fallible version of this method is [`Span::try_minutes`].
806    ///
807    /// # Panics
808    ///
809    /// This panics when the number of minutes is too small or too big.
810    /// The minimum value is `-10,518,456,960`.
811    /// The maximum value is `10,518,456,960`.
812    #[inline]
813    pub fn minutes<I: Into<i64>>(self, minutes: I) -> Span {
814        self.try_minutes(minutes).expect("value for minutes is out of bounds")
815    }
816
817    /// Set the number of seconds on this span. The value may be negative.
818    ///
819    /// The fallible version of this method is [`Span::try_seconds`].
820    ///
821    /// # Panics
822    ///
823    /// This panics when the number of seconds is too small or too big.
824    /// The minimum value is `-631,107,417,600`.
825    /// The maximum value is `631,107,417,600`.
826    #[inline]
827    pub fn seconds<I: Into<i64>>(self, seconds: I) -> Span {
828        self.try_seconds(seconds).expect("value for seconds is out of bounds")
829    }
830
831    /// Set the number of milliseconds on this span. The value may be negative.
832    ///
833    /// The fallible version of this method is [`Span::try_milliseconds`].
834    ///
835    /// # Panics
836    ///
837    /// This panics when the number of milliseconds is too small or too big.
838    /// The minimum value is `-631,107,417,600,000`.
839    /// The maximum value is `631,107,417,600,000`.
840    #[inline]
841    pub fn milliseconds<I: Into<i64>>(self, milliseconds: I) -> Span {
842        self.try_milliseconds(milliseconds)
843            .expect("value for milliseconds is out of bounds")
844    }
845
846    /// Set the number of microseconds on this span. The value may be negative.
847    ///
848    /// The fallible version of this method is [`Span::try_microseconds`].
849    ///
850    /// # Panics
851    ///
852    /// This panics when the number of microseconds is too small or too big.
853    /// The minimum value is `-631,107,417,600,000,000`.
854    /// The maximum value is `631,107,417,600,000,000`.
855    #[inline]
856    pub fn microseconds<I: Into<i64>>(self, microseconds: I) -> Span {
857        self.try_microseconds(microseconds)
858            .expect("value for microseconds is out of bounds")
859    }
860
861    /// Set the number of nanoseconds on this span. The value may be negative.
862    ///
863    /// Note that unlike all other units, a 64-bit integer number of
864    /// nanoseconds is not big enough to represent all possible spans between
865    /// all possible datetimes supported by Jiff. This means, for example, that
866    /// computing a span between two datetimes that are far enough apart _and_
867    /// requesting a largest unit of [`Unit::Nanosecond`], might return an
868    /// error due to lack of precision.
869    ///
870    /// The fallible version of this method is [`Span::try_nanoseconds`].
871    ///
872    /// # Panics
873    ///
874    /// This panics when the number of nanoseconds is too small or too big.
875    /// The minimum value is `-9,223,372,036,854,775,807`.
876    /// The maximum value is `9,223,372,036,854,775,807`.
877    #[inline]
878    pub fn nanoseconds<I: Into<i64>>(self, nanoseconds: I) -> Span {
879        self.try_nanoseconds(nanoseconds)
880            .expect("value for nanoseconds is out of bounds")
881    }
882}
883
884/// Fallible methods for setting units on a `Span`.
885///
886/// These methods are useful when the span is made up of user provided values
887/// that may not be in range.
888impl Span {
889    /// Set the number of years on this span. The value may be negative.
890    ///
891    /// The panicking version of this method is [`Span::years`].
892    ///
893    /// # Errors
894    ///
895    /// This returns an error when the number of years is too small or too big.
896    /// The minimum value is `-19,998`.
897    /// The maximum value is `19,998`.
898    #[inline]
899    pub fn try_years<I: Into<i64>>(self, years: I) -> Result<Span, Error> {
900        let years = b::SpanYears::check(years.into())?;
901        let mut span = self.years_unchecked(years.abs());
902        span.sign = self.resign(years, &span);
903        Ok(span)
904    }
905
906    /// Set the number of months on this span. The value may be negative.
907    ///
908    /// The panicking version of this method is [`Span::months`].
909    ///
910    /// # Errors
911    ///
912    /// This returns an error when the number of months is too small or too big.
913    /// The minimum value is `-239,976`.
914    /// The maximum value is `239,976`.
915    #[inline]
916    pub fn try_months<I: Into<i64>>(self, months: I) -> Result<Span, Error> {
917        let months = b::SpanMonths::check(months.into())?;
918        let mut span = self.months_unchecked(months.abs());
919        span.sign = self.resign(months, &span);
920        Ok(span)
921    }
922
923    /// Set the number of weeks on this span. The value may be negative.
924    ///
925    /// The panicking version of this method is [`Span::weeks`].
926    ///
927    /// # Errors
928    ///
929    /// This returns an error when the number of weeks is too small or too big.
930    /// The minimum value is `-1,043,497`.
931    /// The maximum value is `1_043_497`.
932    #[inline]
933    pub fn try_weeks<I: Into<i64>>(self, weeks: I) -> Result<Span, Error> {
934        let weeks = b::SpanWeeks::check(weeks.into())?;
935        let mut span = self.weeks_unchecked(weeks.abs());
936        span.sign = self.resign(weeks, &span);
937        Ok(span)
938    }
939
940    /// Set the number of days on this span. The value may be negative.
941    ///
942    /// The panicking version of this method is [`Span::days`].
943    ///
944    /// # Errors
945    ///
946    /// This returns an error when the number of days is too small or too big.
947    /// The minimum value is `-7,304,484`.
948    /// The maximum value is `7,304,484`.
949    #[inline]
950    pub fn try_days<I: Into<i64>>(self, days: I) -> Result<Span, Error> {
951        let days = b::SpanDays::check(days.into())?;
952        let mut span = self.days_unchecked(days.abs());
953        span.sign = self.resign(days, &span);
954        Ok(span)
955    }
956
957    /// Set the number of hours on this span. The value may be negative.
958    ///
959    /// The panicking version of this method is [`Span::hours`].
960    ///
961    /// # Errors
962    ///
963    /// This returns an error when the number of hours is too small or too big.
964    /// The minimum value is `-175,307,616`.
965    /// The maximum value is `175,307,616`.
966    #[inline]
967    pub fn try_hours<I: Into<i64>>(self, hours: I) -> Result<Span, Error> {
968        let hours = b::SpanHours::check(hours.into())?;
969        let mut span = self.hours_unchecked(hours.abs());
970        span.sign = self.resign(hours, &span);
971        Ok(span)
972    }
973
974    /// Set the number of minutes on this span. The value may be negative.
975    ///
976    /// The panicking version of this method is [`Span::minutes`].
977    ///
978    /// # Errors
979    ///
980    /// This returns an error when the number of minutes is too small or too big.
981    /// The minimum value is `-10,518,456,960`.
982    /// The maximum value is `10,518,456,960`.
983    #[inline]
984    pub fn try_minutes<I: Into<i64>>(self, minutes: I) -> Result<Span, Error> {
985        let minutes = b::SpanMinutes::check(minutes.into())?;
986        let mut span = self.minutes_unchecked(minutes.abs());
987        span.sign = self.resign(minutes, &span);
988        Ok(span)
989    }
990
991    /// Set the number of seconds on this span. The value may be negative.
992    ///
993    /// The panicking version of this method is [`Span::seconds`].
994    ///
995    /// # Errors
996    ///
997    /// This returns an error when the number of seconds is too small or too big.
998    /// The minimum value is `-631,107,417,600`.
999    /// The maximum value is `631,107,417,600`.
1000    #[inline]
1001    pub fn try_seconds<I: Into<i64>>(self, seconds: I) -> Result<Span, Error> {
1002        let seconds = b::SpanSeconds::check(seconds.into())?;
1003        let mut span = self.seconds_unchecked(seconds.abs());
1004        span.sign = self.resign(seconds, &span);
1005        Ok(span)
1006    }
1007
1008    /// Set the number of milliseconds on this span. The value may be negative.
1009    ///
1010    /// The panicking version of this method is [`Span::milliseconds`].
1011    ///
1012    /// # Errors
1013    ///
1014    /// This returns an error when the number of milliseconds is too small or
1015    /// too big.
1016    /// The minimum value is `-631,107,417,600,000`.
1017    /// The maximum value is `631,107,417,600,000`.
1018    #[inline]
1019    pub fn try_milliseconds<I: Into<i64>>(
1020        self,
1021        milliseconds: I,
1022    ) -> Result<Span, Error> {
1023        let milliseconds = b::SpanMilliseconds::check(milliseconds.into())?;
1024        let mut span = self.milliseconds_unchecked(milliseconds.abs());
1025        span.sign = self.resign(milliseconds, &span);
1026        Ok(span)
1027    }
1028
1029    /// Set the number of microseconds on this span. The value may be negative.
1030    ///
1031    /// The panicking version of this method is [`Span::microseconds`].
1032    ///
1033    /// # Errors
1034    ///
1035    /// This returns an error when the number of microseconds is too small or
1036    /// too big.
1037    /// The minimum value is `-631,107,417,600,000,000`.
1038    /// The maximum value is `631,107,417,600,000,000`.
1039    #[inline]
1040    pub fn try_microseconds<I: Into<i64>>(
1041        self,
1042        microseconds: I,
1043    ) -> Result<Span, Error> {
1044        let microseconds = b::SpanMicroseconds::check(microseconds.into())?;
1045        let mut span = self.microseconds_unchecked(microseconds.abs());
1046        span.sign = self.resign(microseconds, &span);
1047        Ok(span)
1048    }
1049
1050    /// Set the number of nanoseconds on this span. The value may be negative.
1051    ///
1052    /// Note that unlike all other units, a 64-bit integer number of
1053    /// nanoseconds is not big enough to represent all possible spans between
1054    /// all possible datetimes supported by Jiff. This means, for example, that
1055    /// computing a span between two datetimes that are far enough apart _and_
1056    /// requesting a largest unit of [`Unit::Nanosecond`], might return an
1057    /// error due to lack of precision.
1058    ///
1059    /// The panicking version of this method is [`Span::nanoseconds`].
1060    ///
1061    /// # Errors
1062    ///
1063    /// This returns an error when the number of nanoseconds is too small or
1064    /// too big.
1065    /// The minimum value is `-9,223,372,036,854,775,807`.
1066    /// The maximum value is `9,223,372,036,854,775,807`.
1067    #[inline]
1068    pub fn try_nanoseconds<I: Into<i64>>(
1069        self,
1070        nanoseconds: I,
1071    ) -> Result<Span, Error> {
1072        let nanoseconds = b::SpanNanoseconds::check(nanoseconds.into())?;
1073        let mut span = self.nanoseconds_unchecked(nanoseconds.abs());
1074        span.sign = self.resign(nanoseconds, &span);
1075        Ok(span)
1076    }
1077}
1078
1079/// Routines for accessing the individual units in a `Span`.
1080impl Span {
1081    /// Returns the number of year units in this span.
1082    ///
1083    /// Note that this is not the same as the total number of years in the
1084    /// span. To get that, you'll need to use either [`Span::round`] or
1085    /// [`Span::total`].
1086    ///
1087    /// # Example
1088    ///
1089    /// ```
1090    /// use jiff::{civil::date, ToSpan, Unit};
1091    ///
1092    /// let span = 3.years().months(24);
1093    /// assert_eq!(3, span.get_years());
1094    /// assert_eq!(5.0, span.total((Unit::Year, date(2024, 1, 1)))?);
1095    ///
1096    /// # Ok::<(), Box<dyn std::error::Error>>(())
1097    /// ```
1098    #[inline]
1099    pub fn get_years(&self) -> i16 {
1100        self.sign * self.years
1101    }
1102
1103    /// Returns the number of month units in this span.
1104    ///
1105    /// Note that this is not the same as the total number of months in the
1106    /// span. To get that, you'll need to use either [`Span::round`] or
1107    /// [`Span::total`].
1108    ///
1109    /// # Example
1110    ///
1111    /// ```
1112    /// use jiff::{civil::date, ToSpan, Unit};
1113    ///
1114    /// let span = 7.months().days(59);
1115    /// assert_eq!(7, span.get_months());
1116    /// assert_eq!(9.0, span.total((Unit::Month, date(2022, 6, 1)))?);
1117    ///
1118    /// # Ok::<(), Box<dyn std::error::Error>>(())
1119    /// ```
1120    #[inline]
1121    pub fn get_months(&self) -> i32 {
1122        self.sign * self.months
1123    }
1124
1125    /// Returns the number of week units in this span.
1126    ///
1127    /// Note that this is not the same as the total number of weeks in the
1128    /// span. To get that, you'll need to use either [`Span::round`] or
1129    /// [`Span::total`].
1130    ///
1131    /// # Example
1132    ///
1133    /// ```
1134    /// use jiff::{civil::date, ToSpan, Unit};
1135    ///
1136    /// let span = 3.weeks().days(14);
1137    /// assert_eq!(3, span.get_weeks());
1138    /// assert_eq!(5.0, span.total((Unit::Week, date(2024, 1, 1)))?);
1139    ///
1140    /// # Ok::<(), Box<dyn std::error::Error>>(())
1141    /// ```
1142    #[inline]
1143    pub fn get_weeks(&self) -> i32 {
1144        self.sign * self.weeks
1145    }
1146
1147    /// Returns the number of day units in this span.
1148    ///
1149    /// Note that this is not the same as the total number of days in the
1150    /// span. To get that, you'll need to use either [`Span::round`] or
1151    /// [`Span::total`].
1152    ///
1153    /// # Example
1154    ///
1155    /// ```
1156    /// use jiff::{ToSpan, Unit, Zoned};
1157    ///
1158    /// let span = 3.days().hours(47);
1159    /// assert_eq!(3, span.get_days());
1160    ///
1161    /// let zdt: Zoned = "2024-03-07[America/New_York]".parse()?;
1162    /// assert_eq!(5.0, span.total((Unit::Day, &zdt))?);
1163    ///
1164    /// # Ok::<(), Box<dyn std::error::Error>>(())
1165    /// ```
1166    #[inline]
1167    pub fn get_days(&self) -> i32 {
1168        self.sign * self.days
1169    }
1170
1171    /// Returns the number of hour units in this span.
1172    ///
1173    /// Note that this is not the same as the total number of hours in the
1174    /// span. To get that, you'll need to use either [`Span::round`] or
1175    /// [`Span::total`].
1176    ///
1177    /// # Example
1178    ///
1179    /// ```
1180    /// use jiff::{ToSpan, Unit};
1181    ///
1182    /// let span = 3.hours().minutes(120);
1183    /// assert_eq!(3, span.get_hours());
1184    /// assert_eq!(5.0, span.total(Unit::Hour)?);
1185    ///
1186    /// # Ok::<(), Box<dyn std::error::Error>>(())
1187    /// ```
1188    #[inline]
1189    pub fn get_hours(&self) -> i32 {
1190        self.sign * self.hours
1191    }
1192
1193    /// Returns the number of minute units in this span.
1194    ///
1195    /// Note that this is not the same as the total number of minutes in the
1196    /// span. To get that, you'll need to use either [`Span::round`] or
1197    /// [`Span::total`].
1198    ///
1199    /// # Example
1200    ///
1201    /// ```
1202    /// use jiff::{ToSpan, Unit};
1203    ///
1204    /// let span = 3.minutes().seconds(120);
1205    /// assert_eq!(3, span.get_minutes());
1206    /// assert_eq!(5.0, span.total(Unit::Minute)?);
1207    ///
1208    /// # Ok::<(), Box<dyn std::error::Error>>(())
1209    /// ```
1210    #[inline]
1211    pub fn get_minutes(&self) -> i64 {
1212        self.sign * self.minutes
1213    }
1214
1215    /// Returns the number of second units in this span.
1216    ///
1217    /// Note that this is not the same as the total number of seconds in the
1218    /// span. To get that, you'll need to use either [`Span::round`] or
1219    /// [`Span::total`].
1220    ///
1221    /// # Example
1222    ///
1223    /// ```
1224    /// use jiff::{ToSpan, Unit};
1225    ///
1226    /// let span = 3.seconds().milliseconds(2_000);
1227    /// assert_eq!(3, span.get_seconds());
1228    /// assert_eq!(5.0, span.total(Unit::Second)?);
1229    ///
1230    /// # Ok::<(), Box<dyn std::error::Error>>(())
1231    /// ```
1232    #[inline]
1233    pub fn get_seconds(&self) -> i64 {
1234        self.sign * self.seconds
1235    }
1236
1237    /// Returns the number of millisecond units in this span.
1238    ///
1239    /// Note that this is not the same as the total number of milliseconds in
1240    /// the span. To get that, you'll need to use either [`Span::round`] or
1241    /// [`Span::total`].
1242    ///
1243    /// # Example
1244    ///
1245    /// ```
1246    /// use jiff::{ToSpan, Unit};
1247    ///
1248    /// let span = 3.milliseconds().microseconds(2_000);
1249    /// assert_eq!(3, span.get_milliseconds());
1250    /// assert_eq!(5.0, span.total(Unit::Millisecond)?);
1251    ///
1252    /// # Ok::<(), Box<dyn std::error::Error>>(())
1253    /// ```
1254    #[inline]
1255    pub fn get_milliseconds(&self) -> i64 {
1256        self.sign * self.milliseconds
1257    }
1258
1259    /// Returns the number of microsecond units in this span.
1260    ///
1261    /// Note that this is not the same as the total number of microseconds in
1262    /// the span. To get that, you'll need to use either [`Span::round`] or
1263    /// [`Span::total`].
1264    ///
1265    /// # Example
1266    ///
1267    /// ```
1268    /// use jiff::{ToSpan, Unit};
1269    ///
1270    /// let span = 3.microseconds().nanoseconds(2_000);
1271    /// assert_eq!(3, span.get_microseconds());
1272    /// // Floating point precision may provide imprecise results.
1273    /// assert_eq!(5.0, span.total(Unit::Microsecond)?);
1274    ///
1275    /// # Ok::<(), Box<dyn std::error::Error>>(())
1276    /// ```
1277    #[inline]
1278    pub fn get_microseconds(&self) -> i64 {
1279        self.sign * self.microseconds
1280    }
1281
1282    /// Returns the number of nanosecond units in this span.
1283    ///
1284    /// Note that this is not the same as the total number of nanoseconds in
1285    /// the span. To get that, you'll need to use either [`Span::round`] or
1286    /// [`Span::total`].
1287    ///
1288    /// # Example
1289    ///
1290    /// ```
1291    /// use jiff::{ToSpan, Unit};
1292    ///
1293    /// let span = 3.microseconds().nanoseconds(2_000);
1294    /// assert_eq!(2_000, span.get_nanoseconds());
1295    /// assert_eq!(5_000.0, span.total(Unit::Nanosecond)?);
1296    ///
1297    /// # Ok::<(), Box<dyn std::error::Error>>(())
1298    /// ```
1299    #[inline]
1300    pub fn get_nanoseconds(&self) -> i64 {
1301        self.sign * self.nanoseconds
1302    }
1303}
1304
1305/// Routines for manipulating, comparing and inspecting `Span` values.
1306impl Span {
1307    /// Returns a new span that is the absolute value of this span.
1308    ///
1309    /// If this span is zero or positive, then this is a no-op.
1310    ///
1311    /// # Example
1312    ///
1313    /// ```
1314    /// use jiff::ToSpan;
1315    ///
1316    /// let span = -100.seconds();
1317    /// assert_eq!(span.to_string(), "-PT100S");
1318    /// let span = span.abs();
1319    /// assert_eq!(span.to_string(), "PT100S");
1320    /// ```
1321    #[inline]
1322    pub fn abs(self) -> Span {
1323        if self.is_zero() {
1324            return self;
1325        }
1326        Span { sign: b::Sign::Positive, ..self }
1327    }
1328
1329    /// Returns a new span that negates this span.
1330    ///
1331    /// If this span is zero, then this is a no-op. If this span is negative,
1332    /// then the returned span is positive. If this span is positive, then
1333    /// the returned span is negative.
1334    ///
1335    /// # Example
1336    ///
1337    /// ```
1338    /// use jiff::ToSpan;
1339    ///
1340    /// let span = 100.days();
1341    /// assert_eq!(span.to_string(), "P100D");
1342    /// let span = span.negate();
1343    /// assert_eq!(span.to_string(), "-P100D");
1344    /// ```
1345    ///
1346    /// # Example: available via the negation operator
1347    ///
1348    /// This routine can also be used via `-`:
1349    ///
1350    /// ```
1351    /// use jiff::ToSpan;
1352    ///
1353    /// let span = 100.days();
1354    /// assert_eq!(span.to_string(), "P100D");
1355    /// let span = -span;
1356    /// assert_eq!(span.to_string(), "-P100D");
1357    /// ```
1358    #[inline]
1359    pub fn negate(self) -> Span {
1360        Span { sign: -self.sign, ..self }
1361    }
1362
1363    /// Returns the "sign number" or "signum" of this span.
1364    ///
1365    /// The number returned is `-1` when this span is negative,
1366    /// `0` when this span is zero and `1` when this span is positive.
1367    #[inline]
1368    pub fn signum(self) -> i8 {
1369        self.sign.signum()
1370    }
1371
1372    /// Returns true if and only if this span is positive.
1373    ///
1374    /// This returns false when the span is zero or negative.
1375    ///
1376    /// # Example
1377    ///
1378    /// ```
1379    /// use jiff::ToSpan;
1380    ///
1381    /// assert!(!2.months().is_negative());
1382    /// assert!((-2.months()).is_negative());
1383    /// ```
1384    #[inline]
1385    pub fn is_positive(self) -> bool {
1386        self.get_sign().is_positive()
1387    }
1388
1389    /// Returns true if and only if this span is negative.
1390    ///
1391    /// This returns false when the span is zero or positive.
1392    ///
1393    /// # Example
1394    ///
1395    /// ```
1396    /// use jiff::ToSpan;
1397    ///
1398    /// assert!(!2.months().is_negative());
1399    /// assert!((-2.months()).is_negative());
1400    /// ```
1401    #[inline]
1402    pub fn is_negative(self) -> bool {
1403        self.get_sign().is_negative()
1404    }
1405
1406    /// Returns true if and only if every field in this span is set to `0`.
1407    ///
1408    /// # Example
1409    ///
1410    /// ```
1411    /// use jiff::{Span, ToSpan};
1412    ///
1413    /// assert!(Span::new().is_zero());
1414    /// assert!(Span::default().is_zero());
1415    /// assert!(0.seconds().is_zero());
1416    /// assert!(!0.seconds().seconds(1).is_zero());
1417    /// assert!(0.seconds().seconds(1).seconds(0).is_zero());
1418    /// ```
1419    #[inline]
1420    pub fn is_zero(self) -> bool {
1421        self.sign.is_zero()
1422    }
1423
1424    /// Returns this `Span` as a value with a type that implements the
1425    /// `Hash`, `Eq` and `PartialEq` traits in a fieldwise fashion.
1426    ///
1427    /// A `SpanFieldwise` is meant to make it easy to compare two spans in a
1428    /// "dumb" way based purely on its unit values. This is distinct from
1429    /// something like [`Span::compare`] that performs a comparison on the
1430    /// actual elapsed time of two spans.
1431    ///
1432    /// It is generally discouraged to use `SpanFieldwise` since spans that
1433    /// represent an equivalent elapsed amount of time may compare unequal.
1434    /// However, in some cases, it is useful to be able to assert precise
1435    /// field values. For example, Jiff itself makes heavy use of fieldwise
1436    /// comparisons for tests.
1437    ///
1438    /// # Example: the difference between `SpanFieldwise` and `Span::compare`
1439    ///
1440    /// In short, `SpanFieldwise` considers `2 hours` and `120 minutes` to be
1441    /// distinct values, but `Span::compare` considers them to be equivalent:
1442    ///
1443    /// ```
1444    /// use std::cmp::Ordering;
1445    /// use jiff::ToSpan;
1446    ///
1447    /// assert_ne!(120.minutes().fieldwise(), 2.hours().fieldwise());
1448    /// assert_eq!(120.minutes().compare(2.hours())?, Ordering::Equal);
1449    ///
1450    /// # Ok::<(), Box<dyn std::error::Error>>(())
1451    /// ```
1452    #[inline]
1453    pub fn fieldwise(self) -> SpanFieldwise {
1454        SpanFieldwise(self)
1455    }
1456
1457    /// Multiplies each field in this span by a given integer.
1458    ///
1459    /// If this would cause any individual field in this span to overflow, then
1460    /// this returns an error.
1461    ///
1462    /// # Example
1463    ///
1464    /// ```
1465    /// use jiff::ToSpan;
1466    ///
1467    /// let span = 4.days().seconds(8);
1468    /// assert_eq!(span.checked_mul(2)?, 8.days().seconds(16).fieldwise());
1469    /// assert_eq!(span.checked_mul(-3)?, -12.days().seconds(24).fieldwise());
1470    /// // Notice that no re-balancing is done. It's "just" multiplication.
1471    /// assert_eq!(span.checked_mul(10)?, 40.days().seconds(80).fieldwise());
1472    ///
1473    /// let span = 10_000.years();
1474    /// // too big!
1475    /// assert!(span.checked_mul(3).is_err());
1476    ///
1477    /// # Ok::<(), Box<dyn std::error::Error>>(())
1478    /// ```
1479    ///
1480    /// # Example: available via the multiplication operator
1481    ///
1482    /// This method can be used via the `*` operator. Note though that a panic
1483    /// happens on overflow.
1484    ///
1485    /// ```
1486    /// use jiff::ToSpan;
1487    ///
1488    /// let span = 4.days().seconds(8);
1489    /// assert_eq!(span * 2, 8.days().seconds(16).fieldwise());
1490    /// assert_eq!(2 * span, 8.days().seconds(16).fieldwise());
1491    /// assert_eq!(span * -3, -12.days().seconds(24).fieldwise());
1492    /// assert_eq!(-3 * span, -12.days().seconds(24).fieldwise());
1493    ///
1494    /// # Ok::<(), Box<dyn std::error::Error>>(())
1495    /// ```
1496    #[inline]
1497    pub fn checked_mul(mut self, rhs: i64) -> Result<Span, Error> {
1498        if rhs == 0 {
1499            return Ok(Span::default());
1500        } else if rhs == 1 {
1501            return Ok(self);
1502        }
1503        self.sign = self.sign * b::Sign::from(rhs);
1504        // This can only fail when `rhs == i64::MIN`, which is out of bounds
1505        // for all possible span units (including nanoseconds).
1506        let rhs = rhs.checked_abs().ok_or_else(b::SpanMultiple::error)?;
1507        // This is all somewhat odd, but since each of our span fields uses
1508        // a different primitive representation and range of allowed values,
1509        // we only seek to perform multiplications when they will actually
1510        // do something. Otherwise, we risk multiplying the mins/maxs of a
1511        // ranged integer and causing a spurious panic. Basically, the idea
1512        // here is the allowable values for our multiple depend on what we're
1513        // actually going to multiply with it. If our span has non-zero years,
1514        // then our multiple can't exceed the bounds of `SpanYears`, otherwise
1515        // it is guaranteed to overflow.
1516        if self.years != 0 {
1517            let rhs = b::SpanYears::check(rhs)?;
1518            self.years = b::SpanYears::checked_mul(self.years, rhs)?;
1519        }
1520        if self.months != 0 {
1521            let rhs = b::SpanMonths::check(rhs)?;
1522            self.months = b::SpanMonths::checked_mul(self.months, rhs)?;
1523        }
1524        if self.weeks != 0 {
1525            let rhs = b::SpanWeeks::check(rhs)?;
1526            self.weeks = b::SpanWeeks::checked_mul(self.weeks, rhs)?;
1527        }
1528        if self.days != 0 {
1529            let rhs = b::SpanDays::check(rhs)?;
1530            self.days = b::SpanDays::checked_mul(self.days, rhs)?;
1531        }
1532        if self.hours != 0 {
1533            let rhs = b::SpanHours::check(rhs)?;
1534            self.hours = b::SpanHours::checked_mul(self.hours, rhs)?;
1535        }
1536        if self.minutes != 0 {
1537            self.minutes = b::SpanMinutes::checked_mul(self.minutes, rhs)?;
1538        }
1539        if self.seconds != 0 {
1540            self.seconds = b::SpanSeconds::checked_mul(self.seconds, rhs)?;
1541        }
1542        if self.milliseconds != 0 {
1543            self.milliseconds =
1544                b::SpanMilliseconds::checked_mul(self.milliseconds, rhs)?;
1545        }
1546        if self.microseconds != 0 {
1547            self.microseconds =
1548                b::SpanMicroseconds::checked_mul(self.microseconds, rhs)?;
1549        }
1550        if self.nanoseconds != 0 {
1551            self.nanoseconds =
1552                b::SpanNanoseconds::checked_mul(self.nanoseconds, rhs)?;
1553        }
1554        // N.B. We don't need to update `self.units` here since it shouldn't
1555        // change. The only way it could is if a unit goes from zero to
1556        // non-zero (which can't happen, because multiplication by zero is
1557        // always zero), or if a unit goes from non-zero to zero. That also
1558        // can't happen because we handle the case of the factor being zero
1559        // specially above, and it returns a `Span` will all units zero
1560        // correctly.
1561        Ok(self)
1562    }
1563
1564    /// Adds a span to this one and returns the sum as a new span.
1565    ///
1566    /// When adding a span with units greater than hours, callers must provide
1567    /// a relative datetime to anchor the spans.
1568    ///
1569    /// Arithmetic proceeds as specified in [RFC 5545]. Bigger units are
1570    /// added together before smaller units.
1571    ///
1572    /// This routine accepts anything that implements `Into<SpanArithmetic>`.
1573    /// There are some trait implementations that make using this routine
1574    /// ergonomic:
1575    ///
1576    /// * `From<Span> for SpanArithmetic` adds the given span to this one.
1577    /// * `From<(Span, civil::Date)> for SpanArithmetic` adds the given
1578    /// span to this one relative to the given date. There are also `From`
1579    /// implementations for `civil::DateTime` and `Zoned`.
1580    ///
1581    /// This also works with different duration types, such as
1582    /// [`SignedDuration`] and [`std::time::Duration`], via additional trait
1583    /// implementations:
1584    ///
1585    /// * `From<SignedDuration> for SpanArithmetic` adds the given duration to
1586    /// this one.
1587    /// * `From<(SignedDuration, civil::Date)> for SpanArithmetic` adds the
1588    /// given duration to this one relative to the given date. There are also
1589    /// `From` implementations for `civil::DateTime` and `Zoned`.
1590    ///
1591    /// And similarly for `std::time::Duration`.
1592    ///
1593    /// Adding a negative span is equivalent to subtracting its absolute value.
1594    ///
1595    /// The largest non-zero unit in the span returned is at most the largest
1596    /// non-zero unit among the two spans being added. For an absolute
1597    /// duration, its "largest" unit is considered to be nanoseconds.
1598    ///
1599    /// The sum returned is automatically re-balanced so that the span is not
1600    /// "bottom heavy."
1601    ///
1602    /// [RFC 5545]: https://datatracker.ietf.org/doc/html/rfc5545
1603    ///
1604    /// # Errors
1605    ///
1606    /// This returns an error when adding the two spans would overflow any
1607    /// individual field of a span. This will also return an error if either
1608    /// of the spans have non-zero units of days or greater and no relative
1609    /// reference time is provided.
1610    ///
1611    /// Callers may use [`SpanArithmetic::days_are_24_hours`] as a special
1612    /// marker instead of providing a relative civil date to indicate that
1613    /// all days should be 24 hours long. This also results in treating all
1614    /// weeks as seven 24 hour days (168 hours).
1615    ///
1616    /// # Example
1617    ///
1618    /// ```
1619    /// use jiff::ToSpan;
1620    ///
1621    /// assert_eq!(
1622    ///     1.hour().checked_add(30.minutes())?,
1623    ///     1.hour().minutes(30).fieldwise(),
1624    /// );
1625    ///
1626    /// # Ok::<(), Box<dyn std::error::Error>>(())
1627    /// ```
1628    ///
1629    /// # Example: re-balancing
1630    ///
1631    /// This example shows how units are automatically rebalanced into bigger
1632    /// units when appropriate.
1633    ///
1634    /// ```
1635    /// use jiff::ToSpan;
1636    ///
1637    /// let span1 = 2.hours().minutes(59);
1638    /// let span2 = 2.minutes();
1639    /// assert_eq!(span1.checked_add(span2)?, 3.hours().minutes(1).fieldwise());
1640    ///
1641    /// # Ok::<(), Box<dyn std::error::Error>>(())
1642    /// ```
1643    ///
1644    /// # Example: days are not assumed to be 24 hours by default
1645    ///
1646    /// When dealing with units involving days or weeks, one must either
1647    /// provide a relative datetime (shown in the following examples) or opt
1648    /// into invariant 24 hour days:
1649    ///
1650    /// ```
1651    /// use jiff::{SpanRelativeTo, ToSpan};
1652    ///
1653    /// let span1 = 2.days().hours(23);
1654    /// let span2 = 2.hours();
1655    /// assert_eq!(
1656    ///     span1.checked_add((span2, SpanRelativeTo::days_are_24_hours()))?,
1657    ///     3.days().hours(1).fieldwise(),
1658    /// );
1659    ///
1660    /// # Ok::<(), Box<dyn std::error::Error>>(())
1661    /// ```
1662    ///
1663    /// # Example: adding spans with calendar units
1664    ///
1665    /// If you try to add two spans with calendar units without specifying a
1666    /// relative datetime, you'll get an error:
1667    ///
1668    /// ```
1669    /// use jiff::ToSpan;
1670    ///
1671    /// let span1 = 1.month().days(15);
1672    /// let span2 = 15.days();
1673    /// assert!(span1.checked_add(span2).is_err());
1674    /// ```
1675    ///
1676    /// A relative datetime is needed because calendar spans may correspond to
1677    /// different actual durations depending on where the span begins:
1678    ///
1679    /// ```
1680    /// use jiff::{civil::date, ToSpan};
1681    ///
1682    /// let span1 = 1.month().days(15);
1683    /// let span2 = 15.days();
1684    /// // 1 month from March 1 is 31 days...
1685    /// assert_eq!(
1686    ///     span1.checked_add((span2, date(2008, 3, 1)))?,
1687    ///     2.months().fieldwise(),
1688    /// );
1689    /// // ... but 1 month from April 1 is 30 days!
1690    /// assert_eq!(
1691    ///     span1.checked_add((span2, date(2008, 4, 1)))?,
1692    ///     1.month().days(30).fieldwise(),
1693    /// );
1694    ///
1695    /// # Ok::<(), Box<dyn std::error::Error>>(())
1696    /// ```
1697    ///
1698    /// # Example: error on overflow
1699    ///
1700    /// Adding two spans can overflow, and this will result in an error:
1701    ///
1702    /// ```
1703    /// use jiff::ToSpan;
1704    ///
1705    /// assert!(19_998.years().checked_add(1.year()).is_err());
1706    /// ```
1707    ///
1708    /// # Example: adding an absolute duration to a span
1709    ///
1710    /// This shows how one isn't limited to just adding two spans together.
1711    /// One can also add absolute durations to a span.
1712    ///
1713    /// ```
1714    /// use std::time::Duration;
1715    ///
1716    /// use jiff::{SignedDuration, ToSpan};
1717    ///
1718    /// assert_eq!(
1719    ///     1.hour().checked_add(SignedDuration::from_mins(30))?,
1720    ///     1.hour().minutes(30).fieldwise(),
1721    /// );
1722    /// assert_eq!(
1723    ///     1.hour().checked_add(Duration::from_secs(30 * 60))?,
1724    ///     1.hour().minutes(30).fieldwise(),
1725    /// );
1726    ///
1727    /// # Ok::<(), Box<dyn std::error::Error>>(())
1728    /// ```
1729    ///
1730    /// Note that even when adding an absolute duration, if the span contains
1731    /// non-uniform units, you still need to provide a relative datetime:
1732    ///
1733    /// ```
1734    /// use jiff::{civil::date, SignedDuration, ToSpan};
1735    ///
1736    /// // Might be 1 month or less than 1 month!
1737    /// let dur = SignedDuration::from_hours(30 * 24);
1738    /// // No relative datetime provided even when the span
1739    /// // contains non-uniform units results in an error.
1740    /// assert!(1.month().checked_add(dur).is_err());
1741    /// // In this case, 30 days is one month (April).
1742    /// assert_eq!(
1743    ///     1.month().checked_add((dur, date(2024, 3, 1)))?,
1744    ///     2.months().fieldwise(),
1745    /// );
1746    /// // In this case, 30 days is less than one month (May).
1747    /// assert_eq!(
1748    ///     1.month().checked_add((dur, date(2024, 4, 1)))?,
1749    ///     1.month().days(30).fieldwise(),
1750    /// );
1751    ///
1752    /// # Ok::<(), Box<dyn std::error::Error>>(())
1753    /// ```
1754    #[inline]
1755    pub fn checked_add<'a, A: Into<SpanArithmetic<'a>>>(
1756        &self,
1757        options: A,
1758    ) -> Result<Span, Error> {
1759        let options: SpanArithmetic<'_> = options.into();
1760        options.checked_add(*self)
1761    }
1762
1763    #[inline]
1764    fn checked_add_span<'a>(
1765        &self,
1766        relative: Option<SpanRelativeTo<'a>>,
1767        span: &Span,
1768    ) -> Result<Span, Error> {
1769        let (span1, span2) = (*self, *span);
1770        let unit = span1.largest_unit().max(span2.largest_unit());
1771        let start = match relative {
1772            Some(r) => match r.to_relative(unit)? {
1773                None => return span1.checked_add_invariant(unit, &span2),
1774                Some(r) => r,
1775            },
1776            None => {
1777                requires_relative_date_err(unit)?;
1778                return span1.checked_add_invariant(unit, &span2);
1779            }
1780        };
1781        let mid = start.checked_add(span1)?;
1782        let end = mid.checked_add(span2)?;
1783        start.until(unit, &end)
1784    }
1785
1786    #[inline]
1787    fn checked_add_duration<'a>(
1788        &self,
1789        relative: Option<SpanRelativeTo<'a>>,
1790        duration: SignedDuration,
1791    ) -> Result<Span, Error> {
1792        let (span1, dur2) = (*self, duration);
1793        let unit = span1.largest_unit();
1794        let start = match relative {
1795            Some(r) => match r.to_relative(unit)? {
1796                None => {
1797                    return span1.checked_add_invariant_duration(unit, dur2)
1798                }
1799                Some(r) => r,
1800            },
1801            None => {
1802                requires_relative_date_err(unit)?;
1803                return span1.checked_add_invariant_duration(unit, dur2);
1804            }
1805        };
1806        let mid = start.checked_add(span1)?;
1807        let end = mid.checked_add_duration(dur2)?;
1808        start.until(unit, &end)
1809    }
1810
1811    /// Like `checked_add`, but only applies for invariant units. That is,
1812    /// when *both* spans whose non-zero units are all hours or smaller
1813    /// (or weeks or smaller with the "days are 24 hours" marker).
1814    #[inline]
1815    fn checked_add_invariant(
1816        &self,
1817        unit: Unit,
1818        span: &Span,
1819    ) -> Result<Span, Error> {
1820        assert!(unit <= Unit::Week);
1821        self.checked_add_invariant_duration(unit, span.to_invariant_duration())
1822    }
1823
1824    /// Like `checked_add_invariant`, but adds an absolute duration.
1825    #[inline]
1826    fn checked_add_invariant_duration(
1827        &self,
1828        unit: Unit,
1829        rhs_duration: SignedDuration,
1830    ) -> Result<Span, Error> {
1831        assert!(unit <= Unit::Week);
1832        let self_duration = self.to_invariant_duration();
1833        // OK because maximal invariant `Span` is way below maximal
1834        // `SignedDuration`. Doubling it can never overflow.
1835        let sum = self_duration + rhs_duration;
1836        Span::from_invariant_duration(unit, sum)
1837    }
1838
1839    /// This routine is identical to [`Span::checked_add`] with the given
1840    /// duration negated.
1841    ///
1842    /// # Errors
1843    ///
1844    /// This has the same error conditions as [`Span::checked_add`].
1845    ///
1846    /// # Example
1847    ///
1848    /// ```
1849    /// use std::time::Duration;
1850    ///
1851    /// use jiff::{SignedDuration, ToSpan};
1852    ///
1853    /// assert_eq!(
1854    ///     1.hour().checked_sub(30.minutes())?,
1855    ///     30.minutes().fieldwise(),
1856    /// );
1857    /// assert_eq!(
1858    ///     1.hour().checked_sub(SignedDuration::from_mins(30))?,
1859    ///     30.minutes().fieldwise(),
1860    /// );
1861    /// assert_eq!(
1862    ///     1.hour().checked_sub(Duration::from_secs(30 * 60))?,
1863    ///     30.minutes().fieldwise(),
1864    /// );
1865    ///
1866    /// # Ok::<(), Box<dyn std::error::Error>>(())
1867    /// ```
1868    #[inline]
1869    pub fn checked_sub<'a, A: Into<SpanArithmetic<'a>>>(
1870        &self,
1871        options: A,
1872    ) -> Result<Span, Error> {
1873        let mut options: SpanArithmetic<'_> = options.into();
1874        options.duration = options.duration.checked_neg()?;
1875        options.checked_add(*self)
1876    }
1877
1878    /// Compares two spans in terms of how long they are. Negative spans are
1879    /// considered shorter than the zero span.
1880    ///
1881    /// Two spans compare equal when they correspond to the same duration
1882    /// of time, even if their individual fields are different. This is in
1883    /// contrast to the `Eq` trait implementation of `SpanFieldwise` (created
1884    /// by [`Span::fieldwise`]), which performs exact field-wise comparisons.
1885    /// This split exists because the comparison provided by this routine is
1886    /// "heavy" in that it may need to do datetime arithmetic to return an
1887    /// answer. In contrast, the `Eq` trait implementation is "cheap."
1888    ///
1889    /// This routine accepts anything that implements `Into<SpanCompare>`.
1890    /// There are some trait implementations that make using this routine
1891    /// ergonomic:
1892    ///
1893    /// * `From<Span> for SpanCompare` compares the given span to this one.
1894    /// * `From<(Span, civil::Date)> for SpanArithmetic` compares the given
1895    /// span to this one relative to the given date. There are also `From`
1896    /// implementations for `civil::DateTime` and `Zoned`.
1897    ///
1898    /// # Errors
1899    ///
1900    /// If either of the spans being compared have a non-zero calendar unit
1901    /// (units bigger than hours), then this routine requires a relative
1902    /// datetime. If one is not provided, then an error is returned.
1903    ///
1904    /// An error can also occur when adding either span to the relative
1905    /// datetime given results in overflow.
1906    ///
1907    /// Callers may use [`SpanArithmetic::days_are_24_hours`] as a special
1908    /// marker instead of providing a relative civil date to indicate that
1909    /// all days should be 24 hours long. This also results in treating all
1910    /// weeks as seven 24 hour days (168 hours).
1911    ///
1912    /// # Example
1913    ///
1914    /// ```
1915    /// use jiff::ToSpan;
1916    ///
1917    /// let span1 = 3.hours();
1918    /// let span2 = 180.minutes();
1919    /// assert_eq!(span1.compare(span2)?, std::cmp::Ordering::Equal);
1920    /// // But notice that the two spans are not equal via `Eq`:
1921    /// assert_ne!(span1.fieldwise(), span2.fieldwise());
1922    ///
1923    /// # Ok::<(), Box<dyn std::error::Error>>(())
1924    /// ```
1925    ///
1926    /// # Example: negative spans are less than zero
1927    ///
1928    /// ```
1929    /// use jiff::ToSpan;
1930    ///
1931    /// let span1 = -1.second();
1932    /// let span2 = 0.seconds();
1933    /// assert_eq!(span1.compare(span2)?, std::cmp::Ordering::Less);
1934    ///
1935    /// # Ok::<(), Box<dyn std::error::Error>>(())
1936    /// ```
1937    ///
1938    /// # Example: comparisons take DST into account
1939    ///
1940    /// When a relative datetime is time zone aware, then DST is taken into
1941    /// account when comparing spans:
1942    ///
1943    /// ```
1944    /// use jiff::{civil, ToSpan, Zoned};
1945    ///
1946    /// let span1 = 79.hours().minutes(10);
1947    /// let span2 = 3.days().hours(7).seconds(630);
1948    /// let span3 = 3.days().hours(6).minutes(50);
1949    ///
1950    /// let relative: Zoned = "2020-11-01T00-07[America/Los_Angeles]".parse()?;
1951    /// let mut spans = [span1, span2, span3];
1952    /// spans.sort_by(|s1, s2| s1.compare((s2, &relative)).unwrap());
1953    /// assert_eq!(
1954    ///     spans.map(|sp| sp.fieldwise()),
1955    ///     [span1.fieldwise(), span3.fieldwise(), span2.fieldwise()],
1956    /// );
1957    ///
1958    /// // Compare with the result of sorting without taking DST into account.
1959    /// // We can that by providing a relative civil date:
1960    /// let relative = civil::date(2020, 11, 1);
1961    /// spans.sort_by(|s1, s2| s1.compare((s2, relative)).unwrap());
1962    /// assert_eq!(
1963    ///     spans.map(|sp| sp.fieldwise()),
1964    ///     [span3.fieldwise(), span1.fieldwise(), span2.fieldwise()],
1965    /// );
1966    ///
1967    /// # Ok::<(), Box<dyn std::error::Error>>(())
1968    /// ```
1969    ///
1970    /// See the examples for [`Span::total`] if you want to sort spans without
1971    /// an `unwrap()` call.
1972    #[inline]
1973    pub fn compare<'a, C: Into<SpanCompare<'a>>>(
1974        &self,
1975        options: C,
1976    ) -> Result<Ordering, Error> {
1977        let options: SpanCompare<'_> = options.into();
1978        options.compare(*self)
1979    }
1980
1981    /// Returns a floating point number representing the total number of a
1982    /// specific unit (as given) in this span. If the span is not evenly
1983    /// divisible by the requested units, then the number returned may have a
1984    /// fractional component.
1985    ///
1986    /// This routine accepts anything that implements `Into<SpanTotal>`. There
1987    /// are some trait implementations that make using this routine ergonomic:
1988    ///
1989    /// * `From<Unit> for SpanTotal` computes a total for the given unit in
1990    /// this span.
1991    /// * `From<(Unit, civil::Date)> for SpanTotal` computes a total for the
1992    /// given unit in this span, relative to the given date. There are also
1993    /// `From` implementations for `civil::DateTime` and `Zoned`.
1994    ///
1995    /// # Errors
1996    ///
1997    /// If this span has any non-zero calendar unit (units bigger than hours),
1998    /// then this routine requires a relative datetime. If one is not provided,
1999    /// then an error is returned.
2000    ///
2001    /// An error can also occur when adding the span to the relative
2002    /// datetime given results in overflow.
2003    ///
2004    /// Callers may use [`SpanArithmetic::days_are_24_hours`] as a special
2005    /// marker instead of providing a relative civil date to indicate that
2006    /// all days should be 24 hours long. This also results in treating all
2007    /// weeks as seven 24 hour days (168 hours).
2008    ///
2009    /// # Example
2010    ///
2011    /// This example shows how to find the number of seconds in a particular
2012    /// span:
2013    ///
2014    /// ```
2015    /// use jiff::{ToSpan, Unit};
2016    ///
2017    /// let span = 3.hours().minutes(10);
2018    /// assert_eq!(span.total(Unit::Second)?, 11_400.0);
2019    ///
2020    /// # Ok::<(), Box<dyn std::error::Error>>(())
2021    /// ```
2022    ///
2023    /// # Example: 24 hour days
2024    ///
2025    /// This shows how to find the total number of 24 hour days in
2026    /// `123,456,789` seconds.
2027    ///
2028    /// ```
2029    /// use jiff::{SpanTotal, ToSpan, Unit};
2030    ///
2031    /// let span = 123_456_789.seconds();
2032    /// assert_eq!(
2033    ///     span.total(SpanTotal::from(Unit::Day).days_are_24_hours())?,
2034    ///     1428.8980208333332,
2035    /// );
2036    ///
2037    /// # Ok::<(), Box<dyn std::error::Error>>(())
2038    /// ```
2039    ///
2040    /// # Example: DST is taken into account
2041    ///
2042    /// The month of March 2024 in `America/New_York` had 31 days, but one of
2043    /// those days was 23 hours long due a transition into daylight saving
2044    /// time:
2045    ///
2046    /// ```
2047    /// use jiff::{civil::date, ToSpan, Unit};
2048    ///
2049    /// let span = 744.hours();
2050    /// let relative = date(2024, 3, 1).in_tz("America/New_York")?;
2051    /// // Because of the short day, 744 hours is actually a little *more* than
2052    /// // 1 month starting from 2024-03-01.
2053    /// assert_eq!(span.total((Unit::Month, &relative))?, 1.0013888888888889);
2054    ///
2055    /// # Ok::<(), Box<dyn std::error::Error>>(())
2056    /// ```
2057    ///
2058    /// Now compare what happens when the relative datetime is civil and not
2059    /// time zone aware:
2060    ///
2061    /// ```
2062    /// use jiff::{civil::date, ToSpan, Unit};
2063    ///
2064    /// let span = 744.hours();
2065    /// let relative = date(2024, 3, 1);
2066    /// assert_eq!(span.total((Unit::Month, relative))?, 1.0);
2067    ///
2068    /// # Ok::<(), Box<dyn std::error::Error>>(())
2069    /// ```
2070    ///
2071    /// # Example: infallible sorting
2072    ///
2073    /// The sorting example in [`Span::compare`] has to use `unwrap()` in
2074    /// its `sort_by(..)` call because `Span::compare` may fail and there
2075    /// is no "fallible" sorting routine in Rust's standard library (as of
2076    /// 2024-07-07). While the ways in which `Span::compare` can fail for
2077    /// a valid configuration are limited to overflow for "extreme" values, it
2078    /// is possible to sort spans infallibly by computing floating point
2079    /// representations for each span up-front:
2080    ///
2081    /// ```
2082    /// use jiff::{civil::Date, ToSpan, Unit, Zoned};
2083    ///
2084    /// let span1 = 79.hours().minutes(10);
2085    /// let span2 = 3.days().hours(7).seconds(630);
2086    /// let span3 = 3.days().hours(6).minutes(50);
2087    ///
2088    /// let relative: Zoned = "2020-11-01T00-07[America/Los_Angeles]".parse()?;
2089    /// let mut spans = [
2090    ///     (span1, span1.total((Unit::Day, &relative))?),
2091    ///     (span2, span2.total((Unit::Day, &relative))?),
2092    ///     (span3, span3.total((Unit::Day, &relative))?),
2093    /// ];
2094    /// spans.sort_by(|&(_, total1), &(_, total2)| total1.total_cmp(&total2));
2095    /// assert_eq!(
2096    ///     spans.map(|(sp, _)| sp.fieldwise()),
2097    ///     [span1.fieldwise(), span3.fieldwise(), span2.fieldwise()],
2098    /// );
2099    ///
2100    /// // Compare with the result of sorting without taking DST into account.
2101    /// // We do that here by providing a relative civil date.
2102    /// let relative: Date = "2020-11-01".parse()?;
2103    /// let mut spans = [
2104    ///     (span1, span1.total((Unit::Day, relative))?),
2105    ///     (span2, span2.total((Unit::Day, relative))?),
2106    ///     (span3, span3.total((Unit::Day, relative))?),
2107    /// ];
2108    /// spans.sort_by(|&(_, total1), &(_, total2)| total1.total_cmp(&total2));
2109    /// assert_eq!(
2110    ///     spans.map(|(sp, _)| sp.fieldwise()),
2111    ///     [span3.fieldwise(), span1.fieldwise(), span2.fieldwise()],
2112    /// );
2113    ///
2114    /// # Ok::<(), Box<dyn std::error::Error>>(())
2115    /// ```
2116    #[inline]
2117    pub fn total<'a, T: Into<SpanTotal<'a>>>(
2118        &self,
2119        options: T,
2120    ) -> Result<f64, Error> {
2121        let options: SpanTotal<'_> = options.into();
2122        options.total(*self)
2123    }
2124
2125    /// Returns a new span that is balanced and rounded.
2126    ///
2127    /// Rounding a span has a number of parameters, all of which are optional.
2128    /// When no parameters are given, then no rounding or balancing is done,
2129    /// and the span as given is returned. That is, it's a no-op.
2130    ///
2131    /// The parameters are, in brief:
2132    ///
2133    /// * [`SpanRound::largest`] sets the largest [`Unit`] that is allowed to
2134    /// be non-zero in the span returned. When _only_ the largest unit is set,
2135    /// rounding itself doesn't occur and instead the span is merely balanced.
2136    /// * [`SpanRound::smallest`] sets the smallest [`Unit`] that is allowed to
2137    /// be non-zero in the span returned. By default, it is set to
2138    /// [`Unit::Nanosecond`], i.e., no rounding occurs. When the smallest unit
2139    /// is set to something bigger than nanoseconds, then the non-zero units
2140    /// in the span smaller than the smallest unit are used to determine how
2141    /// the span should be rounded. For example, rounding `1 hour 59 minutes`
2142    /// to the nearest hour using the default rounding mode would produce
2143    /// `2 hours`.
2144    /// * [`SpanRound::mode`] determines how to handle the remainder when
2145    /// rounding. The default is [`RoundMode::HalfExpand`], which corresponds
2146    /// to how you were taught to round in school. Alternative modes, like
2147    /// [`RoundMode::Trunc`], exist too. For example, a truncating rounding of
2148    /// `1 hour 59 minutes` to the nearest hour would produce `1 hour`.
2149    /// * [`SpanRound::increment`] sets the rounding granularity to use for
2150    /// the configured smallest unit. For example, if the smallest unit is
2151    /// minutes and the increment is 5, then the span returned will always have
2152    /// its minute units set to a multiple of `5`.
2153    /// * [`SpanRound::relative`] sets the datetime from which to interpret the
2154    /// span. This is required when rounding spans with calendar units (years,
2155    /// months or weeks). When a relative datetime is time zone aware, then
2156    /// rounding accounts for the fact that not all days are 24 hours long.
2157    /// When a relative datetime is omitted or is civil (not time zone aware),
2158    /// then days are always 24 hours long.
2159    ///
2160    /// # Constructing a [`SpanRound`]
2161    ///
2162    /// This routine accepts anything that implements `Into<SpanRound>`. There
2163    /// are a few key trait implementations that make this convenient:
2164    ///
2165    /// * `From<Unit> for SpanRound` will construct a rounding configuration
2166    /// where the smallest unit is set to the one given.
2167    /// * `From<(Unit, i64)> for SpanRound` will construct a rounding
2168    /// configuration where the smallest unit and the rounding increment are
2169    /// set to the ones given.
2170    ///
2171    /// To set other options (like the largest unit, the rounding mode and the
2172    /// relative datetime), one must explicitly create a `SpanRound` and pass
2173    /// it to this routine.
2174    ///
2175    /// # Errors
2176    ///
2177    /// In general, there are two main ways for rounding to fail: an improper
2178    /// configuration like trying to round a span with calendar units but
2179    /// without a relative datetime, or when overflow occurs. Overflow can
2180    /// occur when the span, added to the relative datetime if given, would
2181    /// exceed the minimum or maximum datetime values. Overflow can also occur
2182    /// if the span is too big to fit into the requested unit configuration.
2183    /// For example, a span like `19_998.years()` cannot be represented with a
2184    /// 64-bit integer number of nanoseconds.
2185    ///
2186    /// Callers may use [`SpanArithmetic::days_are_24_hours`] as a special
2187    /// marker instead of providing a relative civil date to indicate that
2188    /// all days should be 24 hours long. This also results in treating all
2189    /// weeks as seven 24 hour days (168 hours).
2190    ///
2191    /// # Example: balancing
2192    ///
2193    /// This example demonstrates balancing, not rounding. And in particular,
2194    /// this example shows how to balance a span as much as possible (i.e.,
2195    /// with units of hours or smaller) without needing to specify a relative
2196    /// datetime:
2197    ///
2198    /// ```
2199    /// use jiff::{SpanRound, ToSpan, Unit};
2200    ///
2201    /// let span = 123_456_789_123_456_789i64.nanoseconds();
2202    /// assert_eq!(
2203    ///     span.round(SpanRound::new().largest(Unit::Hour))?.fieldwise(),
2204    ///     34_293.hours().minutes(33).seconds(9)
2205    ///         .milliseconds(123).microseconds(456).nanoseconds(789),
2206    /// );
2207    ///
2208    /// # Ok::<(), Box<dyn std::error::Error>>(())
2209    /// ```
2210    ///
2211    /// Or you can opt into invariant 24-hour days (and 7-day weeks) without a
2212    /// relative date with [`SpanRound::days_are_24_hours`]:
2213    ///
2214    /// ```
2215    /// use jiff::{SpanRound, ToSpan, Unit};
2216    ///
2217    /// let span = 123_456_789_123_456_789i64.nanoseconds();
2218    /// assert_eq!(
2219    ///     span.round(
2220    ///         SpanRound::new().largest(Unit::Day).days_are_24_hours(),
2221    ///     )?.fieldwise(),
2222    ///     1_428.days()
2223    ///         .hours(21).minutes(33).seconds(9)
2224    ///         .milliseconds(123).microseconds(456).nanoseconds(789),
2225    /// );
2226    ///
2227    /// # Ok::<(), Box<dyn std::error::Error>>(())
2228    /// ```
2229    ///
2230    /// # Example: balancing and rounding
2231    ///
2232    /// This example is like the one before it, but where we round to the
2233    /// nearest second:
2234    ///
2235    /// ```
2236    /// use jiff::{SpanRound, ToSpan, Unit};
2237    ///
2238    /// let span = 123_456_789_123_456_789i64.nanoseconds();
2239    /// assert_eq!(
2240    ///     span.round(SpanRound::new().largest(Unit::Hour).smallest(Unit::Second))?,
2241    ///     34_293.hours().minutes(33).seconds(9).fieldwise(),
2242    /// );
2243    ///
2244    /// # Ok::<(), Box<dyn std::error::Error>>(())
2245    /// ```
2246    ///
2247    /// Or, just rounding to the nearest hour can make use of the
2248    /// `From<Unit> for SpanRound` trait implementation:
2249    ///
2250    /// ```
2251    /// use jiff::{ToSpan, Unit};
2252    ///
2253    /// let span = 123_456_789_123_456_789i64.nanoseconds();
2254    /// assert_eq!(span.round(Unit::Hour)?, 34_294.hours().fieldwise());
2255    ///
2256    /// # Ok::<(), Box<dyn std::error::Error>>(())
2257    /// ```
2258    ///
2259    /// # Example: balancing with a relative datetime
2260    ///
2261    /// Even with calendar units, so long as a relative datetime is provided,
2262    /// it's easy to turn days into bigger units:
2263    ///
2264    /// ```
2265    /// use jiff::{civil::date, SpanRound, ToSpan, Unit};
2266    ///
2267    /// let span = 1_000.days();
2268    /// let relative = date(2000, 1, 1);
2269    /// let options = SpanRound::new().largest(Unit::Year).relative(relative);
2270    /// assert_eq!(span.round(options)?, 2.years().months(8).days(26).fieldwise());
2271    ///
2272    /// # Ok::<(), Box<dyn std::error::Error>>(())
2273    /// ```
2274    ///
2275    /// # Example: round to the nearest half-hour
2276    ///
2277    /// ```
2278    /// use jiff::{Span, ToSpan, Unit};
2279    ///
2280    /// let span: Span = "PT23h50m3.123s".parse()?;
2281    /// assert_eq!(span.round((Unit::Minute, 30))?, 24.hours().fieldwise());
2282    ///
2283    /// # Ok::<(), Box<dyn std::error::Error>>(())
2284    /// ```
2285    ///
2286    /// # Example: yearly quarters in a span
2287    ///
2288    /// This example shows how to find how many full 3 month quarters are in a
2289    /// particular span of time.
2290    ///
2291    /// ```
2292    /// use jiff::{civil::date, RoundMode, SpanRound, ToSpan, Unit};
2293    ///
2294    /// let span1 = 10.months().days(15);
2295    /// let round = SpanRound::new()
2296    ///     .smallest(Unit::Month)
2297    ///     .increment(3)
2298    ///     .mode(RoundMode::Trunc)
2299    ///     // A relative datetime must be provided when
2300    ///     // rounding involves calendar units.
2301    ///     .relative(date(2024, 1, 1));
2302    /// let span2 = span1.round(round)?;
2303    /// assert_eq!(span2.get_months() / 3, 3);
2304    ///
2305    /// # Ok::<(), Box<dyn std::error::Error>>(())
2306    /// ```
2307    #[inline]
2308    pub fn round<'a, R: Into<SpanRound<'a>>>(
2309        self,
2310        options: R,
2311    ) -> Result<Span, Error> {
2312        let options: SpanRound<'a> = options.into();
2313        options.round(self)
2314    }
2315
2316    /// Converts a `Span` to a [`SignedDuration`] relative to the date given.
2317    ///
2318    /// In most cases, it is unlikely that you'll need to use this routine to
2319    /// convert a `Span` to a `SignedDuration` and instead will be ably to
2320    /// use `SignedDuration::try_from(span)`. Namely, by default:
2321    ///
2322    /// * [`Zoned::until`] guarantees that the biggest non-zero unit is hours.
2323    /// * [`Timestamp::until`] guarantees that the biggest non-zero unit is
2324    /// seconds.
2325    /// * [`DateTime::until`] guarantees that the biggest non-zero unit is
2326    /// days.
2327    /// * [`Date::until`] guarantees that the biggest non-zero unit is days.
2328    /// * [`Time::until`] guarantees that the biggest non-zero unit is hours.
2329    ///
2330    /// In the above, only [`DateTime::until`] and [`Date::until`] return
2331    /// calendar units by default, and thus would require this routine. (In
2332    /// which case, one may pass [`SpanRelativeTo::days_are_24_hours`] or an
2333    /// actual relative date to resolve the length of a day.)
2334    ///
2335    /// Of course, one may change the defaults. For example, if one
2336    /// uses `Zoned::until` with the largest unit set to `Unit::Year`
2337    /// and the resulting `Span` includes non-zero calendar units, then
2338    /// `SignedDuration::try_from` will fail because there is no relative date.
2339    ///
2340    /// # Errors
2341    ///
2342    /// This returns an error if adding this span to the date given results in
2343    /// overflow. This can also return an error if one uses
2344    /// [`SpanRelativeTo::days_are_24_hours`] with a `Span` that has non-zero
2345    /// units greater than weeks.
2346    ///
2347    /// # Example: converting a span with calendar units to a `SignedDuration`
2348    ///
2349    /// This compares the number of seconds in a non-leap year with a leap
2350    /// year:
2351    ///
2352    /// ```
2353    /// use jiff::{civil::date, SignedDuration, ToSpan};
2354    ///
2355    /// let span = 1.year();
2356    ///
2357    /// let duration = span.to_duration(date(2024, 1, 1))?;
2358    /// assert_eq!(duration, SignedDuration::from_secs(31_622_400));
2359    /// let duration = span.to_duration(date(2023, 1, 1))?;
2360    /// assert_eq!(duration, SignedDuration::from_secs(31_536_000));
2361    ///
2362    /// # Ok::<(), Box<dyn std::error::Error>>(())
2363    /// ```
2364    ///
2365    /// # Example: converting a span without a relative datetime
2366    ///
2367    /// If for some reason it doesn't make sense to include a
2368    /// relative datetime, you can use this routine to convert a
2369    /// `Span` with units up to weeks to a `SignedDuration` via the
2370    /// [`SpanRelativeTo::days_are_24_hours`] marker:
2371    ///
2372    /// ```
2373    /// use jiff::{civil::date, SignedDuration, SpanRelativeTo, ToSpan};
2374    ///
2375    /// let span = 1.week().days(1);
2376    ///
2377    /// let duration = span.to_duration(SpanRelativeTo::days_are_24_hours())?;
2378    /// assert_eq!(duration, SignedDuration::from_hours(192));
2379    ///
2380    /// # Ok::<(), Box<dyn std::error::Error>>(())
2381    /// ```
2382    #[inline]
2383    pub fn to_duration<'a, R: Into<SpanRelativeTo<'a>>>(
2384        &self,
2385        relative: R,
2386    ) -> Result<SignedDuration, Error> {
2387        let max_unit = self.largest_unit();
2388        let relative: SpanRelativeTo<'a> = relative.into();
2389        let Some(result) = relative.to_relative(max_unit).transpose() else {
2390            return Ok(self.to_invariant_duration());
2391        };
2392        let relspan = result
2393            .and_then(|r| r.into_relative_span(Unit::Second, *self))
2394            .with_context(|| match relative.kind {
2395                SpanRelativeToKind::Civil(_) => E::ToDurationCivil,
2396                SpanRelativeToKind::Zoned(_) => E::ToDurationZoned,
2397                SpanRelativeToKind::DaysAre24Hours => {
2398                    E::ToDurationDaysAre24Hours
2399                }
2400            })?;
2401        debug_assert!(relspan.span.largest_unit() <= Unit::Second);
2402        Ok(relspan.span.to_invariant_duration())
2403    }
2404
2405    /// Converts the non-variable units of this `Span` to a `SignedDuration`.
2406    ///
2407    /// This includes days and weeks, even though they can be of varying
2408    /// length during time zone transitions. If this applies, then callers
2409    /// should set the days and weeks to `0` before calling this routine.
2410    ///
2411    /// All units above weeks are always ignored.
2412    #[inline]
2413    pub(crate) fn to_invariant_duration(&self) -> SignedDuration {
2414        // This guarantees, at compile time, that a maximal invariant Span
2415        // (that is, all units are weeks or lower and all units are set to
2416        // their maximum values) will still balance out to a number of seconds
2417        // that fits into a `i64`. This in turn implies that a `SignedDuration`
2418        // can represent all possible invariant positive spans.
2419        const _FITS_IN_U64: () = {
2420            debug_assert!(
2421                i64::MAX as i128
2422                    > ((b::SpanWeeks::MAX as i128 * b::SECS_PER_WEEK as i128)
2423                        + (b::SpanDays::MAX as i128
2424                            * b::SECS_PER_CIVIL_DAY as i128)
2425                        + (b::SpanHours::MAX as i128
2426                            * b::SECS_PER_HOUR as i128)
2427                        + (b::SpanMinutes::MAX as i128
2428                            * b::SECS_PER_MIN as i128)
2429                        + b::SpanSeconds::MAX as i128
2430                        + (b::SpanMilliseconds::MAX as i128
2431                            / b::MILLIS_PER_SEC as i128)
2432                        + (b::SpanMicroseconds::MAX as i128
2433                            / b::MICROS_PER_SEC as i128)
2434                        + (b::SpanNanoseconds::MAX as i128
2435                            / b::NANOS_PER_SEC as i128)),
2436            );
2437            ()
2438        };
2439
2440        // OK because we have a compile time assert above that ensures our
2441        // nanoseconds are in the valid range of a `SignedDuration`.
2442        SignedDuration::from_civil_weeks32(self.get_weeks())
2443            + SignedDuration::from_civil_days32(self.get_days())
2444            + SignedDuration::from_hours32(self.get_hours())
2445            + SignedDuration::from_mins(self.get_minutes())
2446            + SignedDuration::from_secs(self.get_seconds())
2447            + SignedDuration::from_millis(self.get_milliseconds())
2448            + SignedDuration::from_micros(self.get_microseconds())
2449            + SignedDuration::from_nanos(self.get_nanoseconds())
2450    }
2451
2452    /// Like `Span::to_invariant_duration`, except only considers units of
2453    /// hours and lower. All bigger units are ignored.
2454    #[inline]
2455    pub(crate) fn to_invariant_duration_time_only(&self) -> SignedDuration {
2456        // This guarantees, at compile time, that a maximal invariant Span
2457        // (that is, all units are weeks or lower and all units are set to
2458        // their maximum values) will still balance out to a number of seconds
2459        // that fits into a `i64`. This in turn implies that a `SignedDuration`
2460        // can represent all possible invariant positive spans.
2461        const _FITS_IN_U64: () = {
2462            debug_assert!(
2463                i64::MAX as i128
2464                    > ((b::SpanHours::MAX as i128 * b::SECS_PER_HOUR as i128)
2465                        + (b::SpanMinutes::MAX as i128
2466                            * b::SECS_PER_MIN as i128)
2467                        + b::SpanSeconds::MAX as i128
2468                        + (b::SpanMilliseconds::MAX as i128
2469                            / b::MILLIS_PER_SEC as i128)
2470                        + (b::SpanMicroseconds::MAX as i128
2471                            / b::MICROS_PER_SEC as i128)
2472                        + (b::SpanNanoseconds::MAX as i128
2473                            / b::NANOS_PER_SEC as i128)),
2474            );
2475            ()
2476        };
2477
2478        // OK because we have a compile time assert above that ensures our
2479        // nanoseconds are in the valid range of a `SignedDuration`.
2480        SignedDuration::from_hours32(self.get_hours())
2481            + SignedDuration::from_mins(self.get_minutes())
2482            + SignedDuration::from_secs(self.get_seconds())
2483            + SignedDuration::from_millis(self.get_milliseconds())
2484            + SignedDuration::from_micros(self.get_microseconds())
2485            + SignedDuration::from_nanos(self.get_nanoseconds())
2486    }
2487}
2488
2489/// Crate internal APIs that operate on ranged integer types.
2490impl Span {
2491    #[inline]
2492    fn try_unit(self, unit: Unit, value: i64) -> Result<Span, Error> {
2493        match unit {
2494            Unit::Year => self.try_years(value),
2495            Unit::Month => self.try_months(value),
2496            Unit::Week => self.try_weeks(value),
2497            Unit::Day => self.try_days(value),
2498            Unit::Hour => self.try_hours(value),
2499            Unit::Minute => self.try_minutes(value),
2500            Unit::Second => self.try_seconds(value),
2501            Unit::Millisecond => self.try_milliseconds(value),
2502            Unit::Microsecond => self.try_microseconds(value),
2503            Unit::Nanosecond => self.try_nanoseconds(value),
2504        }
2505    }
2506
2507    #[inline]
2508    pub(crate) fn get_years_unsigned(&self) -> u16 {
2509        self.years as u16
2510    }
2511
2512    #[inline]
2513    pub(crate) fn get_months_unsigned(&self) -> u32 {
2514        self.months as u32
2515    }
2516
2517    #[inline]
2518    pub(crate) fn get_weeks_unsigned(&self) -> u32 {
2519        self.weeks as u32
2520    }
2521
2522    #[inline]
2523    pub(crate) fn get_days_unsigned(&self) -> u32 {
2524        self.days as u32
2525    }
2526
2527    #[inline]
2528    pub(crate) fn get_hours_unsigned(&self) -> u32 {
2529        self.hours as u32
2530    }
2531
2532    #[inline]
2533    pub(crate) fn get_minutes_unsigned(&self) -> u64 {
2534        self.minutes as u64
2535    }
2536
2537    #[inline]
2538    pub(crate) fn get_seconds_unsigned(&self) -> u64 {
2539        self.seconds as u64
2540    }
2541
2542    #[inline]
2543    pub(crate) fn get_milliseconds_unsigned(&self) -> u64 {
2544        self.milliseconds as u64
2545    }
2546
2547    #[inline]
2548    pub(crate) fn get_microseconds_unsigned(&self) -> u64 {
2549        self.microseconds as u64
2550    }
2551
2552    #[inline]
2553    pub(crate) fn get_nanoseconds_unsigned(&self) -> u64 {
2554        self.nanoseconds as u64
2555    }
2556
2557    #[inline]
2558    fn get_sign(&self) -> b::Sign {
2559        self.sign
2560    }
2561
2562    #[inline]
2563    fn get_unit(&self, unit: Unit) -> i64 {
2564        match unit {
2565            Unit::Year => self.get_years().into(),
2566            Unit::Month => self.get_months().into(),
2567            Unit::Week => self.get_weeks().into(),
2568            Unit::Day => self.get_days().into(),
2569            Unit::Hour => self.get_hours().into(),
2570            Unit::Minute => self.get_minutes(),
2571            Unit::Second => self.get_seconds(),
2572            Unit::Millisecond => self.get_milliseconds(),
2573            Unit::Microsecond => self.get_microseconds(),
2574            Unit::Nanosecond => self.get_nanoseconds(),
2575        }
2576    }
2577}
2578
2579/// Crate internal APIs that permit setting units without checks.
2580///
2581/// Callers should be very careful when using these. These notably also do
2582/// not handle updating the sign on the `Span` and require the precisely
2583/// correct integer primitive.
2584impl Span {
2585    #[inline]
2586    pub(crate) fn years_unchecked(mut self, years: i16) -> Span {
2587        self.years = years;
2588        self.units = self.units.set(Unit::Year, years == 0);
2589        self
2590    }
2591
2592    #[inline]
2593    pub(crate) fn months_unchecked(mut self, months: i32) -> Span {
2594        self.months = months;
2595        self.units = self.units.set(Unit::Month, months == 0);
2596        self
2597    }
2598
2599    #[inline]
2600    pub(crate) fn weeks_unchecked(mut self, weeks: i32) -> Span {
2601        self.weeks = weeks;
2602        self.units = self.units.set(Unit::Week, weeks == 0);
2603        self
2604    }
2605
2606    #[inline]
2607    pub(crate) fn days_unchecked(mut self, days: i32) -> Span {
2608        self.days = days;
2609        self.units = self.units.set(Unit::Day, days == 0);
2610        self
2611    }
2612
2613    #[inline]
2614    pub(crate) fn hours_unchecked(mut self, hours: i32) -> Span {
2615        self.hours = hours;
2616        self.units = self.units.set(Unit::Hour, hours == 0);
2617        self
2618    }
2619
2620    #[inline]
2621    pub(crate) fn minutes_unchecked(mut self, minutes: i64) -> Span {
2622        self.minutes = minutes;
2623        self.units = self.units.set(Unit::Minute, minutes == 0);
2624        self
2625    }
2626
2627    #[inline]
2628    pub(crate) fn seconds_unchecked(mut self, seconds: i64) -> Span {
2629        self.seconds = seconds;
2630        self.units = self.units.set(Unit::Second, seconds == 0);
2631        self
2632    }
2633
2634    #[inline]
2635    pub(crate) fn milliseconds_unchecked(mut self, milliseconds: i64) -> Span {
2636        self.milliseconds = milliseconds;
2637        self.units = self.units.set(Unit::Millisecond, milliseconds == 0);
2638        self
2639    }
2640
2641    #[inline]
2642    pub(crate) fn microseconds_unchecked(mut self, microseconds: i64) -> Span {
2643        self.microseconds = microseconds;
2644        self.units = self.units.set(Unit::Microsecond, microseconds == 0);
2645        self
2646    }
2647
2648    #[inline]
2649    pub(crate) fn nanoseconds_unchecked(mut self, nanoseconds: i64) -> Span {
2650        self.nanoseconds = nanoseconds;
2651        self.units = self.units.set(Unit::Nanosecond, nanoseconds == 0);
2652        self
2653    }
2654
2655    #[inline]
2656    pub(crate) fn sign_unchecked(self, sign: b::Sign) -> Span {
2657        Span { sign, ..self }
2658    }
2659}
2660
2661/// Crate internal helper routines.
2662impl Span {
2663    /// Converts the given duration to a `Span` whose units do not
2664    /// exceed `largest`.
2665    ///
2666    /// Note that `largest` is capped at `Unit::Week`. Note though that if
2667    /// any unit greater than `Unit::Week` is given, then it is treated as
2668    /// `Unit::Day`. The only way to get weeks in the `Span` returned is to
2669    /// specifically request `Unit::Week`.
2670    ///
2671    /// And also note that days in this context are civil days. That is, they
2672    /// are always 24 hours long. Callers needing to deal with variable length
2673    /// days should do so outside of this routine and should not provide a
2674    /// `largest` unit bigger than `Unit::Hour`.
2675    pub(crate) fn from_invariant_duration(
2676        largest: Unit,
2677        mut dur: SignedDuration,
2678    ) -> Result<Span, Error> {
2679        let mut span = Span::new();
2680
2681        if matches!(largest, Unit::Week) {
2682            let (weeks, rem) = dur.as_civil_weeks_with_remainder();
2683            span = span.try_weeks(weeks)?;
2684            dur = rem;
2685        }
2686        if largest >= Unit::Day {
2687            let (days, rem) = dur.as_civil_days_with_remainder();
2688            span = span.try_days(days)?;
2689            dur = rem;
2690        }
2691        if largest >= Unit::Hour {
2692            let (hours, rem) = dur.as_hours_with_remainder();
2693            span = span.try_hours(hours)?;
2694            dur = rem;
2695        }
2696        if largest >= Unit::Minute {
2697            let (mins, rem) = dur.as_mins_with_remainder();
2698            span = span.try_minutes(mins)?;
2699            dur = rem;
2700        }
2701        if largest >= Unit::Second {
2702            let (secs, rem) = dur.as_secs_with_remainder();
2703            span = span.try_seconds(secs)?;
2704            dur = rem;
2705        }
2706        if largest >= Unit::Millisecond {
2707            let (millis, rem) = dur.as_millis_with_remainder();
2708            let millis = i64::try_from(millis)
2709                .map_err(|_| b::SpanMilliseconds::error())?;
2710            span = span.try_milliseconds(millis)?;
2711            dur = rem;
2712        }
2713        if largest >= Unit::Microsecond {
2714            let (micros, rem) = dur.as_micros_with_remainder();
2715            let micros = i64::try_from(micros)
2716                .map_err(|_| b::SpanMicroseconds::error())?;
2717            span = span.try_microseconds(micros)?;
2718            dur = rem;
2719        }
2720        if largest >= Unit::Nanosecond {
2721            let nanos = i64::try_from(dur.as_nanos())
2722                .map_err(|_| b::SpanNanoseconds::error())?;
2723            span = span.try_nanoseconds(nanos)?;
2724        }
2725
2726        Ok(span)
2727    }
2728
2729    /// Converts the hour, minute and second units in this `Span` to seconds.
2730    ///
2731    /// This ignores all other units.
2732    #[inline]
2733    pub(crate) fn to_hms_seconds(&self) -> i64 {
2734        // This can never overflow because the maximal values for hours,
2735        // minutes and seconds (even when combined) can fit into an `i64`.
2736        let mut secs = self.seconds;
2737        secs += self.minutes * b::SECS_PER_MIN;
2738        secs += i64::from(self.hours) * b::SECS_PER_HOUR;
2739        self.sign * secs
2740    }
2741
2742    /// Returns true if and only if this span has at least one non-zero
2743    /// fractional second unit.
2744    #[inline]
2745    pub(crate) fn has_fractional_seconds(&self) -> bool {
2746        static SUBSECOND: UnitSet = UnitSet::from_slice(&[
2747            Unit::Millisecond,
2748            Unit::Microsecond,
2749            Unit::Nanosecond,
2750        ]);
2751        !self.units().intersection(SUBSECOND).is_empty()
2752    }
2753
2754    /// Returns an equivalent span, but with all non-calendar (units below
2755    /// days) set to zero.
2756    #[cfg_attr(feature = "perf-inline", inline(always))]
2757    pub(crate) fn only_calendar(mut self) -> Span {
2758        self.hours = 0;
2759        self.minutes = 0;
2760        self.seconds = 0;
2761        self.milliseconds = 0;
2762        self.microseconds = 0;
2763        self.nanoseconds = 0;
2764        if !self.sign.is_zero()
2765            && self.years == 0
2766            && self.months == 0
2767            && self.weeks == 0
2768            && self.days == 0
2769        {
2770            self.sign = b::Sign::Zero;
2771        }
2772        self.units = self.units.only_calendar();
2773        self
2774    }
2775
2776    /// Returns an equivalent span, but with all calendar (units above
2777    /// hours) set to zero.
2778    #[cfg_attr(feature = "perf-inline", inline(always))]
2779    pub(crate) fn only_time(mut self) -> Span {
2780        self.years = 0;
2781        self.months = 0;
2782        self.weeks = 0;
2783        self.days = 0;
2784        if !self.sign.is_zero()
2785            && self.hours == 0
2786            && self.minutes == 0
2787            && self.seconds == 0
2788            && self.milliseconds == 0
2789            && self.microseconds == 0
2790            && self.nanoseconds == 0
2791        {
2792            self.sign = b::Sign::Zero;
2793        }
2794        self.units = self.units.only_time();
2795        self
2796    }
2797
2798    /// Returns an equivalent span, but with all units greater than or equal to
2799    /// the one given set to zero.
2800    #[cfg_attr(feature = "perf-inline", inline(always))]
2801    pub(crate) fn only_lower(self, unit: Unit) -> Span {
2802        let mut span = self;
2803        // Unit::Nanosecond is the minimum, so nothing can be smaller than it.
2804        if unit <= Unit::Microsecond {
2805            span = span.microseconds(0);
2806        }
2807        if unit <= Unit::Millisecond {
2808            span = span.milliseconds(0);
2809        }
2810        if unit <= Unit::Second {
2811            span = span.seconds(0);
2812        }
2813        if unit <= Unit::Minute {
2814            span = span.minutes(0);
2815        }
2816        if unit <= Unit::Hour {
2817            span = span.hours(0);
2818        }
2819        if unit <= Unit::Day {
2820            span = span.days(0);
2821        }
2822        if unit <= Unit::Week {
2823            span = span.weeks(0);
2824        }
2825        if unit <= Unit::Month {
2826            span = span.months(0);
2827        }
2828        if unit <= Unit::Year {
2829            span = span.years(0);
2830        }
2831        span
2832    }
2833
2834    /// Returns an equivalent span, but with all units less than the one given
2835    /// set to zero.
2836    #[cfg_attr(feature = "perf-inline", inline(always))]
2837    pub(crate) fn without_lower(self, unit: Unit) -> Span {
2838        let mut span = self;
2839        if unit > Unit::Nanosecond {
2840            span = span.nanoseconds(0);
2841        }
2842        if unit > Unit::Microsecond {
2843            span = span.microseconds(0);
2844        }
2845        if unit > Unit::Millisecond {
2846            span = span.milliseconds(0);
2847        }
2848        if unit > Unit::Second {
2849            span = span.seconds(0);
2850        }
2851        if unit > Unit::Minute {
2852            span = span.minutes(0);
2853        }
2854        if unit > Unit::Hour {
2855            span = span.hours(0);
2856        }
2857        if unit > Unit::Day {
2858            span = span.days(0);
2859        }
2860        if unit > Unit::Week {
2861            span = span.weeks(0);
2862        }
2863        if unit > Unit::Month {
2864            span = span.months(0);
2865        }
2866        // Unit::Year is the max, so nothing can be bigger than it.
2867        span
2868    }
2869
2870    /// Returns an error corresponding to the smallest non-time non-zero unit.
2871    ///
2872    /// If all non-time units are zero, then this returns `None`.
2873    #[cfg_attr(feature = "perf-inline", inline(always))]
2874    pub(crate) fn smallest_non_time_non_zero_unit_error(
2875        &self,
2876    ) -> Option<Error> {
2877        let non_time_unit = self.largest_calendar_unit()?;
2878        Some(Error::from(UnitConfigError::CalendarUnitsNotAllowed {
2879            unit: non_time_unit,
2880        }))
2881    }
2882
2883    /// Returns the largest non-zero calendar unit, or `None` if there are no
2884    /// non-zero calendar units.
2885    #[inline]
2886    fn largest_calendar_unit(&self) -> Option<Unit> {
2887        self.units().only_calendar().largest_unit()
2888    }
2889
2890    /// Returns the largest non-zero unit in this span.
2891    ///
2892    /// If all components of this span are zero, then `Unit::Nanosecond` is
2893    /// returned.
2894    #[inline]
2895    pub(crate) fn largest_unit(&self) -> Unit {
2896        self.units().largest_unit().unwrap_or(Unit::Nanosecond)
2897    }
2898
2899    /// Returns the set of units on this `Span`.
2900    #[inline]
2901    pub(crate) fn units(&self) -> UnitSet {
2902        self.units
2903    }
2904
2905    /// Returns a string containing the value of all non-zero fields.
2906    ///
2907    /// This is useful for debugging. Normally, this would be the "alternate"
2908    /// debug impl (perhaps), but that's what insta uses and I preferred having
2909    /// the friendly format used there since it is much more terse.
2910    #[cfg(feature = "alloc")]
2911    #[allow(dead_code)]
2912    pub(crate) fn debug(&self) -> alloc::string::String {
2913        use core::fmt::Write;
2914
2915        let mut buf = alloc::string::String::new();
2916        write!(buf, "Span {{ sign: {:?}, units: {:?}", self.sign, self.units)
2917            .unwrap();
2918        if self.years != 0 {
2919            write!(buf, ", years: {:?}", self.years).unwrap();
2920        }
2921        if self.months != 0 {
2922            write!(buf, ", months: {:?}", self.months).unwrap();
2923        }
2924        if self.weeks != 0 {
2925            write!(buf, ", weeks: {:?}", self.weeks).unwrap();
2926        }
2927        if self.days != 0 {
2928            write!(buf, ", days: {:?}", self.days).unwrap();
2929        }
2930        if self.hours != 0 {
2931            write!(buf, ", hours: {:?}", self.hours).unwrap();
2932        }
2933        if self.minutes != 0 {
2934            write!(buf, ", minutes: {:?}", self.minutes).unwrap();
2935        }
2936        if self.seconds != 0 {
2937            write!(buf, ", seconds: {:?}", self.seconds).unwrap();
2938        }
2939        if self.milliseconds != 0 {
2940            write!(buf, ", milliseconds: {:?}", self.milliseconds).unwrap();
2941        }
2942        if self.microseconds != 0 {
2943            write!(buf, ", microseconds: {:?}", self.microseconds).unwrap();
2944        }
2945        if self.nanoseconds != 0 {
2946            write!(buf, ", nanoseconds: {:?}", self.nanoseconds).unwrap();
2947        }
2948        buf.push_str(" }}");
2949        buf
2950    }
2951
2952    /// Given some new units to set on this span and the span updates with the
2953    /// new units, this determines the what the sign of `new` should be.
2954    #[inline]
2955    fn resign(&self, units: impl Into<i64>, new: &Span) -> b::Sign {
2956        fn imp(span: &Span, units: i64, new: &Span) -> b::Sign {
2957            // Negative units anywhere always makes the entire span negative.
2958            if units.is_negative() {
2959                return b::Sign::Negative;
2960            }
2961            let mut new_is_zero = new.sign.is_zero() && units == 0;
2962            // When `units == 0` and it was previously non-zero, then
2963            // `new.sign` won't be `0` and thus `new_is_zero` will be false
2964            // when it should be true. So in this case, we need to re-check all
2965            // the units to set the sign correctly.
2966            if units == 0 {
2967                new_is_zero = new.years == 0
2968                    && new.months == 0
2969                    && new.weeks == 0
2970                    && new.days == 0
2971                    && new.hours == 0
2972                    && new.minutes == 0
2973                    && new.seconds == 0
2974                    && new.milliseconds == 0
2975                    && new.microseconds == 0
2976                    && new.nanoseconds == 0;
2977            }
2978            match (span.is_zero(), new_is_zero) {
2979                (_, true) => b::Sign::Zero,
2980                (true, false) => b::Sign::from(units),
2981                // If the old and new span are both non-zero, and we know our
2982                // new units are not negative, then the sign remains unchanged.
2983                (false, false) => new.sign,
2984            }
2985        }
2986        imp(self, units.into(), new)
2987    }
2988}
2989
2990impl core::fmt::Debug for Span {
2991    #[inline]
2992    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2993        use crate::fmt::StdFmtWrite;
2994
2995        friendly::DEFAULT_SPAN_PRINTER
2996            .print_span(self, StdFmtWrite(f))
2997            .map_err(|_| core::fmt::Error)
2998    }
2999}
3000
3001impl core::fmt::Display for Span {
3002    #[inline]
3003    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
3004        use crate::fmt::StdFmtWrite;
3005
3006        if f.alternate() {
3007            friendly::DEFAULT_SPAN_PRINTER
3008                .print_span(self, StdFmtWrite(f))
3009                .map_err(|_| core::fmt::Error)
3010        } else {
3011            temporal::DEFAULT_SPAN_PRINTER
3012                .print_span(self, StdFmtWrite(f))
3013                .map_err(|_| core::fmt::Error)
3014        }
3015    }
3016}
3017
3018impl core::str::FromStr for Span {
3019    type Err = Error;
3020
3021    #[inline]
3022    fn from_str(string: &str) -> Result<Span, Error> {
3023        parse_iso_or_friendly(string.as_bytes())
3024    }
3025}
3026
3027impl core::ops::Neg for Span {
3028    type Output = Span;
3029
3030    #[inline]
3031    fn neg(self) -> Span {
3032        self.negate()
3033    }
3034}
3035
3036/// This multiplies each unit in a span by an integer.
3037///
3038/// This panics on overflow. For checked arithmetic, use [`Span::checked_mul`].
3039impl core::ops::Mul<i64> for Span {
3040    type Output = Span;
3041
3042    #[inline]
3043    fn mul(self, rhs: i64) -> Span {
3044        self.checked_mul(rhs)
3045            .expect("multiplying `Span` by a scalar overflowed")
3046    }
3047}
3048
3049/// This multiplies each unit in a span by an integer.
3050///
3051/// This panics on overflow. For checked arithmetic, use [`Span::checked_mul`].
3052impl core::ops::Mul<Span> for i64 {
3053    type Output = Span;
3054
3055    #[inline]
3056    fn mul(self, rhs: Span) -> Span {
3057        rhs.checked_mul(self)
3058            .expect("multiplying `Span` by a scalar overflowed")
3059    }
3060}
3061
3062/// Converts a `Span` to a [`std::time::Duration`].
3063///
3064/// # Errors
3065///
3066/// This can fail for only two reasons:
3067///
3068/// * The span is negative. This is an error because a `std::time::Duration` is
3069///   unsigned.)
3070/// * The span has any non-zero units greater than hours. This is an error
3071///   because it's impossible to determine the length of, e.g., a month without
3072///   a reference date.
3073///
3074/// This can never result in overflow because a `Duration` can represent a
3075/// bigger span of time than `Span` when limited to units of hours or lower.
3076///
3077/// If you need to convert a `Span` to a `Duration` that has non-zero
3078/// units bigger than hours, then please use [`Span::to_duration`] with a
3079/// corresponding relative date.
3080///
3081/// # Example: maximal span
3082///
3083/// This example shows the maximum possible span using units of hours or
3084/// smaller, and the corresponding `Duration` value:
3085///
3086/// ```
3087/// use std::time::Duration;
3088///
3089/// use jiff::Span;
3090///
3091/// let sp = Span::new()
3092///     .hours(175_307_616)
3093///     .minutes(10_518_456_960i64)
3094///     .seconds(631_107_417_600i64)
3095///     .milliseconds(631_107_417_600_000i64)
3096///     .microseconds(631_107_417_600_000_000i64)
3097///     .nanoseconds(9_223_372_036_854_775_807i64);
3098/// let duration = Duration::try_from(sp)?;
3099/// assert_eq!(duration, Duration::new(3_164_760_460_036, 854_775_807));
3100///
3101/// # Ok::<(), Box<dyn std::error::Error>>(())
3102/// ```
3103///
3104/// # Example: converting a negative span
3105///
3106/// Since a `Span` is signed and a `Duration` is unsigned, converting
3107/// a negative `Span` to `Duration` will always fail. One can use
3108/// [`Span::signum`] to get the sign of the span and [`Span::abs`] to make the
3109/// span positive before converting it to a `Duration`:
3110///
3111/// ```
3112/// use std::time::Duration;
3113///
3114/// use jiff::{Span, ToSpan};
3115///
3116/// let span = -86_400.seconds().nanoseconds(1);
3117/// let (sign, duration) = (span.signum(), Duration::try_from(span.abs())?);
3118/// assert_eq!((sign, duration), (-1, Duration::new(86_400, 1)));
3119///
3120/// # Ok::<(), Box<dyn std::error::Error>>(())
3121/// ```
3122impl TryFrom<Span> for UnsignedDuration {
3123    type Error = Error;
3124
3125    #[inline]
3126    fn try_from(sp: Span) -> Result<UnsignedDuration, Error> {
3127        // This isn't needed, but improves error messages.
3128        if sp.is_negative() {
3129            return Err(Error::from(E::ConvertNegative));
3130        }
3131        SignedDuration::try_from(sp).and_then(UnsignedDuration::try_from)
3132    }
3133}
3134
3135/// Converts a [`std::time::Duration`] to a `Span`.
3136///
3137/// The span returned from this conversion will only ever have non-zero units
3138/// of seconds or smaller.
3139///
3140/// # Errors
3141///
3142/// This only fails when the given `Duration` overflows the maximum number of
3143/// seconds representable by a `Span`.
3144///
3145/// # Example
3146///
3147/// This shows a basic conversion:
3148///
3149/// ```
3150/// use std::time::Duration;
3151///
3152/// use jiff::{Span, ToSpan};
3153///
3154/// let duration = Duration::new(86_400, 123_456_789);
3155/// let span = Span::try_from(duration)?;
3156/// // A duration-to-span conversion always results in a span with
3157/// // non-zero units no bigger than seconds.
3158/// assert_eq!(
3159///     span.fieldwise(),
3160///     86_400.seconds().milliseconds(123).microseconds(456).nanoseconds(789),
3161/// );
3162///
3163/// # Ok::<(), Box<dyn std::error::Error>>(())
3164/// ```
3165///
3166/// # Example: rounding
3167///
3168/// This example shows how to convert a `Duration` to a `Span`, and then round
3169/// it up to bigger units given a relative date:
3170///
3171/// ```
3172/// use std::time::Duration;
3173///
3174/// use jiff::{civil::date, Span, SpanRound, ToSpan, Unit};
3175///
3176/// let duration = Duration::new(450 * 86_401, 0);
3177/// let span = Span::try_from(duration)?;
3178/// // We get back a simple span of just seconds:
3179/// assert_eq!(span.fieldwise(), Span::new().seconds(450 * 86_401));
3180/// // But we can balance it up to bigger units:
3181/// let options = SpanRound::new()
3182///     .largest(Unit::Year)
3183///     .relative(date(2024, 1, 1));
3184/// assert_eq!(
3185///     span.round(options)?,
3186///     1.year().months(2).days(25).minutes(7).seconds(30).fieldwise(),
3187/// );
3188///
3189/// # Ok::<(), Box<dyn std::error::Error>>(())
3190/// ```
3191impl TryFrom<UnsignedDuration> for Span {
3192    type Error = Error;
3193
3194    #[inline]
3195    fn try_from(d: UnsignedDuration) -> Result<Span, Error> {
3196        let sdur = SignedDuration::try_from(d)
3197            .map_err(|_| b::SpanSeconds::error())?;
3198        Span::try_from(sdur)
3199    }
3200}
3201
3202/// Converts a `Span` to a [`SignedDuration`].
3203///
3204/// # Errors
3205///
3206/// This can fail for only when the span has any non-zero units greater than
3207/// hours. This is an error because it's impossible to determine the length of,
3208/// e.g., a month without a reference date.
3209///
3210/// This can never result in overflow because a `SignedDuration` can represent
3211/// a bigger span of time than `Span` when limited to units of hours or lower.
3212///
3213/// If you need to convert a `Span` to a `SignedDuration` that has non-zero
3214/// units bigger than hours, then please use [`Span::to_duration`] with a
3215/// corresponding relative date.
3216///
3217/// # Example: maximal span
3218///
3219/// This example shows the maximum possible span using units of hours or
3220/// smaller, and the corresponding `SignedDuration` value:
3221///
3222/// ```
3223/// use jiff::{SignedDuration, Span};
3224///
3225/// let sp = Span::new()
3226///     .hours(175_307_616)
3227///     .minutes(10_518_456_960i64)
3228///     .seconds(631_107_417_600i64)
3229///     .milliseconds(631_107_417_600_000i64)
3230///     .microseconds(631_107_417_600_000_000i64)
3231///     .nanoseconds(9_223_372_036_854_775_807i64);
3232/// let duration = SignedDuration::try_from(sp)?;
3233/// assert_eq!(duration, SignedDuration::new(3_164_760_460_036, 854_775_807));
3234///
3235/// # Ok::<(), Box<dyn std::error::Error>>(())
3236/// ```
3237impl TryFrom<Span> for SignedDuration {
3238    type Error = Error;
3239
3240    #[inline]
3241    fn try_from(sp: Span) -> Result<SignedDuration, Error> {
3242        requires_relative_date_err(sp.largest_unit())
3243            .context(E::ConvertSpanToSignedDuration)?;
3244        Ok(sp.to_invariant_duration())
3245    }
3246}
3247
3248/// Converts a [`SignedDuration`] to a `Span`.
3249///
3250/// The span returned from this conversion will only ever have non-zero units
3251/// of seconds or smaller.
3252///
3253/// # Errors
3254///
3255/// This only fails when the given `SignedDuration` overflows the maximum
3256/// number of seconds representable by a `Span`.
3257///
3258/// # Example
3259///
3260/// This shows a basic conversion:
3261///
3262/// ```
3263/// use jiff::{SignedDuration, Span, ToSpan};
3264///
3265/// let duration = SignedDuration::new(86_400, 123_456_789);
3266/// let span = Span::try_from(duration)?;
3267/// // A duration-to-span conversion always results in a span with
3268/// // non-zero units no bigger than seconds.
3269/// assert_eq!(
3270///     span.fieldwise(),
3271///     86_400.seconds().milliseconds(123).microseconds(456).nanoseconds(789),
3272/// );
3273///
3274/// # Ok::<(), Box<dyn std::error::Error>>(())
3275/// ```
3276///
3277/// # Example: rounding
3278///
3279/// This example shows how to convert a `SignedDuration` to a `Span`, and then
3280/// round it up to bigger units given a relative date:
3281///
3282/// ```
3283/// use jiff::{civil::date, SignedDuration, Span, SpanRound, ToSpan, Unit};
3284///
3285/// let duration = SignedDuration::new(450 * 86_401, 0);
3286/// let span = Span::try_from(duration)?;
3287/// // We get back a simple span of just seconds:
3288/// assert_eq!(span.fieldwise(), Span::new().seconds(450 * 86_401));
3289/// // But we can balance it up to bigger units:
3290/// let options = SpanRound::new()
3291///     .largest(Unit::Year)
3292///     .relative(date(2024, 1, 1));
3293/// assert_eq!(
3294///     span.round(options)?,
3295///     1.year().months(2).days(25).minutes(7).seconds(30).fieldwise(),
3296/// );
3297///
3298/// # Ok::<(), Box<dyn std::error::Error>>(())
3299/// ```
3300impl TryFrom<SignedDuration> for Span {
3301    type Error = Error;
3302
3303    #[inline]
3304    fn try_from(d: SignedDuration) -> Result<Span, Error> {
3305        let seconds = d.as_secs();
3306        let nanoseconds = i64::from(d.subsec_nanos());
3307        let milliseconds = nanoseconds / b::NANOS_PER_MILLI;
3308        let microseconds =
3309            (nanoseconds % b::NANOS_PER_MILLI) / b::NANOS_PER_MICRO;
3310        let nanoseconds = nanoseconds % b::NANOS_PER_MICRO;
3311
3312        let span = Span::new().try_seconds(seconds)?;
3313        // These are all OK because `|SignedDuration::subsec_nanos|` is
3314        // guaranteed to return less than 1_000_000_000 nanoseconds. And
3315        // splitting that up into millis, micros and nano components is
3316        // guaranteed to fit into the limits of a `Span`.
3317        Ok(span
3318            .milliseconds(milliseconds)
3319            .microseconds(microseconds)
3320            .nanoseconds(nanoseconds))
3321    }
3322}
3323
3324#[cfg(feature = "serde")]
3325impl serde_core::Serialize for Span {
3326    #[inline]
3327    fn serialize<S: serde_core::Serializer>(
3328        &self,
3329        serializer: S,
3330    ) -> Result<S::Ok, S::Error> {
3331        serializer.collect_str(self)
3332    }
3333}
3334
3335#[cfg(feature = "serde")]
3336impl<'de> serde_core::Deserialize<'de> for Span {
3337    #[inline]
3338    fn deserialize<D: serde_core::Deserializer<'de>>(
3339        deserializer: D,
3340    ) -> Result<Span, D::Error> {
3341        use serde_core::de;
3342
3343        struct SpanVisitor;
3344
3345        impl<'de> de::Visitor<'de> for SpanVisitor {
3346            type Value = Span;
3347
3348            fn expecting(
3349                &self,
3350                f: &mut core::fmt::Formatter,
3351            ) -> core::fmt::Result {
3352                f.write_str("a span duration string")
3353            }
3354
3355            #[inline]
3356            fn visit_bytes<E: de::Error>(
3357                self,
3358                value: &[u8],
3359            ) -> Result<Span, E> {
3360                parse_iso_or_friendly(value).map_err(de::Error::custom)
3361            }
3362
3363            #[inline]
3364            fn visit_str<E: de::Error>(self, value: &str) -> Result<Span, E> {
3365                self.visit_bytes(value.as_bytes())
3366            }
3367        }
3368
3369        deserializer.deserialize_str(SpanVisitor)
3370    }
3371}
3372
3373#[cfg(test)]
3374impl quickcheck::Arbitrary for Span {
3375    fn arbitrary(g: &mut quickcheck::Gen) -> Span {
3376        // In order to sample from the full space of possible spans, we need
3377        // to provide a relative datetime. But if we do that, then it's
3378        // possible the span plus the datetime overflows. So we pick one
3379        // datetime and shrink the size of the span we can produce.
3380        const MIN: i64 = -631_107_417_600_000_000;
3381        const MAX: i64 = 631_107_417_600_000_000;
3382        const LEN: i64 = MAX - MIN + 1;
3383
3384        let mut nanos = i64::arbitrary(g).wrapping_rem_euclid(LEN);
3385        nanos += MIN;
3386        let relative =
3387            SpanRelativeTo::from(DateTime::constant(0, 1, 1, 0, 0, 0, 0));
3388        let round =
3389            SpanRound::new().largest(Unit::arbitrary(g)).relative(relative);
3390        Span::new().nanoseconds(nanos).round(round).unwrap()
3391    }
3392
3393    fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Self>> {
3394        alloc::boxed::Box::new(
3395            (
3396                (
3397                    self.get_years(),
3398                    self.get_months(),
3399                    self.get_weeks(),
3400                    self.get_days(),
3401                ),
3402                (
3403                    self.get_hours(),
3404                    self.get_minutes(),
3405                    self.get_seconds(),
3406                    self.get_milliseconds(),
3407                ),
3408                (self.get_microseconds(), self.get_nanoseconds()),
3409            )
3410                .shrink()
3411                .filter_map(
3412                    |(
3413                        (years, months, weeks, days),
3414                        (hours, minutes, seconds, milliseconds),
3415                        (microseconds, nanoseconds),
3416                    )| {
3417                        let span = Span::new()
3418                            .try_years(years)
3419                            .ok()?
3420                            .try_months(months)
3421                            .ok()?
3422                            .try_weeks(weeks)
3423                            .ok()?
3424                            .try_days(days)
3425                            .ok()?
3426                            .try_hours(hours)
3427                            .ok()?
3428                            .try_minutes(minutes)
3429                            .ok()?
3430                            .try_seconds(seconds)
3431                            .ok()?
3432                            .try_milliseconds(milliseconds)
3433                            .ok()?
3434                            .try_microseconds(microseconds)
3435                            .ok()?
3436                            .try_nanoseconds(nanoseconds)
3437                            .ok()?;
3438                        Some(span)
3439                    },
3440                ),
3441        )
3442    }
3443}
3444
3445/// A wrapper for [`Span`] that implements the `Hash`, `Eq` and `PartialEq`
3446/// traits.
3447///
3448/// A `SpanFieldwise` is meant to make it easy to compare two spans in a "dumb"
3449/// way based purely on its unit values, while still providing a speed bump
3450/// to avoid accidentally doing this comparison on `Span` directly. This is
3451/// distinct from something like [`Span::compare`] that performs a comparison
3452/// on the actual elapsed time of two spans.
3453///
3454/// It is generally discouraged to use `SpanFieldwise` since spans that
3455/// represent an equivalent elapsed amount of time may compare unequal.
3456/// However, in some cases, it is useful to be able to assert precise field
3457/// values. For example, Jiff itself makes heavy use of fieldwise comparisons
3458/// for tests.
3459///
3460/// # Construction
3461///
3462/// While callers may use `SpanFieldwise(span)` (where `span` has type [`Span`])
3463/// to construct a value of this type, callers may find [`Span::fieldwise`]
3464/// more convenient. Namely, `Span::fieldwise` may avoid the need to explicitly
3465/// import `SpanFieldwise`.
3466///
3467/// # Trait implementations
3468///
3469/// In addition to implementing the `Hash`, `Eq` and `PartialEq` traits, this
3470/// type also provides `PartialEq` impls for comparing a `Span` with a
3471/// `SpanFieldwise`. This simplifies comparisons somewhat while still requiring
3472/// that at least one of the values has an explicit fieldwise comparison type.
3473///
3474/// # Safety
3475///
3476/// This type is guaranteed to have the same layout in memory as [`Span`].
3477///
3478/// # Example: the difference between `SpanFieldwise` and [`Span::compare`]
3479///
3480/// In short, `SpanFieldwise` considers `2 hours` and `120 minutes` to be
3481/// distinct values, but `Span::compare` considers them to be equivalent:
3482///
3483/// ```
3484/// use std::cmp::Ordering;
3485/// use jiff::ToSpan;
3486///
3487/// assert_ne!(120.minutes().fieldwise(), 2.hours().fieldwise());
3488/// assert_eq!(120.minutes().compare(2.hours())?, Ordering::Equal);
3489///
3490/// // These comparisons are allowed between a `Span` and a `SpanFieldwise`.
3491/// // Namely, as long as one value is "fieldwise," then the comparison is OK.
3492/// assert_ne!(120.minutes().fieldwise(), 2.hours());
3493/// assert_ne!(120.minutes(), 2.hours().fieldwise());
3494///
3495/// # Ok::<(), Box<dyn std::error::Error>>(())
3496/// ```
3497#[derive(Clone, Copy, Debug, Default)]
3498#[repr(transparent)]
3499pub struct SpanFieldwise(pub Span);
3500
3501// Exists so that things like `-1.day().fieldwise()` works as expected.
3502impl core::ops::Neg for SpanFieldwise {
3503    type Output = SpanFieldwise;
3504
3505    #[inline]
3506    fn neg(self) -> SpanFieldwise {
3507        SpanFieldwise(self.0.negate())
3508    }
3509}
3510
3511impl Eq for SpanFieldwise {}
3512
3513impl PartialEq for SpanFieldwise {
3514    fn eq(&self, rhs: &SpanFieldwise) -> bool {
3515        self.0.sign == rhs.0.sign
3516            && self.0.years == rhs.0.years
3517            && self.0.months == rhs.0.months
3518            && self.0.weeks == rhs.0.weeks
3519            && self.0.days == rhs.0.days
3520            && self.0.hours == rhs.0.hours
3521            && self.0.minutes == rhs.0.minutes
3522            && self.0.seconds == rhs.0.seconds
3523            && self.0.milliseconds == rhs.0.milliseconds
3524            && self.0.microseconds == rhs.0.microseconds
3525            && self.0.nanoseconds == rhs.0.nanoseconds
3526    }
3527}
3528
3529impl<'a> PartialEq<SpanFieldwise> for &'a SpanFieldwise {
3530    fn eq(&self, rhs: &SpanFieldwise) -> bool {
3531        *self == rhs
3532    }
3533}
3534
3535impl PartialEq<Span> for SpanFieldwise {
3536    fn eq(&self, rhs: &Span) -> bool {
3537        self == rhs.fieldwise()
3538    }
3539}
3540
3541impl PartialEq<SpanFieldwise> for Span {
3542    fn eq(&self, rhs: &SpanFieldwise) -> bool {
3543        self.fieldwise() == *rhs
3544    }
3545}
3546
3547impl<'a> PartialEq<SpanFieldwise> for &'a Span {
3548    fn eq(&self, rhs: &SpanFieldwise) -> bool {
3549        self.fieldwise() == *rhs
3550    }
3551}
3552
3553impl core::hash::Hash for SpanFieldwise {
3554    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
3555        self.0.sign.hash(state);
3556        self.0.years.hash(state);
3557        self.0.months.hash(state);
3558        self.0.weeks.hash(state);
3559        self.0.days.hash(state);
3560        self.0.hours.hash(state);
3561        self.0.minutes.hash(state);
3562        self.0.seconds.hash(state);
3563        self.0.milliseconds.hash(state);
3564        self.0.microseconds.hash(state);
3565        self.0.nanoseconds.hash(state);
3566    }
3567}
3568
3569impl From<Span> for SpanFieldwise {
3570    fn from(span: Span) -> SpanFieldwise {
3571        SpanFieldwise(span)
3572    }
3573}
3574
3575impl From<SpanFieldwise> for Span {
3576    fn from(span: SpanFieldwise) -> Span {
3577        span.0
3578    }
3579}
3580
3581/// A trait for enabling concise literals for creating [`Span`] values.
3582///
3583/// In short, this trait lets you write something like `5.seconds()` or
3584/// `1.day()` to create a [`Span`]. Once a `Span` has been created, you can
3585/// use its mutator methods to add more fields. For example,
3586/// `1.day().hours(10)` is equivalent to `Span::new().days(1).hours(10)`.
3587///
3588/// This trait is implemented for the following integer types: `i8`, `i16`,
3589/// `i32` and `i64`.
3590///
3591/// Note that this trait is provided as a convenience and should generally
3592/// only be used for literals in your source code. You should not use this
3593/// trait on numbers provided by end users. Namely, if the number provided
3594/// is not within Jiff's span limits, then these trait methods will panic.
3595/// Instead, use fallible mutator constructors like [`Span::try_days`]
3596/// or [`Span::try_seconds`].
3597///
3598/// # Example
3599///
3600/// ```
3601/// use jiff::ToSpan;
3602///
3603/// assert_eq!(5.days().to_string(), "P5D");
3604/// assert_eq!(5.days().hours(10).to_string(), "P5DT10H");
3605///
3606/// // Negation works and it doesn't matter where the sign goes. It can be
3607/// // applied to the span itself or to the integer.
3608/// assert_eq!((-5.days()).to_string(), "-P5D");
3609/// assert_eq!((-5).days().to_string(), "-P5D");
3610/// ```
3611///
3612/// # Example: alternative via span parsing
3613///
3614/// Another way of tersely building a `Span` value is by parsing a ISO 8601
3615/// duration string:
3616///
3617/// ```
3618/// use jiff::Span;
3619///
3620/// let span = "P5y2m15dT23h30m10s".parse::<Span>()?;
3621/// assert_eq!(
3622///     span.fieldwise(),
3623///     Span::new().years(5).months(2).days(15).hours(23).minutes(30).seconds(10),
3624/// );
3625///
3626/// # Ok::<(), Box<dyn std::error::Error>>(())
3627/// ```
3628pub trait ToSpan: Sized {
3629    /// Create a new span from this integer in units of years.
3630    ///
3631    /// # Panics
3632    ///
3633    /// When `Span::new().years(self)` would panic.
3634    fn years(self) -> Span;
3635
3636    /// Create a new span from this integer in units of months.
3637    ///
3638    /// # Panics
3639    ///
3640    /// When `Span::new().months(self)` would panic.
3641    fn months(self) -> Span;
3642
3643    /// Create a new span from this integer in units of weeks.
3644    ///
3645    /// # Panics
3646    ///
3647    /// When `Span::new().weeks(self)` would panic.
3648    fn weeks(self) -> Span;
3649
3650    /// Create a new span from this integer in units of days.
3651    ///
3652    /// # Panics
3653    ///
3654    /// When `Span::new().days(self)` would panic.
3655    fn days(self) -> Span;
3656
3657    /// Create a new span from this integer in units of hours.
3658    ///
3659    /// # Panics
3660    ///
3661    /// When `Span::new().hours(self)` would panic.
3662    fn hours(self) -> Span;
3663
3664    /// Create a new span from this integer in units of minutes.
3665    ///
3666    /// # Panics
3667    ///
3668    /// When `Span::new().minutes(self)` would panic.
3669    fn minutes(self) -> Span;
3670
3671    /// Create a new span from this integer in units of seconds.
3672    ///
3673    /// # Panics
3674    ///
3675    /// When `Span::new().seconds(self)` would panic.
3676    fn seconds(self) -> Span;
3677
3678    /// Create a new span from this integer in units of milliseconds.
3679    ///
3680    /// # Panics
3681    ///
3682    /// When `Span::new().milliseconds(self)` would panic.
3683    fn milliseconds(self) -> Span;
3684
3685    /// Create a new span from this integer in units of microseconds.
3686    ///
3687    /// # Panics
3688    ///
3689    /// When `Span::new().microseconds(self)` would panic.
3690    fn microseconds(self) -> Span;
3691
3692    /// Create a new span from this integer in units of nanoseconds.
3693    ///
3694    /// # Panics
3695    ///
3696    /// When `Span::new().nanoseconds(self)` would panic.
3697    fn nanoseconds(self) -> Span;
3698
3699    /// Equivalent to `years()`, but reads better for singular units.
3700    #[inline]
3701    fn year(self) -> Span {
3702        self.years()
3703    }
3704
3705    /// Equivalent to `months()`, but reads better for singular units.
3706    #[inline]
3707    fn month(self) -> Span {
3708        self.months()
3709    }
3710
3711    /// Equivalent to `weeks()`, but reads better for singular units.
3712    #[inline]
3713    fn week(self) -> Span {
3714        self.weeks()
3715    }
3716
3717    /// Equivalent to `days()`, but reads better for singular units.
3718    #[inline]
3719    fn day(self) -> Span {
3720        self.days()
3721    }
3722
3723    /// Equivalent to `hours()`, but reads better for singular units.
3724    #[inline]
3725    fn hour(self) -> Span {
3726        self.hours()
3727    }
3728
3729    /// Equivalent to `minutes()`, but reads better for singular units.
3730    #[inline]
3731    fn minute(self) -> Span {
3732        self.minutes()
3733    }
3734
3735    /// Equivalent to `seconds()`, but reads better for singular units.
3736    #[inline]
3737    fn second(self) -> Span {
3738        self.seconds()
3739    }
3740
3741    /// Equivalent to `milliseconds()`, but reads better for singular units.
3742    #[inline]
3743    fn millisecond(self) -> Span {
3744        self.milliseconds()
3745    }
3746
3747    /// Equivalent to `microseconds()`, but reads better for singular units.
3748    #[inline]
3749    fn microsecond(self) -> Span {
3750        self.microseconds()
3751    }
3752
3753    /// Equivalent to `nanoseconds()`, but reads better for singular units.
3754    #[inline]
3755    fn nanosecond(self) -> Span {
3756        self.nanoseconds()
3757    }
3758}
3759
3760macro_rules! impl_to_span {
3761    ($ty:ty) => {
3762        impl ToSpan for $ty {
3763            #[inline]
3764            fn years(self) -> Span {
3765                Span::new().years(self)
3766            }
3767            #[inline]
3768            fn months(self) -> Span {
3769                Span::new().months(self)
3770            }
3771            #[inline]
3772            fn weeks(self) -> Span {
3773                Span::new().weeks(self)
3774            }
3775            #[inline]
3776            fn days(self) -> Span {
3777                Span::new().days(self)
3778            }
3779            #[inline]
3780            fn hours(self) -> Span {
3781                Span::new().hours(self)
3782            }
3783            #[inline]
3784            fn minutes(self) -> Span {
3785                Span::new().minutes(self)
3786            }
3787            #[inline]
3788            fn seconds(self) -> Span {
3789                Span::new().seconds(self)
3790            }
3791            #[inline]
3792            fn milliseconds(self) -> Span {
3793                Span::new().milliseconds(self)
3794            }
3795            #[inline]
3796            fn microseconds(self) -> Span {
3797                Span::new().microseconds(self)
3798            }
3799            #[inline]
3800            fn nanoseconds(self) -> Span {
3801                Span::new().nanoseconds(self)
3802            }
3803        }
3804    };
3805}
3806
3807impl_to_span!(i8);
3808impl_to_span!(i16);
3809impl_to_span!(i32);
3810impl_to_span!(i64);
3811
3812/// A way to refer to a single calendar or clock unit.
3813///
3814/// This type is principally used in APIs involving a [`Span`], which is a
3815/// duration of time. For example, routines like [`Zoned::until`] permit
3816/// specifying the largest unit of the span returned:
3817///
3818/// ```
3819/// use jiff::{Unit, Zoned};
3820///
3821/// let zdt1: Zoned = "2024-07-06 17:40-04[America/New_York]".parse()?;
3822/// let zdt2: Zoned = "2024-11-05 08:00-05[America/New_York]".parse()?;
3823/// let span = zdt1.until((Unit::Year, &zdt2))?;
3824/// assert_eq!(format!("{span:#}"), "3mo 29d 14h 20m");
3825///
3826/// # Ok::<(), Box<dyn std::error::Error>>(())
3827/// ```
3828///
3829/// But a `Unit` is also used in APIs for rounding datetimes themselves:
3830///
3831/// ```
3832/// use jiff::{Unit, Zoned};
3833///
3834/// let zdt: Zoned = "2024-07-06 17:44:22.158-04[America/New_York]".parse()?;
3835/// let nearest_minute = zdt.round(Unit::Minute)?;
3836/// assert_eq!(
3837///     nearest_minute.to_string(),
3838///     "2024-07-06T17:44:00-04:00[America/New_York]",
3839/// );
3840///
3841/// # Ok::<(), Box<dyn std::error::Error>>(())
3842/// ```
3843///
3844/// # Example: ordering
3845///
3846/// This example demonstrates that `Unit` has an ordering defined such that
3847/// bigger units compare greater than smaller units.
3848///
3849/// ```
3850/// use jiff::Unit;
3851///
3852/// assert!(Unit::Year > Unit::Nanosecond);
3853/// assert!(Unit::Day > Unit::Hour);
3854/// assert!(Unit::Hour > Unit::Minute);
3855/// assert!(Unit::Hour > Unit::Minute);
3856/// assert_eq!(Unit::Hour, Unit::Hour);
3857/// ```
3858#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
3859pub enum Unit {
3860    /// A Gregorian calendar year. It usually has 365 days for non-leap years,
3861    /// and 366 days for leap years.
3862    Year = 9,
3863    /// A Gregorian calendar month. It usually has one of 28, 29, 30 or 31
3864    /// days.
3865    Month = 8,
3866    /// A week is 7 days that either begins on Sunday or Monday.
3867    Week = 7,
3868    /// A day is usually 24 hours, but some days may have different lengths
3869    /// due to time zone transitions.
3870    Day = 6,
3871    /// An hour is always 60 minutes.
3872    Hour = 5,
3873    /// A minute is always 60 seconds. (Jiff behaves as if leap seconds do not
3874    /// exist.)
3875    Minute = 4,
3876    /// A second is always 1,000 milliseconds.
3877    Second = 3,
3878    /// A millisecond is always 1,000 microseconds.
3879    Millisecond = 2,
3880    /// A microsecond is always 1,000 nanoseconds.
3881    Microsecond = 1,
3882    /// A nanosecond is the smallest granularity of time supported by Jiff.
3883    Nanosecond = 0,
3884}
3885
3886impl Unit {
3887    /// Returns the next biggest unit, if one exists.
3888    pub(crate) fn next(&self) -> Option<Unit> {
3889        match *self {
3890            Unit::Year => None,
3891            Unit::Month => Some(Unit::Year),
3892            Unit::Week => Some(Unit::Month),
3893            Unit::Day => Some(Unit::Week),
3894            Unit::Hour => Some(Unit::Day),
3895            Unit::Minute => Some(Unit::Hour),
3896            Unit::Second => Some(Unit::Minute),
3897            Unit::Millisecond => Some(Unit::Second),
3898            Unit::Microsecond => Some(Unit::Millisecond),
3899            Unit::Nanosecond => Some(Unit::Microsecond),
3900        }
3901    }
3902
3903    /// Returns the number of nanoseconds in this unit as a 96-bit integer.
3904    ///
3905    /// This will treat weeks and days as invariant. Callers must ensure this
3906    /// is appropriate to do.
3907    ///
3908    /// # Panics
3909    ///
3910    /// When this unit is always variable. That is, years or months.
3911    pub(crate) fn duration(self) -> SignedDuration {
3912        match self {
3913            Unit::Nanosecond => SignedDuration::from_nanos(1),
3914            Unit::Microsecond => SignedDuration::from_micros(1),
3915            Unit::Millisecond => SignedDuration::from_millis(1),
3916            Unit::Second => SignedDuration::from_secs(1),
3917            Unit::Minute => SignedDuration::from_mins32(1),
3918            Unit::Hour => SignedDuration::from_hours32(1),
3919            Unit::Day => SignedDuration::from_civil_days32(1),
3920            Unit::Week => SignedDuration::from_civil_weeks32(1),
3921            unit => unreachable!("{unit:?} has no definitive time interval"),
3922        }
3923    }
3924
3925    /// Returns true when this unit is definitively variable.
3926    ///
3927    /// In effect, this is any unit bigger than 'day', because any such unit
3928    /// can vary in time depending on its reference point. A 'day' can as well,
3929    /// but we sorta special case 'day' to mean '24 hours' for cases where
3930    /// the user is dealing with civil time.
3931    fn is_variable(self) -> bool {
3932        matches!(self, Unit::Year | Unit::Month | Unit::Week | Unit::Day)
3933    }
3934
3935    /// A human readable singular description of this unit of time.
3936    pub(crate) fn singular(&self) -> &'static str {
3937        match *self {
3938            Unit::Year => "year",
3939            Unit::Month => "month",
3940            Unit::Week => "week",
3941            Unit::Day => "day",
3942            Unit::Hour => "hour",
3943            Unit::Minute => "minute",
3944            Unit::Second => "second",
3945            Unit::Millisecond => "millisecond",
3946            Unit::Microsecond => "microsecond",
3947            Unit::Nanosecond => "nanosecond",
3948        }
3949    }
3950
3951    /// A human readable plural description of this unit of time.
3952    pub(crate) fn plural(&self) -> &'static str {
3953        match *self {
3954            Unit::Year => "years",
3955            Unit::Month => "months",
3956            Unit::Week => "weeks",
3957            Unit::Day => "days",
3958            Unit::Hour => "hours",
3959            Unit::Minute => "minutes",
3960            Unit::Second => "seconds",
3961            Unit::Millisecond => "milliseconds",
3962            Unit::Microsecond => "microseconds",
3963            Unit::Nanosecond => "nanoseconds",
3964        }
3965    }
3966
3967    /// A very succinct label corresponding to this unit.
3968    pub(crate) fn compact(&self) -> &'static str {
3969        match *self {
3970            Unit::Year => "y",
3971            Unit::Month => "mo",
3972            Unit::Week => "w",
3973            Unit::Day => "d",
3974            Unit::Hour => "h",
3975            Unit::Minute => "m",
3976            Unit::Second => "s",
3977            Unit::Millisecond => "ms",
3978            Unit::Microsecond => "µs",
3979            Unit::Nanosecond => "ns",
3980        }
3981    }
3982
3983    /// Return this unit as a `usize`.
3984    ///
3985    /// This is use `unit as usize`.
3986    pub(crate) fn as_usize(&self) -> usize {
3987        *self as usize
3988    }
3989
3990    /// The inverse of `unit as usize`.
3991    fn from_usize(n: usize) -> Option<Unit> {
3992        match n {
3993            0 => Some(Unit::Nanosecond),
3994            1 => Some(Unit::Microsecond),
3995            2 => Some(Unit::Millisecond),
3996            3 => Some(Unit::Second),
3997            4 => Some(Unit::Minute),
3998            5 => Some(Unit::Hour),
3999            6 => Some(Unit::Day),
4000            7 => Some(Unit::Week),
4001            8 => Some(Unit::Month),
4002            9 => Some(Unit::Year),
4003            _ => None,
4004        }
4005    }
4006
4007    /// Returns an error corresponding the boundaries of this unit.
4008    ///
4009    /// This is useful in contexts where one is doing arithmetic on integers
4010    /// where the units of those integers aren't known statically.
4011    fn error(self) -> b::BoundsError {
4012        match self {
4013            Unit::Year => b::SpanYears::error(),
4014            Unit::Month => b::SpanMonths::error(),
4015            Unit::Week => b::SpanWeeks::error(),
4016            Unit::Day => b::SpanDays::error(),
4017            Unit::Hour => b::SpanHours::error(),
4018            Unit::Minute => b::SpanMinutes::error(),
4019            Unit::Second => b::SpanSeconds::error(),
4020            Unit::Millisecond => b::SpanMilliseconds::error(),
4021            Unit::Microsecond => b::SpanMicroseconds::error(),
4022            Unit::Nanosecond => b::SpanNanoseconds::error(),
4023        }
4024    }
4025}
4026
4027#[cfg(test)]
4028impl quickcheck::Arbitrary for Unit {
4029    fn arbitrary(g: &mut quickcheck::Gen) -> Unit {
4030        Unit::from_usize(usize::arbitrary(g) % 10).unwrap()
4031    }
4032
4033    fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Self>> {
4034        alloc::boxed::Box::new(
4035            (*self as usize)
4036                .shrink()
4037                .map(|n| Unit::from_usize(n % 10).unwrap()),
4038        )
4039    }
4040}
4041
4042/// Options for [`Span::checked_add`] and [`Span::checked_sub`].
4043///
4044/// This type provides a way to ergonomically add two spans with an optional
4045/// relative datetime. Namely, a relative datetime is only needed when at least
4046/// one of the two spans being added (or subtracted) has a non-zero calendar
4047/// unit (years, months, weeks or days). Otherwise, an error will be returned.
4048///
4049/// Callers may use [`SpanArithmetic::days_are_24_hours`] to opt into 24-hour
4050/// invariant days (and 7-day weeks) without providing a relative datetime.
4051///
4052/// The main way to construct values of this type is with its `From` trait
4053/// implementations:
4054///
4055/// * `From<Span> for SpanArithmetic` adds (or subtracts) the given span to the
4056/// receiver in [`Span::checked_add`] (or [`Span::checked_sub`]).
4057/// * `From<(Span, civil::Date)> for SpanArithmetic` adds (or subtracts)
4058/// the given span to the receiver in [`Span::checked_add`] (or
4059/// [`Span::checked_sub`]), relative to the given date. There are also `From`
4060/// implementations for `civil::DateTime`, `Zoned` and [`SpanRelativeTo`].
4061///
4062/// # Example
4063///
4064/// ```
4065/// use jiff::ToSpan;
4066///
4067/// assert_eq!(
4068///     1.hour().checked_add(30.minutes())?,
4069///     1.hour().minutes(30).fieldwise(),
4070/// );
4071///
4072/// # Ok::<(), Box<dyn std::error::Error>>(())
4073/// ```
4074#[derive(Clone, Copy, Debug)]
4075pub struct SpanArithmetic<'a> {
4076    duration: Duration,
4077    relative: Option<SpanRelativeTo<'a>>,
4078}
4079
4080impl<'a> SpanArithmetic<'a> {
4081    /// This is a convenience function for setting the relative option on
4082    /// this configuration to [`SpanRelativeTo::days_are_24_hours`].
4083    ///
4084    /// # Example
4085    ///
4086    /// When doing arithmetic on spans involving days, either a relative
4087    /// datetime must be provided, or a special assertion opting into 24-hour
4088    /// days is required. Otherwise, you get an error.
4089    ///
4090    /// ```
4091    /// use jiff::{SpanArithmetic, ToSpan};
4092    ///
4093    /// let span1 = 2.days().hours(12);
4094    /// let span2 = 12.hours();
4095    /// // No relative date provided, which results in an error.
4096    /// assert_eq!(
4097    ///     span1.checked_add(span2).unwrap_err().to_string(),
4098    ///     "using unit 'day' in a span or configuration requires that \
4099    ///      either a relative reference time be given or \
4100    ///      `jiff::SpanRelativeTo::days_are_24_hours()` is used to indicate \
4101    ///      invariant 24-hour days, but neither were provided",
4102    /// );
4103    /// let sum = span1.checked_add(
4104    ///     SpanArithmetic::from(span2).days_are_24_hours(),
4105    /// )?;
4106    /// assert_eq!(sum, 3.days().fieldwise());
4107    ///
4108    /// # Ok::<(), Box<dyn std::error::Error>>(())
4109    /// ```
4110    #[inline]
4111    pub fn days_are_24_hours(self) -> SpanArithmetic<'a> {
4112        self.relative(SpanRelativeTo::days_are_24_hours())
4113    }
4114}
4115
4116impl<'a> SpanArithmetic<'a> {
4117    #[inline]
4118    fn relative<R: Into<SpanRelativeTo<'a>>>(
4119        self,
4120        relative: R,
4121    ) -> SpanArithmetic<'a> {
4122        SpanArithmetic { relative: Some(relative.into()), ..self }
4123    }
4124
4125    #[inline]
4126    fn checked_add(self, span1: Span) -> Result<Span, Error> {
4127        match self.duration.to_signed()? {
4128            SDuration::Span(span2) => {
4129                span1.checked_add_span(self.relative, &span2)
4130            }
4131            SDuration::Absolute(dur2) => {
4132                span1.checked_add_duration(self.relative, dur2)
4133            }
4134        }
4135    }
4136}
4137
4138impl From<Span> for SpanArithmetic<'static> {
4139    fn from(span: Span) -> SpanArithmetic<'static> {
4140        let duration = Duration::from(span);
4141        SpanArithmetic { duration, relative: None }
4142    }
4143}
4144
4145impl<'a> From<&'a Span> for SpanArithmetic<'static> {
4146    fn from(span: &'a Span) -> SpanArithmetic<'static> {
4147        let duration = Duration::from(*span);
4148        SpanArithmetic { duration, relative: None }
4149    }
4150}
4151
4152impl From<(Span, Date)> for SpanArithmetic<'static> {
4153    #[inline]
4154    fn from((span, date): (Span, Date)) -> SpanArithmetic<'static> {
4155        SpanArithmetic::from(span).relative(date)
4156    }
4157}
4158
4159impl From<(Span, DateTime)> for SpanArithmetic<'static> {
4160    #[inline]
4161    fn from((span, datetime): (Span, DateTime)) -> SpanArithmetic<'static> {
4162        SpanArithmetic::from(span).relative(datetime)
4163    }
4164}
4165
4166impl<'a> From<(Span, &'a Zoned)> for SpanArithmetic<'a> {
4167    #[inline]
4168    fn from((span, zoned): (Span, &'a Zoned)) -> SpanArithmetic<'a> {
4169        SpanArithmetic::from(span).relative(zoned)
4170    }
4171}
4172
4173impl<'a> From<(Span, SpanRelativeTo<'a>)> for SpanArithmetic<'a> {
4174    #[inline]
4175    fn from(
4176        (span, relative): (Span, SpanRelativeTo<'a>),
4177    ) -> SpanArithmetic<'a> {
4178        SpanArithmetic::from(span).relative(relative)
4179    }
4180}
4181
4182impl<'a> From<(&'a Span, Date)> for SpanArithmetic<'static> {
4183    #[inline]
4184    fn from((span, date): (&'a Span, Date)) -> SpanArithmetic<'static> {
4185        SpanArithmetic::from(span).relative(date)
4186    }
4187}
4188
4189impl<'a> From<(&'a Span, DateTime)> for SpanArithmetic<'static> {
4190    #[inline]
4191    fn from(
4192        (span, datetime): (&'a Span, DateTime),
4193    ) -> SpanArithmetic<'static> {
4194        SpanArithmetic::from(span).relative(datetime)
4195    }
4196}
4197
4198impl<'a, 'b> From<(&'a Span, &'b Zoned)> for SpanArithmetic<'b> {
4199    #[inline]
4200    fn from((span, zoned): (&'a Span, &'b Zoned)) -> SpanArithmetic<'b> {
4201        SpanArithmetic::from(span).relative(zoned)
4202    }
4203}
4204
4205impl<'a, 'b> From<(&'a Span, SpanRelativeTo<'b>)> for SpanArithmetic<'b> {
4206    #[inline]
4207    fn from(
4208        (span, relative): (&'a Span, SpanRelativeTo<'b>),
4209    ) -> SpanArithmetic<'b> {
4210        SpanArithmetic::from(span).relative(relative)
4211    }
4212}
4213
4214impl From<SignedDuration> for SpanArithmetic<'static> {
4215    fn from(duration: SignedDuration) -> SpanArithmetic<'static> {
4216        let duration = Duration::from(duration);
4217        SpanArithmetic { duration, relative: None }
4218    }
4219}
4220
4221impl From<(SignedDuration, Date)> for SpanArithmetic<'static> {
4222    #[inline]
4223    fn from(
4224        (duration, date): (SignedDuration, Date),
4225    ) -> SpanArithmetic<'static> {
4226        SpanArithmetic::from(duration).relative(date)
4227    }
4228}
4229
4230impl From<(SignedDuration, DateTime)> for SpanArithmetic<'static> {
4231    #[inline]
4232    fn from(
4233        (duration, datetime): (SignedDuration, DateTime),
4234    ) -> SpanArithmetic<'static> {
4235        SpanArithmetic::from(duration).relative(datetime)
4236    }
4237}
4238
4239impl<'a> From<(SignedDuration, &'a Zoned)> for SpanArithmetic<'a> {
4240    #[inline]
4241    fn from(
4242        (duration, zoned): (SignedDuration, &'a Zoned),
4243    ) -> SpanArithmetic<'a> {
4244        SpanArithmetic::from(duration).relative(zoned)
4245    }
4246}
4247
4248impl From<UnsignedDuration> for SpanArithmetic<'static> {
4249    fn from(duration: UnsignedDuration) -> SpanArithmetic<'static> {
4250        let duration = Duration::from(duration);
4251        SpanArithmetic { duration, relative: None }
4252    }
4253}
4254
4255impl From<(UnsignedDuration, Date)> for SpanArithmetic<'static> {
4256    #[inline]
4257    fn from(
4258        (duration, date): (UnsignedDuration, Date),
4259    ) -> SpanArithmetic<'static> {
4260        SpanArithmetic::from(duration).relative(date)
4261    }
4262}
4263
4264impl From<(UnsignedDuration, DateTime)> for SpanArithmetic<'static> {
4265    #[inline]
4266    fn from(
4267        (duration, datetime): (UnsignedDuration, DateTime),
4268    ) -> SpanArithmetic<'static> {
4269        SpanArithmetic::from(duration).relative(datetime)
4270    }
4271}
4272
4273impl<'a> From<(UnsignedDuration, &'a Zoned)> for SpanArithmetic<'a> {
4274    #[inline]
4275    fn from(
4276        (duration, zoned): (UnsignedDuration, &'a Zoned),
4277    ) -> SpanArithmetic<'a> {
4278        SpanArithmetic::from(duration).relative(zoned)
4279    }
4280}
4281
4282/// Options for [`Span::compare`].
4283///
4284/// This type provides a way to ergonomically compare two spans with an
4285/// optional relative datetime. Namely, a relative datetime is only needed when
4286/// at least one of the two spans being compared has a non-zero calendar unit
4287/// (years, months, weeks or days). Otherwise, an error will be returned.
4288///
4289/// Callers may use [`SpanCompare::days_are_24_hours`] to opt into 24-hour
4290/// invariant days (and 7-day weeks) without providing a relative datetime.
4291///
4292/// The main way to construct values of this type is with its `From` trait
4293/// implementations:
4294///
4295/// * `From<Span> for SpanCompare` compares the given span to the receiver
4296/// in [`Span::compare`].
4297/// * `From<(Span, civil::Date)> for SpanCompare` compares the given span
4298/// to the receiver in [`Span::compare`], relative to the given date. There
4299/// are also `From` implementations for `civil::DateTime`, `Zoned` and
4300/// [`SpanRelativeTo`].
4301///
4302/// # Example
4303///
4304/// ```
4305/// use jiff::ToSpan;
4306///
4307/// let span1 = 3.hours();
4308/// let span2 = 180.minutes();
4309/// assert_eq!(span1.compare(span2)?, std::cmp::Ordering::Equal);
4310///
4311/// # Ok::<(), Box<dyn std::error::Error>>(())
4312/// ```
4313#[derive(Clone, Copy, Debug)]
4314pub struct SpanCompare<'a> {
4315    span: Span,
4316    relative: Option<SpanRelativeTo<'a>>,
4317}
4318
4319impl<'a> SpanCompare<'a> {
4320    /// This is a convenience function for setting the relative option on
4321    /// this configuration to [`SpanRelativeTo::days_are_24_hours`].
4322    ///
4323    /// # Example
4324    ///
4325    /// When comparing spans involving days, either a relative datetime must be
4326    /// provided, or a special assertion opting into 24-hour days is
4327    /// required. Otherwise, you get an error.
4328    ///
4329    /// ```
4330    /// use jiff::{SpanCompare, ToSpan};
4331    ///
4332    /// let span1 = 2.days().hours(12);
4333    /// let span2 = 60.hours();
4334    /// // No relative date provided, which results in an error.
4335    /// assert_eq!(
4336    ///     span1.compare(span2).unwrap_err().to_string(),
4337    ///     "using unit 'day' in a span or configuration requires that \
4338    ///      either a relative reference time be given or \
4339    ///      `jiff::SpanRelativeTo::days_are_24_hours()` is used to indicate \
4340    ///      invariant 24-hour days, but neither were provided",
4341    /// );
4342    /// let ordering = span1.compare(
4343    ///     SpanCompare::from(span2).days_are_24_hours(),
4344    /// )?;
4345    /// assert_eq!(ordering, std::cmp::Ordering::Equal);
4346    ///
4347    /// # Ok::<(), Box<dyn std::error::Error>>(())
4348    /// ```
4349    #[inline]
4350    pub fn days_are_24_hours(self) -> SpanCompare<'a> {
4351        self.relative(SpanRelativeTo::days_are_24_hours())
4352    }
4353}
4354
4355impl<'a> SpanCompare<'a> {
4356    #[inline]
4357    fn new(span: Span) -> SpanCompare<'static> {
4358        SpanCompare { span, relative: None }
4359    }
4360
4361    #[inline]
4362    fn relative<R: Into<SpanRelativeTo<'a>>>(
4363        self,
4364        relative: R,
4365    ) -> SpanCompare<'a> {
4366        SpanCompare { relative: Some(relative.into()), ..self }
4367    }
4368
4369    fn compare(self, span: Span) -> Result<Ordering, Error> {
4370        let (span1, span2) = (span, self.span);
4371        let unit = span1.largest_unit().max(span2.largest_unit());
4372        let start = match self.relative {
4373            Some(r) => match r.to_relative(unit)? {
4374                Some(r) => r,
4375                None => {
4376                    let dur1 = span1.to_invariant_duration();
4377                    let dur2 = span2.to_invariant_duration();
4378                    return Ok(dur1.cmp(&dur2));
4379                }
4380            },
4381            None => {
4382                requires_relative_date_err(unit)?;
4383                let dur1 = span1.to_invariant_duration();
4384                let dur2 = span2.to_invariant_duration();
4385                return Ok(dur1.cmp(&dur2));
4386            }
4387        };
4388        let end1 = start.checked_add(span1)?.to_duration();
4389        let end2 = start.checked_add(span2)?.to_duration();
4390        Ok(end1.cmp(&end2))
4391    }
4392}
4393
4394impl From<Span> for SpanCompare<'static> {
4395    fn from(span: Span) -> SpanCompare<'static> {
4396        SpanCompare::new(span)
4397    }
4398}
4399
4400impl<'a> From<&'a Span> for SpanCompare<'static> {
4401    fn from(span: &'a Span) -> SpanCompare<'static> {
4402        SpanCompare::new(*span)
4403    }
4404}
4405
4406impl From<(Span, Date)> for SpanCompare<'static> {
4407    #[inline]
4408    fn from((span, date): (Span, Date)) -> SpanCompare<'static> {
4409        SpanCompare::from(span).relative(date)
4410    }
4411}
4412
4413impl From<(Span, DateTime)> for SpanCompare<'static> {
4414    #[inline]
4415    fn from((span, datetime): (Span, DateTime)) -> SpanCompare<'static> {
4416        SpanCompare::from(span).relative(datetime)
4417    }
4418}
4419
4420impl<'a> From<(Span, &'a Zoned)> for SpanCompare<'a> {
4421    #[inline]
4422    fn from((span, zoned): (Span, &'a Zoned)) -> SpanCompare<'a> {
4423        SpanCompare::from(span).relative(zoned)
4424    }
4425}
4426
4427impl<'a> From<(Span, SpanRelativeTo<'a>)> for SpanCompare<'a> {
4428    #[inline]
4429    fn from((span, relative): (Span, SpanRelativeTo<'a>)) -> SpanCompare<'a> {
4430        SpanCompare::from(span).relative(relative)
4431    }
4432}
4433
4434impl<'a> From<(&'a Span, Date)> for SpanCompare<'static> {
4435    #[inline]
4436    fn from((span, date): (&'a Span, Date)) -> SpanCompare<'static> {
4437        SpanCompare::from(span).relative(date)
4438    }
4439}
4440
4441impl<'a> From<(&'a Span, DateTime)> for SpanCompare<'static> {
4442    #[inline]
4443    fn from((span, datetime): (&'a Span, DateTime)) -> SpanCompare<'static> {
4444        SpanCompare::from(span).relative(datetime)
4445    }
4446}
4447
4448impl<'a, 'b> From<(&'a Span, &'b Zoned)> for SpanCompare<'b> {
4449    #[inline]
4450    fn from((span, zoned): (&'a Span, &'b Zoned)) -> SpanCompare<'b> {
4451        SpanCompare::from(span).relative(zoned)
4452    }
4453}
4454
4455impl<'a, 'b> From<(&'a Span, SpanRelativeTo<'b>)> for SpanCompare<'b> {
4456    #[inline]
4457    fn from(
4458        (span, relative): (&'a Span, SpanRelativeTo<'b>),
4459    ) -> SpanCompare<'b> {
4460        SpanCompare::from(span).relative(relative)
4461    }
4462}
4463
4464/// Options for [`Span::total`].
4465///
4466/// This type provides a way to ergonomically determine the number of a
4467/// particular unit in a span, with a potentially fractional component, with
4468/// an optional relative datetime. Namely, a relative datetime is only needed
4469/// when the span has a non-zero calendar unit (years, months, weeks or days).
4470/// Otherwise, an error will be returned.
4471///
4472/// Callers may use [`SpanTotal::days_are_24_hours`] to opt into 24-hour
4473/// invariant days (and 7-day weeks) without providing a relative datetime.
4474///
4475/// The main way to construct values of this type is with its `From` trait
4476/// implementations:
4477///
4478/// * `From<Unit> for SpanTotal` computes a total for the given unit in the
4479/// receiver span for [`Span::total`].
4480/// * `From<(Unit, civil::Date)> for SpanTotal` computes a total for the given
4481/// unit in the receiver span for [`Span::total`], relative to the given date.
4482/// There are also `From` implementations for `civil::DateTime`, `Zoned` and
4483/// [`SpanRelativeTo`].
4484///
4485/// # Example
4486///
4487/// This example shows how to find the number of seconds in a particular span:
4488///
4489/// ```
4490/// use jiff::{ToSpan, Unit};
4491///
4492/// let span = 3.hours().minutes(10);
4493/// assert_eq!(span.total(Unit::Second)?, 11_400.0);
4494///
4495/// # Ok::<(), Box<dyn std::error::Error>>(())
4496/// ```
4497///
4498/// # Example: 24 hour days
4499///
4500/// This shows how to find the total number of 24 hour days in `123,456,789`
4501/// seconds.
4502///
4503/// ```
4504/// use jiff::{SpanTotal, ToSpan, Unit};
4505///
4506/// let span = 123_456_789.seconds();
4507/// assert_eq!(
4508///     span.total(SpanTotal::from(Unit::Day).days_are_24_hours())?,
4509///     1428.8980208333332,
4510/// );
4511///
4512/// # Ok::<(), Box<dyn std::error::Error>>(())
4513/// ```
4514///
4515/// # Example: DST is taken into account
4516///
4517/// The month of March 2024 in `America/New_York` had 31 days, but one of those
4518/// days was 23 hours long due a transition into daylight saving time:
4519///
4520/// ```
4521/// use jiff::{civil::date, ToSpan, Unit};
4522///
4523/// let span = 744.hours();
4524/// let relative = date(2024, 3, 1).in_tz("America/New_York")?;
4525/// // Because of the short day, 744 hours is actually a little *more* than
4526/// // 1 month starting from 2024-03-01.
4527/// assert_eq!(span.total((Unit::Month, &relative))?, 1.0013888888888889);
4528///
4529/// # Ok::<(), Box<dyn std::error::Error>>(())
4530/// ```
4531///
4532/// Now compare what happens when the relative datetime is civil and not
4533/// time zone aware:
4534///
4535/// ```
4536/// use jiff::{civil::date, ToSpan, Unit};
4537///
4538/// let span = 744.hours();
4539/// let relative = date(2024, 3, 1);
4540/// assert_eq!(span.total((Unit::Month, relative))?, 1.0);
4541///
4542/// # Ok::<(), Box<dyn std::error::Error>>(())
4543/// ```
4544#[derive(Clone, Copy, Debug)]
4545pub struct SpanTotal<'a> {
4546    unit: Unit,
4547    relative: Option<SpanRelativeTo<'a>>,
4548}
4549
4550impl<'a> SpanTotal<'a> {
4551    /// This is a convenience function for setting the relative option on
4552    /// this configuration to [`SpanRelativeTo::days_are_24_hours`].
4553    ///
4554    /// # Example
4555    ///
4556    /// When computing the total duration for spans involving days, either a
4557    /// relative datetime must be provided, or a special assertion opting into
4558    /// 24-hour days is required. Otherwise, you get an error.
4559    ///
4560    /// ```
4561    /// use jiff::{civil::date, SpanTotal, ToSpan, Unit};
4562    ///
4563    /// let span = 2.days().hours(12);
4564    ///
4565    /// // No relative date provided, which results in an error.
4566    /// assert_eq!(
4567    ///     span.total(Unit::Hour).unwrap_err().to_string(),
4568    ///     "using unit 'day' in a span or configuration requires that either \
4569    ///      a relative reference time be given or \
4570    ///      `jiff::SpanRelativeTo::days_are_24_hours()` is used to indicate \
4571    ///      invariant 24-hour days, but neither were provided",
4572    /// );
4573    ///
4574    /// // If we can assume all days are 24 hours, then we can assert it:
4575    /// let total = span.total(
4576    ///     SpanTotal::from(Unit::Hour).days_are_24_hours(),
4577    /// )?;
4578    /// assert_eq!(total, 60.0);
4579    ///
4580    /// // Or provide a relative datetime, which is preferred if possible:
4581    /// let total = span.total((Unit::Hour, date(2025, 1, 26)))?;
4582    /// assert_eq!(total, 60.0);
4583    ///
4584    /// # Ok::<(), Box<dyn std::error::Error>>(())
4585    /// ```
4586    #[inline]
4587    pub fn days_are_24_hours(self) -> SpanTotal<'a> {
4588        self.relative(SpanRelativeTo::days_are_24_hours())
4589    }
4590}
4591
4592impl<'a> SpanTotal<'a> {
4593    #[inline]
4594    fn new(unit: Unit) -> SpanTotal<'static> {
4595        SpanTotal { unit, relative: None }
4596    }
4597
4598    #[inline]
4599    fn relative<R: Into<SpanRelativeTo<'a>>>(
4600        self,
4601        relative: R,
4602    ) -> SpanTotal<'a> {
4603        SpanTotal { relative: Some(relative.into()), ..self }
4604    }
4605
4606    fn total(self, span: Span) -> Result<f64, Error> {
4607        let max_unit = self.unit.max(span.largest_unit());
4608        let relative = match self.relative {
4609            Some(r) => match r.to_relative(max_unit)? {
4610                Some(r) => r,
4611                None => {
4612                    return Ok(self.total_invariant(span));
4613                }
4614            },
4615            None => {
4616                requires_relative_date_err(max_unit)?;
4617                return Ok(self.total_invariant(span));
4618            }
4619        };
4620        let relspan = relative.into_relative_span(self.unit, span)?;
4621        if !self.unit.is_variable() {
4622            return Ok(self.total_invariant(relspan.span));
4623        }
4624
4625        assert!(self.unit >= Unit::Day);
4626        let sign = relspan.span.get_sign();
4627        let (relative_start, relative_end) = match relspan.kind {
4628            RelativeSpanKind::Civil { start, end } => {
4629                let start = Relative::Civil(start);
4630                let end = Relative::Civil(end);
4631                (start, end)
4632            }
4633            RelativeSpanKind::Zoned { start, end } => {
4634                let start = Relative::Zoned(start);
4635                let end = Relative::Zoned(end);
4636                (start, end)
4637            }
4638        };
4639        let (relative0, relative1) = unit_start_and_end(
4640            &relative_start,
4641            relspan.span.without_lower(self.unit),
4642            self.unit,
4643            sign.as_i64(),
4644        )?;
4645        let denom = (relative1 - relative0).as_nanos() as f64;
4646        let numer = (relative_end.to_duration() - relative0).as_nanos() as f64;
4647        let unit_val = relspan.span.get_unit(self.unit) as f64;
4648        Ok(unit_val + (numer / denom) * (sign.as_i8() as f64))
4649    }
4650
4651    #[inline]
4652    fn total_invariant(&self, span: Span) -> f64 {
4653        assert!(self.unit <= Unit::Week);
4654        let dur = span.to_invariant_duration().as_nanos();
4655        // We do this instead of using `SignedDuration::as_secs_f64()`
4656        // because of floating point precision. It seems that if we represent
4657        // our ratio as floats of seconds instead of nanoseconds, then there
4658        // is more loss of precision than using nanoseconds. Unfortunately,
4659        // this does mean manifesting `i128` values.
4660        (dur as f64) / (self.unit.duration().as_nanos() as f64)
4661    }
4662}
4663
4664impl From<Unit> for SpanTotal<'static> {
4665    #[inline]
4666    fn from(unit: Unit) -> SpanTotal<'static> {
4667        SpanTotal::new(unit)
4668    }
4669}
4670
4671impl From<(Unit, Date)> for SpanTotal<'static> {
4672    #[inline]
4673    fn from((unit, date): (Unit, Date)) -> SpanTotal<'static> {
4674        SpanTotal::from(unit).relative(date)
4675    }
4676}
4677
4678impl From<(Unit, DateTime)> for SpanTotal<'static> {
4679    #[inline]
4680    fn from((unit, datetime): (Unit, DateTime)) -> SpanTotal<'static> {
4681        SpanTotal::from(unit).relative(datetime)
4682    }
4683}
4684
4685impl<'a> From<(Unit, &'a Zoned)> for SpanTotal<'a> {
4686    #[inline]
4687    fn from((unit, zoned): (Unit, &'a Zoned)) -> SpanTotal<'a> {
4688        SpanTotal::from(unit).relative(zoned)
4689    }
4690}
4691
4692impl<'a> From<(Unit, SpanRelativeTo<'a>)> for SpanTotal<'a> {
4693    #[inline]
4694    fn from((unit, relative): (Unit, SpanRelativeTo<'a>)) -> SpanTotal<'a> {
4695        SpanTotal::from(unit).relative(relative)
4696    }
4697}
4698
4699/// Options for [`Span::round`].
4700///
4701/// This type provides a way to configure the rounding of a span. This
4702/// includes setting the smallest unit (i.e., the unit to round), the
4703/// largest unit, the rounding increment, the rounding mode (e.g., "ceil" or
4704/// "truncate") and the datetime that the span is relative to.
4705///
4706/// `Span::round` accepts anything that implements `Into<SpanRound>`. There are
4707/// a few key trait implementations that make this convenient:
4708///
4709/// * `From<Unit> for SpanRound` will construct a rounding configuration where
4710/// the smallest unit is set to the one given.
4711/// * `From<(Unit, i64)> for SpanRound` will construct a rounding configuration
4712/// where the smallest unit and the rounding increment are set to the ones
4713/// given.
4714///
4715/// In order to set other options (like the largest unit, the rounding mode
4716/// and the relative datetime), one must explicitly create a `SpanRound` and
4717/// pass it to `Span::round`.
4718///
4719/// # Example
4720///
4721/// This example shows how to find how many full 3 month quarters are in a
4722/// particular span of time.
4723///
4724/// ```
4725/// use jiff::{civil::date, RoundMode, SpanRound, ToSpan, Unit};
4726///
4727/// let span1 = 10.months().days(15);
4728/// let round = SpanRound::new()
4729///     .smallest(Unit::Month)
4730///     .increment(3)
4731///     .mode(RoundMode::Trunc)
4732///     // A relative datetime must be provided when
4733///     // rounding involves calendar units.
4734///     .relative(date(2024, 1, 1));
4735/// let span2 = span1.round(round)?;
4736/// assert_eq!(span2.get_months() / 3, 3);
4737///
4738/// # Ok::<(), Box<dyn std::error::Error>>(())
4739/// ```
4740#[derive(Clone, Copy, Debug)]
4741pub struct SpanRound<'a> {
4742    largest: Option<Unit>,
4743    smallest: Unit,
4744    mode: RoundMode,
4745    increment: i64,
4746    relative: Option<SpanRelativeTo<'a>>,
4747}
4748
4749impl<'a> SpanRound<'a> {
4750    /// Create a new default configuration for rounding a span via
4751    /// [`Span::round`].
4752    ///
4753    /// The default configuration does no rounding.
4754    #[inline]
4755    pub fn new() -> SpanRound<'static> {
4756        SpanRound {
4757            largest: None,
4758            smallest: Unit::Nanosecond,
4759            mode: RoundMode::HalfExpand,
4760            increment: 1,
4761            relative: None,
4762        }
4763    }
4764
4765    /// Set the smallest units allowed in the span returned. These are the
4766    /// units that the span is rounded to.
4767    ///
4768    /// # Errors
4769    ///
4770    /// The smallest units must be no greater than the largest units. If this
4771    /// is violated, then rounding a span with this configuration will result
4772    /// in an error.
4773    ///
4774    /// If a smallest unit bigger than days is selected without a relative
4775    /// datetime reference point, then an error is returned when using this
4776    /// configuration with [`Span::round`].
4777    ///
4778    /// # Example
4779    ///
4780    /// A basic example that rounds to the nearest minute:
4781    ///
4782    /// ```
4783    /// use jiff::{ToSpan, Unit};
4784    ///
4785    /// let span = 15.minutes().seconds(46);
4786    /// assert_eq!(span.round(Unit::Minute)?, 16.minutes().fieldwise());
4787    ///
4788    /// # Ok::<(), Box<dyn std::error::Error>>(())
4789    /// ```
4790    #[inline]
4791    pub fn smallest(self, unit: Unit) -> SpanRound<'a> {
4792        SpanRound { smallest: unit, ..self }
4793    }
4794
4795    /// Set the largest units allowed in the span returned.
4796    ///
4797    /// When a largest unit is not specified, then it defaults to the largest
4798    /// non-zero unit that is at least as big as the configured smallest
4799    /// unit. For example, given a span of `2 months 17 hours`, the default
4800    /// largest unit would be `Unit::Month`. The default implies that a span's
4801    /// units do not get "bigger" than what was given.
4802    ///
4803    /// Once a largest unit is set, there is no way to change this rounding
4804    /// configuration back to using the "automatic" default. Instead, callers
4805    /// must create a new configuration.
4806    ///
4807    /// If a largest unit is set and no other options are set, then the
4808    /// rounding operation can be said to be a "re-balancing." That is, the
4809    /// span won't lose precision, but the way in which it is expressed may
4810    /// change.
4811    ///
4812    /// # Errors
4813    ///
4814    /// The largest units, when set, must be at least as big as the smallest
4815    /// units (which defaults to [`Unit::Nanosecond`]). If this is violated,
4816    /// then rounding a span with this configuration will result in an error.
4817    ///
4818    /// If a largest unit bigger than days is selected without a relative
4819    /// datetime reference point, then an error is returned when using this
4820    /// configuration with [`Span::round`].
4821    ///
4822    /// # Example: re-balancing
4823    ///
4824    /// This shows how a span can be re-balanced without losing precision:
4825    ///
4826    /// ```
4827    /// use jiff::{SpanRound, ToSpan, Unit};
4828    ///
4829    /// let span = 86_401_123_456_789i64.nanoseconds();
4830    /// assert_eq!(
4831    ///     span.round(SpanRound::new().largest(Unit::Hour))?.fieldwise(),
4832    ///     24.hours().seconds(1).milliseconds(123).microseconds(456).nanoseconds(789),
4833    /// );
4834    ///
4835    /// # Ok::<(), Box<dyn std::error::Error>>(())
4836    /// ```
4837    ///
4838    /// If you need to use a largest unit bigger than hours, then you must
4839    /// provide a relative datetime as a reference point (otherwise an error
4840    /// will occur):
4841    ///
4842    /// ```
4843    /// use jiff::{civil::date, SpanRound, ToSpan, Unit};
4844    ///
4845    /// let span = 3_968_000.seconds();
4846    /// let round = SpanRound::new()
4847    ///     .largest(Unit::Day)
4848    ///     .relative(date(2024, 7, 1));
4849    /// assert_eq!(
4850    ///     span.round(round)?,
4851    ///     45.days().hours(22).minutes(13).seconds(20).fieldwise(),
4852    /// );
4853    ///
4854    /// # Ok::<(), Box<dyn std::error::Error>>(())
4855    /// ```
4856    ///
4857    /// As a special case for days, one can instead opt into invariant 24-hour
4858    /// days (and 7-day weeks) without providing an explicit relative date:
4859    ///
4860    /// ```
4861    /// use jiff::{SpanRound, ToSpan, Unit};
4862    ///
4863    /// let span = 86_401_123_456_789i64.nanoseconds();
4864    /// assert_eq!(
4865    ///     span.round(
4866    ///         SpanRound::new().largest(Unit::Day).days_are_24_hours(),
4867    ///     )?.fieldwise(),
4868    ///     1.day().seconds(1).milliseconds(123).microseconds(456).nanoseconds(789),
4869    /// );
4870    ///
4871    /// # Ok::<(), Box<dyn std::error::Error>>(())
4872    /// ```
4873    ///
4874    /// # Example: re-balancing while taking DST into account
4875    ///
4876    /// When given a zone aware relative datetime, rounding will even take
4877    /// DST into account:
4878    ///
4879    /// ```
4880    /// use jiff::{SpanRound, ToSpan, Unit, Zoned};
4881    ///
4882    /// let span = 2756.hours();
4883    /// let zdt = "2020-01-01T00:00+01:00[Europe/Rome]".parse::<Zoned>()?;
4884    /// let round = SpanRound::new().largest(Unit::Year).relative(&zdt);
4885    /// assert_eq!(
4886    ///     span.round(round)?,
4887    ///     3.months().days(23).hours(21).fieldwise(),
4888    /// );
4889    ///
4890    /// # Ok::<(), Box<dyn std::error::Error>>(())
4891    /// ```
4892    ///
4893    /// Now compare with the same operation, but on a civil datetime (which is
4894    /// not aware of time zone):
4895    ///
4896    /// ```
4897    /// use jiff::{civil::DateTime, SpanRound, ToSpan, Unit};
4898    ///
4899    /// let span = 2756.hours();
4900    /// let dt = "2020-01-01T00:00".parse::<DateTime>()?;
4901    /// let round = SpanRound::new().largest(Unit::Year).relative(dt);
4902    /// assert_eq!(
4903    ///     span.round(round)?,
4904    ///     3.months().days(23).hours(20).fieldwise(),
4905    /// );
4906    ///
4907    /// # Ok::<(), Box<dyn std::error::Error>>(())
4908    /// ```
4909    ///
4910    /// The result is 1 hour shorter. This is because, in the zone
4911    /// aware re-balancing, it accounts for the transition into DST at
4912    /// `2020-03-29T01:00Z`, which skips an hour. This makes the span one hour
4913    /// longer because one of the days in the span is actually only 23 hours
4914    /// long instead of 24 hours.
4915    #[inline]
4916    pub fn largest(self, unit: Unit) -> SpanRound<'a> {
4917        SpanRound { largest: Some(unit), ..self }
4918    }
4919
4920    /// Set the rounding mode.
4921    ///
4922    /// This defaults to [`RoundMode::HalfExpand`], which makes rounding work
4923    /// like how you were taught in school.
4924    ///
4925    /// # Example
4926    ///
4927    /// A basic example that rounds to the nearest minute, but changing its
4928    /// rounding mode to truncation:
4929    ///
4930    /// ```
4931    /// use jiff::{RoundMode, SpanRound, ToSpan, Unit};
4932    ///
4933    /// let span = 15.minutes().seconds(46);
4934    /// assert_eq!(
4935    ///     span.round(SpanRound::new()
4936    ///         .smallest(Unit::Minute)
4937    ///         .mode(RoundMode::Trunc),
4938    ///     )?,
4939    ///     // The default round mode does rounding like
4940    ///     // how you probably learned in school, and would
4941    ///     // result in rounding up to 16 minutes. But we
4942    ///     // change it to truncation here, which makes it
4943    ///     // round down.
4944    ///     15.minutes().fieldwise(),
4945    /// );
4946    ///
4947    /// # Ok::<(), Box<dyn std::error::Error>>(())
4948    /// ```
4949    #[inline]
4950    pub fn mode(self, mode: RoundMode) -> SpanRound<'a> {
4951        SpanRound { mode, ..self }
4952    }
4953
4954    /// Set the rounding increment for the smallest unit.
4955    ///
4956    /// The default value is `1`. Other values permit rounding the smallest
4957    /// unit to the nearest integer increment specified. For example, if the
4958    /// smallest unit is set to [`Unit::Minute`], then a rounding increment of
4959    /// `30` would result in rounding in increments of a half hour. That is,
4960    /// the only minute value that could result would be `0` or `30`.
4961    ///
4962    /// # Errors
4963    ///
4964    /// When the smallest unit is less than days, the rounding increment must
4965    /// divide evenly into the next highest unit after the smallest unit
4966    /// configured (and must not be equivalent to it). For example, if the
4967    /// smallest unit is [`Unit::Nanosecond`], then *some* of the valid values
4968    /// for the rounding increment are `1`, `2`, `4`, `5`, `100` and `500`.
4969    /// Namely, any integer that divides evenly into `1,000` nanoseconds since
4970    /// there are `1,000` nanoseconds in the next highest unit (microseconds).
4971    ///
4972    /// In all cases, the increment must be greater than zero and less than
4973    /// or equal to `1_000_000_000`.
4974    ///
4975    /// The error will occur when computing the span, and not when setting
4976    /// the increment here.
4977    ///
4978    /// # Example
4979    ///
4980    /// This shows how to round a span to the nearest 5 minute increment:
4981    ///
4982    /// ```
4983    /// use jiff::{ToSpan, Unit};
4984    ///
4985    /// let span = 4.hours().minutes(2).seconds(30);
4986    /// assert_eq!(
4987    ///     span.round((Unit::Minute, 5))?,
4988    ///     4.hours().minutes(5).fieldwise(),
4989    /// );
4990    ///
4991    /// # Ok::<(), Box<dyn std::error::Error>>(())
4992    /// ```
4993    #[inline]
4994    pub fn increment(self, increment: i64) -> SpanRound<'a> {
4995        SpanRound { increment, ..self }
4996    }
4997
4998    /// Set the relative datetime to use when rounding a span.
4999    ///
5000    /// A relative datetime is only required when calendar units (units greater
5001    /// than days) are involved. This includes having calendar units in the
5002    /// original span, or calendar units in the configured smallest or largest
5003    /// unit. A relative datetime is required when calendar units are used
5004    /// because the duration of a particular calendar unit (like 1 month or 1
5005    /// year) is variable and depends on the date. For example, 1 month from
5006    /// 2024-01-01 is 31 days, but 1 month from 2024-02-01 is 29 days.
5007    ///
5008    /// A relative datetime is provided by anything that implements
5009    /// `Into<SpanRelativeTo>`. There are a few convenience trait
5010    /// implementations provided:
5011    ///
5012    /// * `From<&Zoned> for SpanRelativeTo` uses a zone aware datetime to do
5013    /// rounding. In this case, rounding will take time zone transitions into
5014    /// account. In particular, when using a zoned relative datetime, not all
5015    /// days are necessarily 24 hours.
5016    /// * `From<civil::DateTime> for SpanRelativeTo` uses a civil datetime. In
5017    /// this case, all days will be considered 24 hours long.
5018    /// * `From<civil::Date> for SpanRelativeTo` uses a civil date. In this
5019    /// case, all days will be considered 24 hours long.
5020    ///
5021    /// Note that one can impose 24-hour days without providing a reference
5022    /// date via [`SpanRelativeTo::days_are_24_hours`].
5023    ///
5024    /// # Errors
5025    ///
5026    /// If rounding involves a calendar unit (units bigger than hours) and no
5027    /// relative datetime is provided, then this configuration will lead to
5028    /// an error when used with [`Span::round`].
5029    ///
5030    /// # Example
5031    ///
5032    /// This example shows very precisely how a DST transition can impact
5033    /// rounding and re-balancing. For example, consider the day `2024-11-03`
5034    /// in `America/New_York`. On this day, the 1 o'clock hour was repeated,
5035    /// making the day 24 hours long. This will be taken into account when
5036    /// rounding if a zoned datetime is provided as a reference point:
5037    ///
5038    /// ```
5039    /// use jiff::{SpanRound, ToSpan, Unit, Zoned};
5040    ///
5041    /// let zdt = "2024-11-03T00-04[America/New_York]".parse::<Zoned>()?;
5042    /// let round = SpanRound::new().largest(Unit::Hour).relative(&zdt);
5043    /// assert_eq!(1.day().round(round)?, 25.hours().fieldwise());
5044    ///
5045    /// # Ok::<(), Box<dyn std::error::Error>>(())
5046    /// ```
5047    ///
5048    /// And similarly for `2024-03-10`, where the 2 o'clock hour was skipped
5049    /// entirely:
5050    ///
5051    /// ```
5052    /// use jiff::{SpanRound, ToSpan, Unit, Zoned};
5053    ///
5054    /// let zdt = "2024-03-10T00-05[America/New_York]".parse::<Zoned>()?;
5055    /// let round = SpanRound::new().largest(Unit::Hour).relative(&zdt);
5056    /// assert_eq!(1.day().round(round)?, 23.hours().fieldwise());
5057    ///
5058    /// # Ok::<(), Box<dyn std::error::Error>>(())
5059    /// ```
5060    #[inline]
5061    pub fn relative<R: Into<SpanRelativeTo<'a>>>(
5062        self,
5063        relative: R,
5064    ) -> SpanRound<'a> {
5065        SpanRound { relative: Some(relative.into()), ..self }
5066    }
5067
5068    /// This is a convenience function for setting the relative option on
5069    /// this configuration to [`SpanRelativeTo::days_are_24_hours`].
5070    ///
5071    /// # Example
5072    ///
5073    /// When rounding spans involving days, either a relative datetime must be
5074    /// provided, or a special assertion opting into 24-hour days is
5075    /// required. Otherwise, you get an error.
5076    ///
5077    /// ```
5078    /// use jiff::{SpanRound, ToSpan, Unit};
5079    ///
5080    /// let span = 2.days().hours(12);
5081    /// // No relative date provided, which results in an error.
5082    /// assert_eq!(
5083    ///     span.round(Unit::Day).unwrap_err().to_string(),
5084    ///     "error with `smallest` rounding option: using unit 'day' in a \
5085    ///      span or configuration requires that either a relative reference \
5086    ///      time be given or `jiff::SpanRelativeTo::days_are_24_hours()` is \
5087    ///      used to indicate invariant 24-hour days, but neither were \
5088    ///      provided",
5089    /// );
5090    /// let rounded = span.round(
5091    ///     SpanRound::new().smallest(Unit::Day).days_are_24_hours(),
5092    /// )?;
5093    /// assert_eq!(rounded, 3.days().fieldwise());
5094    ///
5095    /// # Ok::<(), Box<dyn std::error::Error>>(())
5096    /// ```
5097    #[inline]
5098    pub fn days_are_24_hours(self) -> SpanRound<'a> {
5099        self.relative(SpanRelativeTo::days_are_24_hours())
5100    }
5101
5102    /// Returns the configured smallest unit on this round configuration.
5103    #[inline]
5104    pub(crate) fn get_smallest(&self) -> Unit {
5105        self.smallest
5106    }
5107
5108    /// Returns the configured largest unit on this round configuration.
5109    #[inline]
5110    pub(crate) fn get_largest(&self) -> Option<Unit> {
5111        self.largest
5112    }
5113
5114    /// Returns true only when rounding a span *may* change it. When it
5115    /// returns false, and if the span is already balanced according to
5116    /// the largest unit in this round configuration, then it is guaranteed
5117    /// that rounding is a no-op.
5118    ///
5119    /// This is useful to avoid rounding calls after doing span arithmetic
5120    /// on datetime types. This works because the "largest" unit is used to
5121    /// construct a balanced span for the difference between two datetimes.
5122    /// So we already know the span has been balanced. If this weren't the
5123    /// case, then the largest unit being different from the one in the span
5124    /// could result in rounding making a change. (And indeed, in the general
5125    /// case of span rounding below, we do a more involved check for this.)
5126    #[inline]
5127    pub(crate) fn rounding_may_change_span(&self) -> bool {
5128        self.smallest > Unit::Nanosecond || self.increment != 1
5129    }
5130
5131    /// Like `SpanRound::rounding_may_change_span`, but applies to contexts
5132    /// where only calendar units are applicable.
5133    ///
5134    /// At time of writing (2026-02-05), this is only used for `civil::Date`.
5135    #[inline]
5136    pub(crate) fn rounding_calendar_only_may_change_span(&self) -> bool {
5137        self.smallest > Unit::Day || self.increment != 1
5138    }
5139
5140    /// Does the actual span rounding.
5141    fn round(&self, span: Span) -> Result<Span, Error> {
5142        let existing_largest = span.largest_unit();
5143        let largest = self
5144            .largest
5145            .unwrap_or_else(|| self.smallest.max(existing_largest));
5146        let max = existing_largest.max(largest);
5147        let increment = Increment::for_span(self.smallest, self.increment)?;
5148        if largest < self.smallest {
5149            return Err(Error::from(
5150                UnitConfigError::LargestSmallerThanSmallest {
5151                    smallest: self.smallest,
5152                    largest,
5153                },
5154            ));
5155        }
5156
5157        let relative = match self.relative {
5158            Some(ref r) => {
5159                match r.to_relative(max)? {
5160                    Some(r) => r,
5161                    None => {
5162                        // If our reference point is civil time, then its units
5163                        // are invariant as long as we are using day-or-lower
5164                        // everywhere. That is, the length of the duration is
5165                        // independent of the reference point. In which case,
5166                        // rounding is a simple matter of converting the span
5167                        // to a number of nanoseconds and then rounding that.
5168                        return Ok(round_span_invariant(
5169                            span, largest, &increment, self.mode,
5170                        )?);
5171                    }
5172                }
5173            }
5174            None => {
5175                // This is only okay if none of our units are above 'hour'.
5176                // A `Span` can still be rounded without a relative datetime
5177                // when it has weeks/days units, but that requires explicitly
5178                // specifying a special relative date marker, which is handled
5179                // by the `Some` case above.
5180                requires_relative_date_err(self.smallest)
5181                    .context(E::OptionSmallest)?;
5182                if let Some(largest) = self.largest {
5183                    requires_relative_date_err(largest)
5184                        .context(E::OptionLargest)?;
5185                }
5186                requires_relative_date_err(existing_largest)
5187                    .context(E::OptionLargestInSpan)?;
5188                assert!(max <= Unit::Week);
5189                return Ok(round_span_invariant(
5190                    span, largest, &increment, self.mode,
5191                )?);
5192            }
5193        };
5194        relative.round(span, largest, &increment, self.mode)
5195    }
5196}
5197
5198impl Default for SpanRound<'static> {
5199    fn default() -> SpanRound<'static> {
5200        SpanRound::new()
5201    }
5202}
5203
5204impl From<Unit> for SpanRound<'static> {
5205    fn from(unit: Unit) -> SpanRound<'static> {
5206        SpanRound::default().smallest(unit)
5207    }
5208}
5209
5210impl From<(Unit, i64)> for SpanRound<'static> {
5211    fn from((unit, increment): (Unit, i64)) -> SpanRound<'static> {
5212        SpanRound::default().smallest(unit).increment(increment)
5213    }
5214}
5215
5216/// A relative datetime for use with [`Span`] APIs.
5217///
5218/// A relative datetime can be one of the following: [`civil::Date`](Date),
5219/// [`civil::DateTime`](DateTime) or [`Zoned`]. It can be constructed from any
5220/// of the preceding types via `From` trait implementations.
5221///
5222/// A relative datetime is used to indicate how the calendar units of a `Span`
5223/// should be interpreted. For example, the span "1 month" does not have a
5224/// fixed meaning. One month from `2024-03-01` is 31 days, but one month from
5225/// `2024-04-01` is 30 days. Similar for years.
5226///
5227/// When a relative datetime in time zone aware (i.e., it is a `Zoned`), then
5228/// operations on a `Span` will also consider its day units to be variable in
5229/// length. For example, `2024-03-10` in `America/New_York` was only 23 hours
5230/// long, where as `2024-11-03` in `America/New_York` was 25 hours long. When
5231/// a relative datetime is civil, then days are considered to always be of a
5232/// fixed 24 hour length.
5233///
5234/// This type is principally used as an input to one of several different
5235/// [`Span`] APIs:
5236///
5237/// * [`Span::round`] rounds spans. A relative datetime is necessary when
5238/// dealing with calendar units. (But spans without calendar units can be
5239/// rounded without providing a relative datetime.)
5240/// * Span arithmetic via [`Span::checked_add`] and [`Span::checked_sub`].
5241/// A relative datetime is needed when adding or subtracting spans with
5242/// calendar units.
5243/// * Span comparisons via [`Span::compare`] require a relative datetime when
5244/// comparing spans with calendar units.
5245/// * Computing the "total" duration as a single floating point number via
5246/// [`Span::total`] also requires a relative datetime when dealing with
5247/// calendar units.
5248///
5249/// # Example
5250///
5251/// This example shows how to round a span with larger calendar units to
5252/// smaller units:
5253///
5254/// ```
5255/// use jiff::{SpanRound, ToSpan, Unit, Zoned};
5256///
5257/// let zdt: Zoned = "2012-01-01[Antarctica/Troll]".parse()?;
5258/// let round = SpanRound::new().largest(Unit::Day).relative(&zdt);
5259/// assert_eq!(1.year().round(round)?, 366.days().fieldwise());
5260///
5261/// // If you tried this without a relative datetime, it would fail:
5262/// let round = SpanRound::new().largest(Unit::Day);
5263/// assert!(1.year().round(round).is_err());
5264///
5265/// # Ok::<(), Box<dyn std::error::Error>>(())
5266/// ```
5267#[derive(Clone, Copy, Debug)]
5268pub struct SpanRelativeTo<'a> {
5269    kind: SpanRelativeToKind<'a>,
5270}
5271
5272impl<'a> SpanRelativeTo<'a> {
5273    /// Creates a special marker that indicates all days ought to be assumed
5274    /// to be 24 hours without providing a relative reference time.
5275    ///
5276    /// This is relevant to the following APIs:
5277    ///
5278    /// * [`Span::checked_add`]
5279    /// * [`Span::checked_sub`]
5280    /// * [`Span::compare`]
5281    /// * [`Span::total`]
5282    /// * [`Span::round`]
5283    /// * [`Span::to_duration`]
5284    ///
5285    /// Specifically, in a previous version of Jiff, the above APIs permitted
5286    /// _silently_ assuming that days are always 24 hours when a relative
5287    /// reference date wasn't provided. In the current version of Jiff, this
5288    /// silent interpretation no longer happens and instead an error will
5289    /// occur.
5290    ///
5291    /// If you need to use these APIs with spans that contain non-zero units
5292    /// of days or weeks but without a relative reference date, then you may
5293    /// use this routine to create a special marker for `SpanRelativeTo` that
5294    /// permits the APIs above to assume days are always 24 hours.
5295    ///
5296    /// # Motivation
5297    ///
5298    /// The purpose of the marker is two-fold:
5299    ///
5300    /// * Requiring the marker is important for improving the consistency of
5301    /// `Span` APIs. Previously, some APIs (like [`Timestamp::checked_add`])
5302    /// would always return an error if the `Span` given had non-zero
5303    /// units of days or greater. On the other hand, other APIs (like
5304    /// [`Span::checked_add`]) would automatically assume days were always
5305    /// 24 hours if no relative reference time was given and either span had
5306    /// non-zero units of days. With this marker, APIs _never_ assume days are
5307    /// always 24 hours automatically.
5308    /// * When it _is_ appropriate to assume all days are 24 hours
5309    /// (for example, when only dealing with spans derived from
5310    /// [`civil`](crate::civil) datetimes) and where providing a relative
5311    /// reference datetime doesn't make sense. In this case, one _could_
5312    /// provide a "dummy" reference date since the precise date in civil time
5313    /// doesn't impact the length of a day. But a marker like the one returned
5314    /// here is more explicit for the purpose of assuming days are always 24
5315    /// hours.
5316    ///
5317    /// With that said, ideally, callers should provide a relative reference
5318    /// datetime if possible.
5319    ///
5320    /// See [Issue #48] for more discussion on this topic.
5321    ///
5322    /// # Example: different interpretations of "1 day"
5323    ///
5324    /// This example shows how "1 day" can be interpreted differently via the
5325    /// [`Span::total`] API:
5326    ///
5327    /// ```
5328    /// use jiff::{SpanRelativeTo, ToSpan, Unit, Zoned};
5329    ///
5330    /// let span = 1.day();
5331    ///
5332    /// // An error because days aren't always 24 hours:
5333    /// assert_eq!(
5334    ///     span.total(Unit::Hour).unwrap_err().to_string(),
5335    ///     "using unit 'day' in a span or configuration requires that either \
5336    ///      a relative reference time be given or \
5337    ///      `jiff::SpanRelativeTo::days_are_24_hours()` is used to indicate \
5338    ///      invariant 24-hour days, but neither were provided",
5339    /// );
5340    /// // Opt into invariant 24 hour days without a relative date:
5341    /// let marker = SpanRelativeTo::days_are_24_hours();
5342    /// let hours = span.total((Unit::Hour, marker))?;
5343    /// assert_eq!(hours, 24.0);
5344    /// // Days can be shorter than 24 hours:
5345    /// let zdt: Zoned = "2024-03-10[America/New_York]".parse()?;
5346    /// let hours = span.total((Unit::Hour, &zdt))?;
5347    /// assert_eq!(hours, 23.0);
5348    /// // Days can be longer than 24 hours:
5349    /// let zdt: Zoned = "2024-11-03[America/New_York]".parse()?;
5350    /// let hours = span.total((Unit::Hour, &zdt))?;
5351    /// assert_eq!(hours, 25.0);
5352    ///
5353    /// # Ok::<(), Box<dyn std::error::Error>>(())
5354    /// ```
5355    ///
5356    /// Similar behavior applies to the other APIs listed above.
5357    ///
5358    /// # Example: different interpretations of "1 week"
5359    ///
5360    /// This example shows how "1 week" can be interpreted differently via the
5361    /// [`Span::total`] API:
5362    ///
5363    /// ```
5364    /// use jiff::{SpanRelativeTo, ToSpan, Unit, Zoned};
5365    ///
5366    /// let span = 1.week();
5367    ///
5368    /// // An error because days aren't always 24 hours:
5369    /// assert_eq!(
5370    ///     span.total(Unit::Hour).unwrap_err().to_string(),
5371    ///     "using unit 'week' in a span or configuration requires that either \
5372    ///      a relative reference time be given or \
5373    ///      `jiff::SpanRelativeTo::days_are_24_hours()` is used to indicate \
5374    ///      invariant 24-hour days, but neither were provided",
5375    /// );
5376    /// // Opt into invariant 24 hour days without a relative date:
5377    /// let marker = SpanRelativeTo::days_are_24_hours();
5378    /// let hours = span.total((Unit::Hour, marker))?;
5379    /// assert_eq!(hours, 168.0);
5380    /// // Weeks can be shorter than 24*7 hours:
5381    /// let zdt: Zoned = "2024-03-10[America/New_York]".parse()?;
5382    /// let hours = span.total((Unit::Hour, &zdt))?;
5383    /// assert_eq!(hours, 167.0);
5384    /// // Weeks can be longer than 24*7 hours:
5385    /// let zdt: Zoned = "2024-11-03[America/New_York]".parse()?;
5386    /// let hours = span.total((Unit::Hour, &zdt))?;
5387    /// assert_eq!(hours, 169.0);
5388    ///
5389    /// # Ok::<(), Box<dyn std::error::Error>>(())
5390    /// ```
5391    ///
5392    /// # Example: working with [`civil::Date`](crate::civil::Date)
5393    ///
5394    /// A `Span` returned by computing the difference in time between two
5395    /// [`civil::Date`](crate::civil::Date)s will have a non-zero number of
5396    /// days. In older versions of Jiff, if one wanted to add spans returned by
5397    /// these APIs, you could do so without futzing with relative dates. But
5398    /// now you either need to provide a relative date:
5399    ///
5400    /// ```
5401    /// use jiff::{civil::date, ToSpan};
5402    ///
5403    /// let d1 = date(2025, 1, 18);
5404    /// let d2 = date(2025, 1, 26);
5405    /// let d3 = date(2025, 2, 14);
5406    ///
5407    /// let span1 = d2 - d1;
5408    /// let span2 = d3 - d2;
5409    /// let total = span1.checked_add((span2, d1))?;
5410    /// assert_eq!(total, 27.days().fieldwise());
5411    ///
5412    /// # Ok::<(), Box<dyn std::error::Error>>(())
5413    /// ```
5414    ///
5415    /// Or you can provide a marker indicating that days are always 24 hours.
5416    /// This is fine for this use case since one is only doing civil calendar
5417    /// arithmetic and not working with time zones:
5418    ///
5419    /// ```
5420    /// use jiff::{civil::date, SpanRelativeTo, ToSpan};
5421    ///
5422    /// let d1 = date(2025, 1, 18);
5423    /// let d2 = date(2025, 1, 26);
5424    /// let d3 = date(2025, 2, 14);
5425    ///
5426    /// let span1 = d2 - d1;
5427    /// let span2 = d3 - d2;
5428    /// let total = span1.checked_add(
5429    ///     (span2, SpanRelativeTo::days_are_24_hours()),
5430    /// )?;
5431    /// assert_eq!(total, 27.days().fieldwise());
5432    ///
5433    /// # Ok::<(), Box<dyn std::error::Error>>(())
5434    /// ```
5435    ///
5436    /// [Issue #48]: https://github.com/BurntSushi/jiff/issues/48
5437    #[inline]
5438    pub const fn days_are_24_hours() -> SpanRelativeTo<'static> {
5439        let kind = SpanRelativeToKind::DaysAre24Hours;
5440        SpanRelativeTo { kind }
5441    }
5442
5443    /// Converts this public API relative datetime into a more versatile
5444    /// internal representation of the same concept.
5445    ///
5446    /// The unit given should be the maximal non-zero unit present in the
5447    /// operation. (Which might involve two spans, in which case, it is the
5448    /// maximal non-zero unit across both spans.)
5449    ///
5450    /// Basically, the internal `Relative` type is `Cow` which means it isn't
5451    /// `Copy`. But it can present a more uniform API. The public API type
5452    /// doesn't have `Cow` so that it can be `Copy`.
5453    ///
5454    /// We also take this opportunity to attach some convenient data, such
5455    /// as a timestamp when the relative datetime type is civil.
5456    ///
5457    /// This can return `None` if this `SpanRelativeTo` isn't actually a
5458    /// datetime but a "marker" indicating some unit (like days) should be
5459    /// treated as invariant. Or `None` is returned when the given unit is
5460    /// always invariant (hours or smaller).
5461    ///
5462    /// In effect, given that `unit` is the maximal unit involved, `None` is
5463    /// returned when it's safe to assume that all units in the spans can be
5464    /// interpreted as invariant (even if they can sometimes be varying).
5465    ///
5466    /// # Errors
5467    ///
5468    /// If there was a problem doing this conversion, then an error is
5469    /// returned. In practice, this only occurs for a civil datetime near the
5470    /// civil datetime minimum and maximum values.
5471    fn to_relative(&self, unit: Unit) -> Result<Option<Relative<'a>>, Error> {
5472        if !unit.is_variable() {
5473            return Ok(None);
5474        }
5475        match self.kind {
5476            SpanRelativeToKind::Civil(dt) => {
5477                Ok(Some(Relative::Civil(RelativeCivil::new(dt)?)))
5478            }
5479            SpanRelativeToKind::Zoned(zdt) => {
5480                Ok(Some(Relative::Zoned(RelativeZoned {
5481                    zoned: DumbCow::Borrowed(zdt),
5482                })))
5483            }
5484            SpanRelativeToKind::DaysAre24Hours => {
5485                if matches!(unit, Unit::Year | Unit::Month) {
5486                    return Err(Error::from(
5487                        UnitConfigError::RelativeYearOrMonthGivenDaysAre24Hours {
5488                            unit,
5489                        },
5490                    ));
5491                }
5492                Ok(None)
5493            }
5494        }
5495    }
5496}
5497
5498#[derive(Clone, Copy, Debug)]
5499enum SpanRelativeToKind<'a> {
5500    Civil(DateTime),
5501    Zoned(&'a Zoned),
5502    DaysAre24Hours,
5503}
5504
5505impl<'a> From<&'a Zoned> for SpanRelativeTo<'a> {
5506    fn from(zdt: &'a Zoned) -> SpanRelativeTo<'a> {
5507        SpanRelativeTo { kind: SpanRelativeToKind::Zoned(zdt) }
5508    }
5509}
5510
5511impl From<DateTime> for SpanRelativeTo<'static> {
5512    fn from(dt: DateTime) -> SpanRelativeTo<'static> {
5513        SpanRelativeTo { kind: SpanRelativeToKind::Civil(dt) }
5514    }
5515}
5516
5517impl From<Date> for SpanRelativeTo<'static> {
5518    fn from(date: Date) -> SpanRelativeTo<'static> {
5519        let dt = DateTime::from_parts(date, Time::midnight());
5520        SpanRelativeTo { kind: SpanRelativeToKind::Civil(dt) }
5521    }
5522}
5523
5524/// A bit set that keeps track of all non-zero units on a `Span`.
5525///
5526/// Because of alignment, adding this to a `Span` does not make it any bigger.
5527///
5528/// The benefit of this bit set is to make it extremely cheap to enable fast
5529/// paths in various places. For example, doing arithmetic on a `Date` with an
5530/// arbitrary `Span` is pretty involved. But if you know the `Span` only
5531/// consists of non-zero units of days (and zero for all other units), then you
5532/// can take a much cheaper path.
5533#[derive(Clone, Copy, Default)]
5534pub(crate) struct UnitSet(u16);
5535
5536impl UnitSet {
5537    /// Return a bit set representing all units as zero.
5538    #[inline]
5539    const fn empty() -> UnitSet {
5540        UnitSet(0)
5541    }
5542
5543    /// Set the given `unit` to `is_zero` status in this set.
5544    ///
5545    /// When `is_zero` is false, the unit is added to this set. Otherwise,
5546    /// the unit is removed from this set.
5547    #[inline]
5548    const fn set(self, unit: Unit, is_zero: bool) -> UnitSet {
5549        let bit = 1 << unit as usize;
5550        if is_zero {
5551            UnitSet(self.0 & !bit)
5552        } else {
5553            UnitSet(self.0 | bit)
5554        }
5555    }
5556
5557    /// Returns the set constructed from the given slice of units.
5558    #[inline]
5559    pub(crate) const fn from_slice(units: &[Unit]) -> UnitSet {
5560        let mut set = UnitSet::empty();
5561        let mut i = 0;
5562        while i < units.len() {
5563            set = set.set(units[i], false);
5564            i += 1;
5565        }
5566        set
5567    }
5568
5569    /// Returns true if and only if no units are in this set.
5570    #[inline]
5571    pub(crate) fn is_empty(&self) -> bool {
5572        self.0 == 0
5573    }
5574
5575    /// Returns true when this `Span` contains a non-zero value for the given
5576    /// unit.
5577    #[inline]
5578    pub(crate) fn contains(self, unit: Unit) -> bool {
5579        (self.0 & (1 << unit as usize)) != 0
5580    }
5581
5582    /// Returns true if and only if this `Span` contains precisely one
5583    /// non-zero unit corresponding to the unit given.
5584    #[inline]
5585    pub(crate) fn contains_only(self, unit: Unit) -> bool {
5586        self.0 == (1 << unit as usize)
5587    }
5588
5589    /// Returns this set, but with only calendar units.
5590    #[inline]
5591    pub(crate) fn only_calendar(self) -> UnitSet {
5592        UnitSet(self.0 & 0b0000_0011_1100_0000)
5593    }
5594
5595    /// Returns this set, but with only time units.
5596    #[inline]
5597    pub(crate) fn only_time(self) -> UnitSet {
5598        UnitSet(self.0 & 0b0000_0000_0011_1111)
5599    }
5600
5601    /// Returns the intersection of this set and the one given.
5602    #[inline]
5603    pub(crate) fn intersection(self, other: UnitSet) -> UnitSet {
5604        UnitSet(self.0 & other.0)
5605    }
5606
5607    /// Returns the largest unit in this set, or `None` if none are present.
5608    #[inline]
5609    pub(crate) fn largest_unit(self) -> Option<Unit> {
5610        let zeros = usize::try_from(self.0.leading_zeros()).ok()?;
5611        15usize.checked_sub(zeros).and_then(Unit::from_usize)
5612    }
5613}
5614
5615// N.B. This `Debug` impl isn't typically used.
5616//
5617// This is because the `Debug` impl for `Span` just emits itself in the
5618// friendly duration format, which doesn't include internal representation
5619// details like this set. It is included in `Span::debug`, but this isn't
5620// part of the public crate API.
5621impl core::fmt::Debug for UnitSet {
5622    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
5623        write!(f, "{{")?;
5624        let mut units = *self;
5625        let mut i = 0;
5626        while let Some(unit) = units.largest_unit() {
5627            if i > 0 {
5628                write!(f, ", ")?;
5629            }
5630            i += 1;
5631            write!(f, "{}", unit.compact())?;
5632            units = units.set(unit, false);
5633        }
5634        if i == 0 {
5635            write!(f, "∅")?;
5636        }
5637        write!(f, "}}")
5638    }
5639}
5640
5641/// An internal abstraction for managing a relative datetime for use in some
5642/// `Span` APIs.
5643///
5644/// This is effectively the same as a `SpanRelativeTo`, but uses a `Cow<Zoned>`
5645/// instead of a `&Zoned`. This makes it non-`Copy`, but allows us to craft a
5646/// more uniform API. (i.e., `relative + span = relative` instead of `relative
5647/// + span = owned_relative` or whatever.) Note that the `Copy` impl on
5648/// `SpanRelativeTo` means it has to accept a `&Zoned`. It can't ever take a
5649/// `Zoned` since it is non-Copy.
5650///
5651/// NOTE: Separately from above, I think it's plausible that this type could be
5652/// designed a bit differently. Namely, something like this:
5653///
5654/// ```text
5655/// struct Relative<'a> {
5656///     tz: Option<&'a TimeZone>,
5657///     dt: DateTime,
5658///     ts: Timestamp,
5659/// }
5660/// ```
5661///
5662/// That is, we do zone aware stuff but without an actual `Zoned` type. But I
5663/// think in order to make that work, we would need to expose most of the
5664/// `Zoned` API as functions on its component types (DateTime, Timestamp and
5665/// TimeZone). I think we are likely to want to do that for public API reasons,
5666/// but I'd like to resist it since I think it will add a lot of complexity.
5667/// Or maybe we need a `Unzoned` type that is `DateTime` and `Timestamp`, but
5668/// requires passing the time zone in to each of its methods. That might work
5669/// quite well, even if it was just an internal type.
5670///
5671/// Anyway, I'm not 100% sure the above would work, but I think it would. It
5672/// would be nicer because everything would be `Copy` all the time. We'd never
5673/// need a `Cow<TimeZone>` for example, because we never need to change or
5674/// create a new time zone.
5675#[derive(Clone, Debug)]
5676enum Relative<'a> {
5677    Civil(RelativeCivil),
5678    Zoned(RelativeZoned<'a>),
5679}
5680
5681impl<'a> Relative<'a> {
5682    /// Adds the given span to this relative datetime.
5683    ///
5684    /// This defers to either [`DateTime::checked_add`] or
5685    /// [`Zoned::checked_add`], depending on the type of relative datetime.
5686    ///
5687    /// The `Relative` datetime returned is guaranteed to have the same
5688    /// internal datetie type as `self`.
5689    ///
5690    /// # Errors
5691    ///
5692    /// This returns an error in the same cases as the underlying checked
5693    /// arithmetic APIs. In general, this occurs when adding the given `span`
5694    /// would result in overflow.
5695    fn checked_add(&'a self, span: Span) -> Result<Relative<'a>, Error> {
5696        match *self {
5697            Relative::Civil(dt) => Ok(Relative::Civil(dt.checked_add(span)?)),
5698            Relative::Zoned(ref zdt) => {
5699                Ok(Relative::Zoned(zdt.checked_add(span)?))
5700            }
5701        }
5702    }
5703
5704    fn checked_add_duration(
5705        &'a self,
5706        duration: SignedDuration,
5707    ) -> Result<Relative<'a>, Error> {
5708        match *self {
5709            Relative::Civil(dt) => {
5710                Ok(Relative::Civil(dt.checked_add_duration(duration)?))
5711            }
5712            Relative::Zoned(ref zdt) => {
5713                Ok(Relative::Zoned(zdt.checked_add_duration(duration)?))
5714            }
5715        }
5716    }
5717
5718    /// Returns the span of time from this relative datetime to the one given,
5719    /// with units as large as `largest`.
5720    ///
5721    /// # Errors
5722    ///
5723    /// This returns an error in the same cases as when the underlying
5724    /// [`DateTime::until`] or [`Zoned::until`] fail. Because this doesn't
5725    /// set or expose any rounding configuration, this can generally only
5726    /// occur when `largest` is `Unit::Nanosecond` and the span of time
5727    /// between `self` and `other` is too big to represent as a 64-bit integer
5728    /// nanosecond count.
5729    ///
5730    /// # Panics
5731    ///
5732    /// This panics if `self` and `other` are different internal datetime
5733    /// types. For example, if `self` was a civil datetime and `other` were
5734    /// a zoned datetime.
5735    fn until(&self, largest: Unit, other: &Relative) -> Result<Span, Error> {
5736        match (self, other) {
5737            (&Relative::Civil(ref dt1), &Relative::Civil(ref dt2)) => {
5738                dt1.until(largest, dt2)
5739            }
5740            (&Relative::Zoned(ref zdt1), &Relative::Zoned(ref zdt2)) => {
5741                zdt1.until(largest, zdt2)
5742            }
5743            // This would be bad if `Relative` were a public API, but in
5744            // practice, this case never occurs because we don't mixup our
5745            // `Relative` datetime types.
5746            _ => unreachable!(),
5747        }
5748    }
5749
5750    /// Converts this relative datetime to a nanosecond in UTC time.
5751    ///
5752    /// # Errors
5753    ///
5754    /// If there was a problem doing this conversion, then an error is
5755    /// returned. In practice, this only occurs for a civil datetime near the
5756    /// civil datetime minimum and maximum values.
5757    fn to_duration(&self) -> SignedDuration {
5758        match *self {
5759            Relative::Civil(dt) => dt.timestamp.as_duration(),
5760            Relative::Zoned(ref zdt) => zdt.zoned.timestamp().as_duration(),
5761        }
5762    }
5763
5764    /// Create a balanced span of time relative to this datetime.
5765    ///
5766    /// The relative span returned has the same internal datetime type
5767    /// (civil or zoned) as this relative datetime.
5768    ///
5769    /// # Errors
5770    ///
5771    /// This returns an error when the span in this range cannot be
5772    /// represented. In general, this only occurs when asking for largest units
5773    /// of `Unit::Nanosecond` *and* when the span is too big to fit into a
5774    /// 64-bit nanosecond count.
5775    ///
5776    /// This can also return an error in other extreme cases, such as when
5777    /// adding the given span to this relative datetime results in overflow,
5778    /// or if this relative datetime is a civil datetime and it couldn't be
5779    /// converted to a timestamp in UTC.
5780    fn into_relative_span(
5781        self,
5782        largest: Unit,
5783        span: Span,
5784    ) -> Result<RelativeSpan<'a>, Error> {
5785        let kind = match self {
5786            Relative::Civil(start) => {
5787                let end = start.checked_add(span)?;
5788                RelativeSpanKind::Civil { start, end }
5789            }
5790            Relative::Zoned(start) => {
5791                let end = start.checked_add(span)?;
5792                RelativeSpanKind::Zoned { start, end }
5793            }
5794        };
5795        let relspan = kind.into_relative_span(largest)?;
5796        if !span.get_sign().is_zero()
5797            && !relspan.span.get_sign().is_zero()
5798            && span.get_sign() != relspan.span.get_sign()
5799        {
5800            // I haven't quite figured out when this case is hit. I think it's
5801            // actually impossible right? Balancing a duration should not flip
5802            // the sign.
5803            //
5804            // ref: https://github.com/fullcalendar/temporal-polyfill/blob/9e001042864394247181d1a5d591c18057ce32d2/packages/temporal-polyfill/src/internal/durationMath.ts#L236-L238
5805            unreachable!(
5806                "balanced span should have same sign as original span"
5807            )
5808        }
5809        Ok(relspan)
5810    }
5811
5812    /// Rounds the given span using the given rounding configuration.
5813    fn round(
5814        self,
5815        span: Span,
5816        largest: Unit,
5817        increment: &Increment,
5818        mode: RoundMode,
5819    ) -> Result<Span, Error> {
5820        let relspan = self.into_relative_span(largest, span)?;
5821        if relspan.span.get_sign().is_zero() {
5822            return Ok(relspan.span);
5823        }
5824        let nudge = match relspan.kind {
5825            RelativeSpanKind::Civil { start, end } => {
5826                if increment.unit() > Unit::Day {
5827                    Nudge::relative_calendar(
5828                        relspan.span,
5829                        &Relative::Civil(start),
5830                        &Relative::Civil(end),
5831                        increment,
5832                        mode,
5833                    )?
5834                } else {
5835                    Nudge::relative_invariant(
5836                        relspan.span,
5837                        end.timestamp.as_duration(),
5838                        largest,
5839                        increment,
5840                        mode,
5841                    )?
5842                }
5843            }
5844            RelativeSpanKind::Zoned { ref start, ref end } => {
5845                if increment.unit() >= Unit::Day {
5846                    Nudge::relative_calendar(
5847                        relspan.span,
5848                        &Relative::Zoned(start.borrowed()),
5849                        &Relative::Zoned(end.borrowed()),
5850                        increment,
5851                        mode,
5852                    )?
5853                } else if largest >= Unit::Day {
5854                    // This is a special case for zoned datetimes when rounding
5855                    // could bleed into variable units.
5856                    Nudge::relative_zoned_time(
5857                        relspan.span,
5858                        start,
5859                        increment,
5860                        mode,
5861                    )?
5862                } else {
5863                    // Otherwise, rounding is the same as civil datetime.
5864                    Nudge::relative_invariant(
5865                        relspan.span,
5866                        end.zoned.timestamp().as_duration(),
5867                        largest,
5868                        increment,
5869                        mode,
5870                    )?
5871                }
5872            }
5873        };
5874        nudge.bubble(&relspan, increment.unit(), largest)
5875    }
5876}
5877
5878/// A balanced span between a range of civil or zoned datetimes.
5879///
5880/// The span is always balanced up to a certain unit as given to
5881/// `RelativeSpanKind::into_relative_span`.
5882#[derive(Clone, Debug)]
5883struct RelativeSpan<'a> {
5884    span: Span,
5885    kind: RelativeSpanKind<'a>,
5886}
5887
5888/// A civil or zoned datetime range of time.
5889#[derive(Clone, Debug)]
5890enum RelativeSpanKind<'a> {
5891    Civil { start: RelativeCivil, end: RelativeCivil },
5892    Zoned { start: RelativeZoned<'a>, end: RelativeZoned<'a> },
5893}
5894
5895impl<'a> RelativeSpanKind<'a> {
5896    /// Create a balanced `RelativeSpan` from this range of time.
5897    ///
5898    /// # Errors
5899    ///
5900    /// This returns an error when the span in this range cannot be
5901    /// represented. In general, this only occurs when asking for largest units
5902    /// of `Unit::Nanosecond` *and* when the span is too big to fit into a
5903    /// 64-bit nanosecond count.
5904    fn into_relative_span(
5905        self,
5906        largest: Unit,
5907    ) -> Result<RelativeSpan<'a>, Error> {
5908        let span = match self {
5909            RelativeSpanKind::Civil { ref start, ref end } => start
5910                .datetime
5911                .until((largest, end.datetime))
5912                .context(E::FailedSpanBetweenDateTimes { unit: largest })?,
5913            RelativeSpanKind::Zoned { ref start, ref end } => {
5914                start.zoned.until((largest, &*end.zoned)).context(
5915                    E::FailedSpanBetweenZonedDateTimes { unit: largest },
5916                )?
5917            }
5918        };
5919        Ok(RelativeSpan { span, kind: self })
5920    }
5921}
5922
5923/// A wrapper around a civil datetime and a timestamp corresponding to that
5924/// civil datetime in UTC.
5925///
5926/// Haphazardly interpreting a civil datetime in UTC is an odd and *usually*
5927/// incorrect thing to do. But the way we use it here is basically just to give
5928/// it an "anchoring" point such that we can represent it using a single
5929/// integer for rounding purposes. It is only used in a context *relative* to
5930/// another civil datetime interpreted in UTC. In this fashion, the selection
5931/// of UTC specifically doesn't really matter. We could use any time zone.
5932/// (Although, it must be a time zone without any transitions, otherwise we
5933/// could wind up with time zone aware results in a context where that would
5934/// be unexpected since this is civil time.)
5935#[derive(Clone, Copy, Debug)]
5936struct RelativeCivil {
5937    datetime: DateTime,
5938    timestamp: Timestamp,
5939}
5940
5941impl RelativeCivil {
5942    /// Creates a new relative wrapper around the given civil datetime.
5943    ///
5944    /// This wrapper bundles a timestamp for the given datetime by interpreting
5945    /// it as being in UTC. This is an "odd" thing to do, but it's only used
5946    /// in the context of determining the length of time between two civil
5947    /// datetimes. So technically, any time zone without transitions could be
5948    /// used.
5949    ///
5950    /// # Errors
5951    ///
5952    /// This returns an error if the datetime could not be converted to a
5953    /// timestamp. This only occurs near the minimum and maximum civil datetime
5954    /// values.
5955    fn new(datetime: DateTime) -> Result<RelativeCivil, Error> {
5956        let timestamp = datetime
5957            .to_zoned(TimeZone::UTC)
5958            .context(E::ConvertDateTimeToTimestamp)?
5959            .timestamp();
5960        Ok(RelativeCivil { datetime, timestamp })
5961    }
5962
5963    /// Returns the result of [`DateTime::checked_add`].
5964    ///
5965    /// # Errors
5966    ///
5967    /// Returns an error in the same cases as `DateTime::checked_add`. That is,
5968    /// when adding the span to this zoned datetime would overflow.
5969    ///
5970    /// This also returns an error if the resulting datetime could not be
5971    /// converted to a timestamp in UTC. This only occurs near the minimum and
5972    /// maximum datetime values.
5973    fn checked_add(&self, span: Span) -> Result<RelativeCivil, Error> {
5974        let datetime = self.datetime.checked_add(span)?;
5975        let timestamp = datetime
5976            .to_zoned(TimeZone::UTC)
5977            .context(E::ConvertDateTimeToTimestamp)?
5978            .timestamp();
5979        Ok(RelativeCivil { datetime, timestamp })
5980    }
5981
5982    /// Returns the result of [`DateTime::checked_add`] with an absolute
5983    /// duration.
5984    ///
5985    /// # Errors
5986    ///
5987    /// Returns an error in the same cases as `DateTime::checked_add`. That is,
5988    /// when adding the span to this zoned datetime would overflow.
5989    ///
5990    /// This also returns an error if the resulting datetime could not be
5991    /// converted to a timestamp in UTC. This only occurs near the minimum and
5992    /// maximum datetime values.
5993    fn checked_add_duration(
5994        &self,
5995        duration: SignedDuration,
5996    ) -> Result<RelativeCivil, Error> {
5997        let datetime = self.datetime.checked_add(duration)?;
5998        let timestamp = datetime
5999            .to_zoned(TimeZone::UTC)
6000            .context(E::ConvertDateTimeToTimestamp)?
6001            .timestamp();
6002        Ok(RelativeCivil { datetime, timestamp })
6003    }
6004
6005    /// Returns the result of [`DateTime::until`].
6006    ///
6007    /// # Errors
6008    ///
6009    /// Returns an error in the same cases as `DateTime::until`. That is, when
6010    /// the span for the given largest unit cannot be represented. This can
6011    /// generally only happen when `largest` is `Unit::Nanosecond` and the span
6012    /// cannot be represented as a 64-bit integer of nanoseconds.
6013    fn until(
6014        &self,
6015        largest: Unit,
6016        other: &RelativeCivil,
6017    ) -> Result<Span, Error> {
6018        self.datetime
6019            .until((largest, other.datetime))
6020            .context(E::FailedSpanBetweenDateTimes { unit: largest })
6021    }
6022}
6023
6024/// A simple wrapper around a possibly borrowed `Zoned`.
6025#[derive(Clone, Debug)]
6026struct RelativeZoned<'a> {
6027    zoned: DumbCow<'a, Zoned>,
6028}
6029
6030impl<'a> RelativeZoned<'a> {
6031    /// Returns the result of [`Zoned::checked_add`].
6032    ///
6033    /// # Errors
6034    ///
6035    /// Returns an error in the same cases as `Zoned::checked_add`. That is,
6036    /// when adding the span to this zoned datetime would overflow.
6037    fn checked_add(
6038        &self,
6039        span: Span,
6040    ) -> Result<RelativeZoned<'static>, Error> {
6041        let zoned = self.zoned.checked_add(span)?;
6042        Ok(RelativeZoned { zoned: DumbCow::Owned(zoned) })
6043    }
6044
6045    /// Returns the result of [`Zoned::checked_add`] with an absolute duration.
6046    ///
6047    /// # Errors
6048    ///
6049    /// Returns an error in the same cases as `Zoned::checked_add`. That is,
6050    /// when adding the span to this zoned datetime would overflow.
6051    fn checked_add_duration(
6052        &self,
6053        duration: SignedDuration,
6054    ) -> Result<RelativeZoned<'static>, Error> {
6055        let zoned = self.zoned.checked_add(duration)?;
6056        Ok(RelativeZoned { zoned: DumbCow::Owned(zoned) })
6057    }
6058
6059    /// Returns the result of [`Zoned::until`].
6060    ///
6061    /// # Errors
6062    ///
6063    /// Returns an error in the same cases as `Zoned::until`. That is, when
6064    /// the span for the given largest unit cannot be represented. This can
6065    /// generally only happen when `largest` is `Unit::Nanosecond` and the span
6066    /// cannot be represented as a 64-bit integer of nanoseconds.
6067    fn until(
6068        &self,
6069        largest: Unit,
6070        other: &RelativeZoned<'a>,
6071    ) -> Result<Span, Error> {
6072        self.zoned
6073            .until((largest, &*other.zoned))
6074            .context(E::FailedSpanBetweenZonedDateTimes { unit: largest })
6075    }
6076
6077    /// Returns the borrowed version of self; useful when you need to convert
6078    /// `&RelativeZoned` into `RelativeZoned` without cloning anything.
6079    fn borrowed(&'a self) -> RelativeZoned<'a> {
6080        RelativeZoned { zoned: self.zoned.borrowed() }
6081    }
6082}
6083
6084// The code below is the "core" rounding logic for spans. It was greatly
6085// inspired by this gist[1] and the fullcalendar Temporal polyfill[2]. In
6086// particular, the algorithm implemented below is a major simplification from
6087// how Temporal used to work[3]. Parts of it are still in rough and unclear
6088// shape IMO.
6089//
6090// [1]: https://gist.github.com/arshaw/36d3152c21482bcb78ea2c69591b20e0
6091// [2]: https://github.com/fullcalendar/temporal-polyfill
6092// [3]: https://github.com/tc39/proposal-temporal/issues/2792
6093
6094/// The result of a span rounding strategy. There are three:
6095///
6096/// * Rounding spans relative to civil datetimes using only invariant
6097/// units (days or less). This is achieved by converting the span to a simple
6098/// integer number of nanoseconds and then rounding that.
6099/// * Rounding spans relative to either a civil datetime or a zoned datetime
6100/// where rounding might involve changing non-uniform units. That is, when
6101/// the smallest unit is greater than days for civil datetimes and greater
6102/// than hours for zoned datetimes.
6103/// * Rounding spans relative to a zoned datetime whose smallest unit is
6104/// less than days.
6105///
6106/// Each of these might produce a bottom heavy span that needs to be
6107/// re-balanced. This type represents that result via one of three constructors
6108/// corresponding to each of the above strategies, and then provides a routine
6109/// for rebalancing via "bubbling."
6110#[derive(Debug)]
6111struct Nudge {
6112    /// A possibly bottom heavy rounded span.
6113    span: Span,
6114    /// The nanosecond timestamp corresponding to `relative + span`, where
6115    /// `span` is the (possibly bottom heavy) rounded span.
6116    rounded_relative_end: SignedDuration,
6117    /// Whether rounding may have created a bottom heavy span such that a
6118    /// calendar unit might need to be incremented after re-balancing smaller
6119    /// units.
6120    grew_big_unit: bool,
6121}
6122
6123impl Nudge {
6124    /// Performs rounding on the given span limited to invariant units.
6125    ///
6126    /// For civil datetimes, this means the smallest unit must be days or less,
6127    /// but the largest unit can be bigger. For zoned datetimes, this means
6128    /// that *both* the largest and smallest unit must be hours or less. This
6129    /// is because zoned datetimes with rounding that can spill up to days
6130    /// requires special handling.
6131    ///
6132    /// It works by converting the span to a single integer number of
6133    /// nanoseconds, rounding it and then converting back to a span.
6134    fn relative_invariant(
6135        balanced: Span,
6136        relative_end: SignedDuration,
6137        largest: Unit,
6138        increment: &Increment,
6139        mode: RoundMode,
6140    ) -> Result<Nudge, Error> {
6141        // Ensures this is only called when rounding invariant units.
6142        // Technically, it would be fine to allow weeks here, but this
6143        // code doesn't handle the special case of smallest==Week because
6144        // it just didn't account for it originally. But it probably should.
6145        // Then we could use this routine for rounding civil datetimes when
6146        // smallest==Week.
6147        assert!(increment.unit() <= Unit::Day);
6148
6149        let sign = balanced.get_sign();
6150        let balanced_nanos = balanced.to_invariant_duration();
6151        let rounded_nanos = increment.round(mode, balanced_nanos)?;
6152        let span = Span::from_invariant_duration(largest, rounded_nanos)
6153            .context(E::ConvertNanoseconds { unit: largest })?
6154            .years(balanced.get_years())
6155            .months(balanced.get_months())
6156            .weeks(balanced.get_weeks());
6157
6158        let diff_nanos = rounded_nanos - balanced_nanos;
6159        let diff_days =
6160            rounded_nanos.as_civil_days() - balanced_nanos.as_civil_days();
6161        let grew_big_unit = b::Sign::from(diff_days) == sign;
6162        let rounded_relative_end = relative_end + diff_nanos;
6163        Ok(Nudge { span, rounded_relative_end, grew_big_unit })
6164    }
6165
6166    /// Performs rounding on the given span where the smallest unit configured
6167    /// implies that rounding will cover calendar or "non-uniform" units. (That
6168    /// is, units whose length can change based on the relative datetime.)
6169    fn relative_calendar(
6170        balanced: Span,
6171        relative_start: &Relative<'_>,
6172        relative_end: &Relative<'_>,
6173        increment: &Increment,
6174        mode: RoundMode,
6175    ) -> Result<Nudge, Error> {
6176        // This implementation is quite tricky and subtle. It is loosely based
6177        // on the fullcalendar polyfill for Temporal:
6178        // repo: https://github.com/fullcalendar/temporal-polyfill/
6179        // commit: bc1baf3875392ecd8522d40e7eecb55fa582808c
6180        // file: packages/temporal-polyfill/src/internal/round.ts
6181        // lines: L647-L711
6182        //
6183        // This diverges from the fullcalendar polyfill, however, by avoiding
6184        // the use of floating point. In part because almost all of Jiff avoids
6185        // floats (two exceptions being `Span::total` and
6186        // `SignedDuration::try_from_secs_{f32,f64}`). We used to use floats
6187        // here, and it drove be nuts because it was impossible to avoid in
6188        // this code path. And it also required duplicating our rounding code
6189        // just to handle this case.
6190        //
6191        // In any case, I stared at this code and fullcalendar's implementation
6192        // for quite some time, and I believe converted it over to sticking
6193        // with just integers. The key insight is moving everything to
6194        // nanoseconds and rounding there. I'm not quite sure why fullcalendar
6195        // doesn't do it this way. I think they are more tightly coupled with
6196        // Javascript's `number`, and so avoiding floats probably isn't a
6197        // priority?
6198        //
6199        // OK, so how does this work? The basic idea here is that, e.g., we
6200        // don't know long "1 month" or "1 year" is. (Or "1 day" in the case of
6201        // a zoned datetime.) So how do we know whether to e.g., round "1 month
6202        // 15 days" up to "2 month" or down to "1 month"? (For the `HalfExpand`
6203        // rounding mode.) So for this case, we need to compute what "1 month"
6204        // actually means in the context of our relative datetime (which we
6205        // must have if we're calling this routine). This is done by doing
6206        // some span arithemtic to calculate the length of time for one
6207        // increment's worth of the units we are rounding to.
6208        //
6209        // This approach is overall very similar to the approach we used for
6210        // rounding zoned datetimes. (Because the length of a day may vary.)
6211
6212        // This bit is actually pretty important context: this code *only*
6213        // covers the case when the user asks for a smallest unit that is a
6214        // calendar unit. That means that the rounding we're doing is for a
6215        // unit that is potentially of varying length. If our relative datetime
6216        // is civil, then weeks/days won't be varying length, but the code
6217        // below still handles it. (Although this code won't be used when we
6218        // have a relative civil datetime and request a smallest unit of days.
6219        // That's because we can fall back to code assuming that days are an
6220        // invariant unit.)
6221        assert!(increment.unit() >= Unit::Day);
6222
6223        let increment_units = i64::from(increment.value());
6224        let smallest = increment.unit();
6225        let sign = balanced.get_sign();
6226        // We want to measure the length of `increment`, which is done by
6227        // adding spans to `relative_start` with just one unit adjusted. The
6228        // `truncated` value is our starting point. The next will be
6229        // `truncated + (sign * increment)`.
6230        let truncated =
6231            increment_units * (balanced.get_unit(smallest) / increment_units);
6232        // Drop all units below smallest. We specifically don't want them and
6233        // here is where we no longer need them. `relative_end` still captures
6234        // how "close" we are between increments of `smallest`.
6235        let span =
6236            balanced.without_lower(smallest).try_unit(smallest, truncated)?;
6237        // This is OK because the increment value is guaranteed to be in the
6238        // range `1..=1_000_000_000`. Therefore, multiplying by {-1,0,1} is
6239        // always valid.
6240        //
6241        // The "amount" refers to the length of time (in units of `smallest`)
6242        // we want to measure. We don't actually know how long an `increment`
6243        // is. So we "measure" is by adding (or subtracting, depending on the
6244        // sign of the original span) to our relative datetime.
6245        let amount = sign * increment_units;
6246        // This is the "measurement" we mentioned above. We get back
6247        // `relative_start + span` and `relative_start + span + extra`,
6248        // where `extra` is `span` but with its `smallest` units set to
6249        // `amount`. Thus, `relative1 - relative0` corresponds to the length
6250        // in time, in nanoseconds, of `increment` units of `smallest`.
6251        let (relative0, relative1) =
6252            unit_start_and_end(relative_start, span, smallest, amount)?;
6253
6254        // This corresponds to how far our original span gets us to the next
6255        // increment. That is, `relative_end = relative_start + original_span`.
6256        // (We actually don't have `original_span` here, but that's how
6257        // `relative_end` is computed. `balanced` is then computed from
6258        // `relative_start.until((largest_unit, relative_end))`.
6259        let progress_nanos = relative_end.to_duration() - relative0;
6260        // This is the length of `increment` units of `smallest`, but in units
6261        // of nanoseconds. The `.abs()` is OK because the difference in time,
6262        // even in nanoseconds, between -9999-01-01 and 9999-12-31 will never
6263        // be `SignedDuration::MIN`.
6264        let increment_nanos = (relative1 - relative0).abs();
6265        // Now we finally do the actual rounding: we round how much "progress"
6266        // we've made toward `relative1` by rounding `progress_nanos` to the
6267        // nearest increment value.
6268        //
6269        // The rounded nanoseconds returned can be greater than
6270        // `increment_nanos` when `smallest==Unit::Week` and the *original*
6271        // span had non-zero week units. This is because computing a balanced
6272        // span eliminates the week units, and so it is expected that
6273        // `relative_end` might be much bigger (or smaller, for negative spans)
6274        // than `relative1`.
6275        let rounded_nanos =
6276            mode.round_by_duration(progress_nanos, increment_nanos)?;
6277        // If we rounded up, then it's possible we might need to to re-balance
6278        // our span. (This happens in `bubble`.)
6279        let grew_big_unit =
6280            sign == b::Sign::from(rounded_nanos - progress_nanos);
6281        // These asserts check an assumption that, since we're dealing with
6282        // calendar units, and because time zone transitions never have
6283        // precision less than 1 second, it follows that the *length* of
6284        // the increment at nanosecond precision will never have non-zero
6285        // sub-seconds. This also guarantees that the result of rounding will
6286        // also never have non-zero sub-seconds (since the result of rounding
6287        // has to be a multiple of the increment).
6288        //
6289        // This is an important assumption to check, because we drop the
6290        // sub-second components on these durations in order to do division on
6291        // them below via 64-bit integers. (Otherwise we'd have to use 128-bit
6292        // integers.)
6293        debug_assert_eq!(rounded_nanos.subsec_nanos(), 0);
6294        debug_assert_eq!(increment_nanos.subsec_nanos(), 0);
6295        // Now we need to get back to our original units. We started with
6296        // `truncated`, so just add the number of units we covered via
6297        // rounding. We must multiply by `increment` because `rounded /
6298        // increment` gets us back the number of *increments* we rounded over.
6299        // But the actual number of units may be bigger.
6300        let span = span.try_unit(
6301            smallest,
6302            truncated
6303                + (increment_units
6304                    * (rounded_nanos.as_secs() / increment_nanos.as_secs())),
6305        )?;
6306        // If we rounded up, then the time we don't want to exceed is
6307        // `relative1`. Otherwise, we don't want to exceed `relative0`.
6308        // (This is used later in `bubble`.)
6309        let rounded_relative_end =
6310            if grew_big_unit { relative1 } else { relative0 };
6311        Ok(Nudge { span, rounded_relative_end, grew_big_unit })
6312    }
6313
6314    /// Performs rounding on the given span where the smallest unit is hours
6315    /// or less *and* the relative datetime is time zone aware.
6316    fn relative_zoned_time(
6317        balanced: Span,
6318        relative_start: &RelativeZoned<'_>,
6319        increment: &Increment,
6320        mode: RoundMode,
6321    ) -> Result<Nudge, Error> {
6322        let sign = balanced.get_sign();
6323        let time_dur = balanced.only_lower(Unit::Day).to_invariant_duration();
6324        let mut rounded_time_nanos = increment.round(mode, time_dur)?;
6325        let (relative0, relative1) = unit_start_and_end(
6326            &Relative::Zoned(relative_start.borrowed()),
6327            balanced.without_lower(Unit::Day),
6328            Unit::Day,
6329            sign.as_i64(),
6330        )?;
6331        let day_nanos = relative1 - relative0;
6332        let beyond_day_nanos = rounded_time_nanos - day_nanos;
6333
6334        let mut day_delta = 0;
6335        let rounded_relative_end = if beyond_day_nanos.is_zero()
6336            || b::Sign::from(beyond_day_nanos) == sign
6337        {
6338            day_delta += 1;
6339            rounded_time_nanos = increment.round(mode, beyond_day_nanos)?;
6340            relative1 + rounded_time_nanos
6341        } else {
6342            relative0 + rounded_time_nanos
6343        };
6344
6345        let span =
6346            Span::from_invariant_duration(Unit::Hour, rounded_time_nanos)
6347                .context(E::ConvertNanoseconds { unit: Unit::Hour })?
6348                .years(balanced.get_years())
6349                .months(balanced.get_months())
6350                .weeks(balanced.get_weeks())
6351                .days(balanced.get_days() + day_delta);
6352        let grew_big_unit = day_delta != 0;
6353        Ok(Nudge { span, rounded_relative_end, grew_big_unit })
6354    }
6355
6356    /// This "bubbles" up the units in a potentially "bottom heavy" span to
6357    /// larger units. For example, P1m50d relative to March 1 is bottom heavy.
6358    /// This routine will bubble the days up to months to get P2m19d.
6359    ///
6360    /// # Errors
6361    ///
6362    /// This routine fails if any arithmetic on the individual units fails, or
6363    /// when span arithmetic on the relative datetime given fails.
6364    fn bubble(
6365        &self,
6366        relative: &RelativeSpan,
6367        smallest: Unit,
6368        largest: Unit,
6369    ) -> Result<Span, Error> {
6370        if !self.grew_big_unit || smallest == Unit::Week {
6371            return Ok(self.span);
6372        }
6373
6374        let smallest = smallest.max(Unit::Day);
6375        let mut balanced = self.span;
6376        let sign = balanced.get_sign();
6377        let mut unit = smallest;
6378        while let Some(u) = unit.next() {
6379            unit = u;
6380            if unit > largest {
6381                break;
6382            }
6383            // We only bubble smaller units up into weeks when the largest unit
6384            // is explicitly set to weeks. Otherwise, we leave it as-is.
6385            if unit == Unit::Week && largest != Unit::Week {
6386                continue;
6387            }
6388
6389            let span_start = balanced.without_lower(unit);
6390            let new_units = span_start
6391                .get_unit(unit)
6392                .checked_add(sign.as_i64())
6393                .ok_or_else(|| unit.error())?;
6394            let span_end = span_start.try_unit(unit, new_units)?;
6395            let threshold = match relative.kind {
6396                RelativeSpanKind::Civil { ref start, .. } => {
6397                    start.checked_add(span_end)?.timestamp
6398                }
6399                RelativeSpanKind::Zoned { ref start, .. } => {
6400                    start.checked_add(span_end)?.zoned.timestamp()
6401                }
6402            };
6403            // If we overshoot our expected endpoint, then bail.
6404            let beyond = self.rounded_relative_end - threshold.as_duration();
6405            if beyond.is_zero() || b::Sign::from(beyond) == sign {
6406                balanced = span_end;
6407            } else {
6408                break;
6409            }
6410        }
6411        Ok(balanced)
6412    }
6413}
6414
6415/// Rounds a span consisting of only invariant units.
6416///
6417/// This only applies when the max of the units in the span being rounded,
6418/// the largest configured unit and the smallest configured unit are all
6419/// invariant. That is, hours or lower for spans without a relative datetime,
6420/// or weeks or lower for spans with a `SpanRelativeTo::days_are_24_hours()`
6421/// marker.
6422///
6423/// All we do here is convert the span to an integer number of nanoseconds,
6424/// round that and then convert back. There aren't any tricky corner cases to
6425/// consider here.
6426fn round_span_invariant(
6427    span: Span,
6428    largest: Unit,
6429    increment: &Increment,
6430    mode: RoundMode,
6431) -> Result<Span, Error> {
6432    debug_assert!(increment.unit() <= Unit::Week);
6433    debug_assert!(largest <= Unit::Week);
6434    let dur = span.to_invariant_duration();
6435    let rounded = increment.round(mode, dur)?;
6436    Span::from_invariant_duration(largest, rounded)
6437        .context(E::ConvertNanoseconds { unit: largest })
6438}
6439
6440/// Returns the nanosecond timestamps of `relative + span` and `relative +
6441/// {amount of unit} + span`.
6442///
6443/// This is useful for determining the actual length, in nanoseconds, of some
6444/// unit amount (usually a single unit). Usually, this is called with a span
6445/// whose units lower than `unit` are zeroed out and with an `amount` that
6446/// is `-1` or `1` or `0`. So for example, if `unit` were `Unit::Day`, then
6447/// you'd get back two nanosecond timestamps relative to the relative datetime
6448/// given that start exactly "one day" apart. (Which might be different than 24
6449/// hours, depending on the time zone.)
6450///
6451/// # Errors
6452///
6453/// This returns an error if adding the units overflows, or if doing the span
6454/// arithmetic on `relative` overflows.
6455fn unit_start_and_end(
6456    relative: &Relative<'_>,
6457    span: Span,
6458    unit: Unit,
6459    amount: i64,
6460) -> Result<(SignedDuration, SignedDuration), Error> {
6461    let amount =
6462        span.get_unit(unit).checked_add(amount).ok_or_else(|| unit.error())?;
6463    let span_amount = span.try_unit(unit, amount)?;
6464    let relative0 = relative.checked_add(span)?.to_duration();
6465    let relative1 = relative.checked_add(span_amount)?.to_duration();
6466    // This assertion gives better failure modes to what would otherwise be
6467    // subtle errors downstream if the durations returned here were equivalent.
6468    // It would imply that the physical time duration between them is zero,
6469    // and thus adding two spans---where one is strictly bigger/smaller than
6470    // the other---would produce identical timestamps.
6471    assert_ne!(
6472        relative0, relative1,
6473        "adding different spans should produce different timestamps"
6474    );
6475    Ok((relative0, relative1))
6476}
6477
6478/// A common parsing function that works in bytes.
6479///
6480/// Specifically, this parses either an ISO 8601 duration into a `Span` or
6481/// a "friendly" duration into a `Span`. It also tries to give decent error
6482/// messages.
6483///
6484/// This works because the friendly and ISO 8601 formats have non-overlapping
6485/// prefixes. Both can start with a `+` or `-`, but aside from that, an ISO
6486/// 8601 duration _always_ has to start with a `P` or `p`. We can utilize this
6487/// property to very quickly determine how to parse the input. We just need to
6488/// handle the possibly ambiguous case with a leading sign a little carefully
6489/// in order to ensure good error messages.
6490///
6491/// (We do the same thing for `SignedDuration`.)
6492#[cfg_attr(feature = "perf-inline", inline(always))]
6493fn parse_iso_or_friendly(bytes: &[u8]) -> Result<Span, Error> {
6494    let Some((&byte, tail)) = bytes.split_first() else {
6495        return Err(crate::Error::from(
6496            crate::error::fmt::Error::HybridDurationEmpty,
6497        ));
6498    };
6499    let mut first = byte;
6500    // N.B. Unsigned durations don't support negative durations (of
6501    // course), but we still check for it here so that we can defer to
6502    // the dedicated parsers. They will provide their own error messages.
6503    if first == b'+' || first == b'-' {
6504        let Some(&byte) = tail.first() else {
6505            return Err(crate::Error::from(
6506                crate::error::fmt::Error::HybridDurationPrefix { sign: first },
6507            ));
6508        };
6509        first = byte;
6510    }
6511    if first == b'P' || first == b'p' {
6512        temporal::DEFAULT_SPAN_PARSER.parse_span(bytes)
6513    } else {
6514        friendly::DEFAULT_SPAN_PARSER.parse_span(bytes)
6515    }
6516}
6517
6518fn requires_relative_date_err(unit: Unit) -> Result<(), Error> {
6519    if unit.is_variable() {
6520        return Err(Error::from(if matches!(unit, Unit::Week | Unit::Day) {
6521            UnitConfigError::RelativeWeekOrDay { unit }
6522        } else {
6523            UnitConfigError::RelativeYearOrMonth { unit }
6524        }));
6525    }
6526    Ok(())
6527}
6528
6529#[cfg(test)]
6530mod tests {
6531    use std::io::Cursor;
6532
6533    use alloc::string::ToString;
6534
6535    use crate::{civil::date, RoundMode};
6536
6537    use super::*;
6538
6539    #[test]
6540    fn test_total() {
6541        if crate::tz::db().is_definitively_empty() {
6542            return;
6543        }
6544
6545        let span = 130.hours().minutes(20);
6546        let total = span.total(Unit::Second).unwrap();
6547        assert_eq!(total, 469200.0);
6548
6549        let span = 123456789.seconds();
6550        let total = span
6551            .total(SpanTotal::from(Unit::Day).days_are_24_hours())
6552            .unwrap();
6553        assert_eq!(total, 1428.8980208333332);
6554
6555        let span = 2756.hours();
6556        let dt = date(2020, 1, 1).at(0, 0, 0, 0);
6557        let zdt = dt.in_tz("Europe/Rome").unwrap();
6558        let total = span.total((Unit::Month, &zdt)).unwrap();
6559        assert_eq!(total, 3.7958333333333334);
6560        let total = span.total((Unit::Month, dt)).unwrap();
6561        assert_eq!(total, 3.7944444444444443);
6562    }
6563
6564    #[test]
6565    fn test_compare() {
6566        if crate::tz::db().is_definitively_empty() {
6567            return;
6568        }
6569
6570        let span1 = 79.hours().minutes(10);
6571        let span2 = 79.hours().seconds(630);
6572        let span3 = 78.hours().minutes(50);
6573        let mut array = [span1, span2, span3];
6574        array.sort_by(|sp1, sp2| sp1.compare(sp2).unwrap());
6575        assert_eq!(array, [span3, span1, span2].map(SpanFieldwise));
6576
6577        let day24 = SpanRelativeTo::days_are_24_hours();
6578        let span1 = 79.hours().minutes(10);
6579        let span2 = 3.days().hours(7).seconds(630);
6580        let span3 = 3.days().hours(6).minutes(50);
6581        let mut array = [span1, span2, span3];
6582        array.sort_by(|sp1, sp2| sp1.compare((sp2, day24)).unwrap());
6583        assert_eq!(array, [span3, span1, span2].map(SpanFieldwise));
6584
6585        let dt = date(2020, 11, 1).at(0, 0, 0, 0);
6586        let zdt = dt.in_tz("America/Los_Angeles").unwrap();
6587        array.sort_by(|sp1, sp2| sp1.compare((sp2, &zdt)).unwrap());
6588        assert_eq!(array, [span1, span3, span2].map(SpanFieldwise));
6589    }
6590
6591    #[test]
6592    fn test_checked_add() {
6593        let span1 = 1.hour();
6594        let span2 = 30.minutes();
6595        let sum = span1.checked_add(span2).unwrap();
6596        span_eq!(sum, 1.hour().minutes(30));
6597
6598        let span1 = 1.hour().minutes(30);
6599        let span2 = 2.hours().minutes(45);
6600        let sum = span1.checked_add(span2).unwrap();
6601        span_eq!(sum, 4.hours().minutes(15));
6602
6603        let span = 50
6604            .years()
6605            .months(50)
6606            .days(50)
6607            .hours(50)
6608            .minutes(50)
6609            .seconds(50)
6610            .milliseconds(500)
6611            .microseconds(500)
6612            .nanoseconds(500);
6613        let relative = date(1900, 1, 1).at(0, 0, 0, 0);
6614        let sum = span.checked_add((span, relative)).unwrap();
6615        let expected = 108
6616            .years()
6617            .months(7)
6618            .days(12)
6619            .hours(5)
6620            .minutes(41)
6621            .seconds(41)
6622            .milliseconds(1)
6623            .microseconds(1)
6624            .nanoseconds(0);
6625        span_eq!(sum, expected);
6626
6627        let span = 1.month().days(15);
6628        let relative = date(2000, 2, 1).at(0, 0, 0, 0);
6629        let sum = span.checked_add((span, relative)).unwrap();
6630        span_eq!(sum, 3.months());
6631        let relative = date(2000, 3, 1).at(0, 0, 0, 0);
6632        let sum = span.checked_add((span, relative)).unwrap();
6633        span_eq!(sum, 2.months().days(30));
6634    }
6635
6636    #[test]
6637    fn test_round_day_time() {
6638        let span = 29.seconds();
6639        let rounded = span.round(Unit::Minute).unwrap();
6640        span_eq!(rounded, 0.minute());
6641
6642        let span = 30.seconds();
6643        let rounded = span.round(Unit::Minute).unwrap();
6644        span_eq!(rounded, 1.minute());
6645
6646        let span = 8.seconds();
6647        let rounded = span
6648            .round(
6649                SpanRound::new()
6650                    .smallest(Unit::Nanosecond)
6651                    .largest(Unit::Microsecond),
6652            )
6653            .unwrap();
6654        span_eq!(rounded, 8_000_000.microseconds());
6655
6656        let span = 130.minutes();
6657        let rounded = span
6658            .round(SpanRound::new().largest(Unit::Day).days_are_24_hours())
6659            .unwrap();
6660        span_eq!(rounded, 2.hours().minutes(10));
6661
6662        let span = 10.minutes().seconds(52);
6663        let rounded = span.round(Unit::Minute).unwrap();
6664        span_eq!(rounded, 11.minutes());
6665
6666        let span = 10.minutes().seconds(52);
6667        let rounded = span
6668            .round(
6669                SpanRound::new().smallest(Unit::Minute).mode(RoundMode::Trunc),
6670            )
6671            .unwrap();
6672        span_eq!(rounded, 10.minutes());
6673
6674        let span = 2.hours().minutes(34).seconds(18);
6675        let rounded =
6676            span.round(SpanRound::new().largest(Unit::Second)).unwrap();
6677        span_eq!(rounded, 9258.seconds());
6678
6679        let span = 6.minutes();
6680        let rounded = span
6681            .round(
6682                SpanRound::new()
6683                    .smallest(Unit::Minute)
6684                    .increment(5)
6685                    .mode(RoundMode::Ceil),
6686            )
6687            .unwrap();
6688        span_eq!(rounded, 10.minutes());
6689    }
6690
6691    #[test]
6692    fn test_round_relative_zoned_calendar() {
6693        if crate::tz::db().is_definitively_empty() {
6694            return;
6695        }
6696
6697        let span = 2756.hours();
6698        let relative =
6699            date(2020, 1, 1).at(0, 0, 0, 0).in_tz("America/New_York").unwrap();
6700        let options = SpanRound::new()
6701            .largest(Unit::Year)
6702            .smallest(Unit::Day)
6703            .relative(&relative);
6704        let rounded = span.round(options).unwrap();
6705        span_eq!(rounded, 3.months().days(24));
6706
6707        let span = 24.hours().nanoseconds(5);
6708        let relative = date(2000, 10, 29)
6709            .at(0, 0, 0, 0)
6710            .in_tz("America/Vancouver")
6711            .unwrap();
6712        let options = SpanRound::new()
6713            .largest(Unit::Day)
6714            .smallest(Unit::Minute)
6715            .relative(&relative)
6716            .mode(RoundMode::Expand)
6717            .increment(30);
6718        let rounded = span.round(options).unwrap();
6719        // It seems like this is the correct answer, although it apparently
6720        // differs from Temporal and the FullCalendar polyfill. I'm not sure
6721        // what accounts for the difference in the implementation.
6722        //
6723        // See: https://github.com/tc39/proposal-temporal/pull/2758#discussion_r1597255245
6724        span_eq!(rounded, 24.hours().minutes(30));
6725
6726        // Ref: https://github.com/tc39/proposal-temporal/issues/2816#issuecomment-2115608460
6727        let span = -1.month().hours(24);
6728        let relative: crate::Zoned = date(2024, 4, 11)
6729            .at(2, 0, 0, 0)
6730            .in_tz("America/New_York")
6731            .unwrap();
6732        let options =
6733            SpanRound::new().smallest(Unit::Millisecond).relative(&relative);
6734        let rounded = span.round(options).unwrap();
6735        span_eq!(rounded, -1.month().days(1).hours(1));
6736        let dt = relative.checked_add(span).unwrap();
6737        let diff = relative.until((Unit::Month, &dt)).unwrap();
6738        span_eq!(diff, -1.month().days(1).hours(1));
6739
6740        // Like the above, but don't use a datetime near a DST transition. In
6741        // this case, a day is a normal 24 hours. (Unlike above, where the
6742        // duration includes a 23 hour day, and so an additional hour has to be
6743        // added to the span to account for that.)
6744        let span = -1.month().hours(24);
6745        let relative = date(2024, 6, 11)
6746            .at(2, 0, 0, 0)
6747            .in_tz("America/New_York")
6748            .unwrap();
6749        let options =
6750            SpanRound::new().smallest(Unit::Millisecond).relative(&relative);
6751        let rounded = span.round(options).unwrap();
6752        span_eq!(rounded, -1.month().days(1));
6753    }
6754
6755    #[test]
6756    fn test_round_relative_zoned_time() {
6757        if crate::tz::db().is_definitively_empty() {
6758            return;
6759        }
6760
6761        let span = 2756.hours();
6762        let relative =
6763            date(2020, 1, 1).at(0, 0, 0, 0).in_tz("America/New_York").unwrap();
6764        let options = SpanRound::new().largest(Unit::Year).relative(&relative);
6765        let rounded = span.round(options).unwrap();
6766        span_eq!(rounded, 3.months().days(23).hours(21));
6767
6768        let span = 2756.hours();
6769        let relative =
6770            date(2020, 9, 1).at(0, 0, 0, 0).in_tz("America/New_York").unwrap();
6771        let options = SpanRound::new().largest(Unit::Year).relative(&relative);
6772        let rounded = span.round(options).unwrap();
6773        span_eq!(rounded, 3.months().days(23).hours(19));
6774
6775        let span = 3.hours();
6776        let relative =
6777            date(2020, 3, 8).at(0, 0, 0, 0).in_tz("America/New_York").unwrap();
6778        let options = SpanRound::new().largest(Unit::Year).relative(&relative);
6779        let rounded = span.round(options).unwrap();
6780        span_eq!(rounded, 3.hours());
6781    }
6782
6783    #[test]
6784    fn test_round_relative_day_time() {
6785        let span = 2756.hours();
6786        let options =
6787            SpanRound::new().largest(Unit::Year).relative(date(2020, 1, 1));
6788        let rounded = span.round(options).unwrap();
6789        span_eq!(rounded, 3.months().days(23).hours(20));
6790
6791        let span = 2756.hours();
6792        let options =
6793            SpanRound::new().largest(Unit::Year).relative(date(2020, 9, 1));
6794        let rounded = span.round(options).unwrap();
6795        span_eq!(rounded, 3.months().days(23).hours(20));
6796
6797        let span = 190.days();
6798        let options =
6799            SpanRound::new().largest(Unit::Year).relative(date(2020, 1, 1));
6800        let rounded = span.round(options).unwrap();
6801        span_eq!(rounded, 6.months().days(8));
6802
6803        let span = 30
6804            .days()
6805            .hours(23)
6806            .minutes(59)
6807            .seconds(59)
6808            .milliseconds(999)
6809            .microseconds(999)
6810            .nanoseconds(999);
6811        let options = SpanRound::new()
6812            .smallest(Unit::Microsecond)
6813            .largest(Unit::Year)
6814            .relative(date(2024, 5, 1));
6815        let rounded = span.round(options).unwrap();
6816        span_eq!(rounded, 1.month());
6817
6818        let span = 364
6819            .days()
6820            .hours(23)
6821            .minutes(59)
6822            .seconds(59)
6823            .milliseconds(999)
6824            .microseconds(999)
6825            .nanoseconds(999);
6826        let options = SpanRound::new()
6827            .smallest(Unit::Microsecond)
6828            .largest(Unit::Year)
6829            .relative(date(2023, 1, 1));
6830        let rounded = span.round(options).unwrap();
6831        span_eq!(rounded, 1.year());
6832
6833        let span = 365
6834            .days()
6835            .hours(23)
6836            .minutes(59)
6837            .seconds(59)
6838            .milliseconds(999)
6839            .microseconds(999)
6840            .nanoseconds(999);
6841        let options = SpanRound::new()
6842            .smallest(Unit::Microsecond)
6843            .largest(Unit::Year)
6844            .relative(date(2023, 1, 1));
6845        let rounded = span.round(options).unwrap();
6846        span_eq!(rounded, 1.year().days(1));
6847
6848        let span = 365
6849            .days()
6850            .hours(23)
6851            .minutes(59)
6852            .seconds(59)
6853            .milliseconds(999)
6854            .microseconds(999)
6855            .nanoseconds(999);
6856        let options = SpanRound::new()
6857            .smallest(Unit::Microsecond)
6858            .largest(Unit::Year)
6859            .relative(date(2024, 1, 1));
6860        let rounded = span.round(options).unwrap();
6861        span_eq!(rounded, 1.year());
6862
6863        let span = 3.hours();
6864        let options =
6865            SpanRound::new().largest(Unit::Year).relative(date(2020, 3, 8));
6866        let rounded = span.round(options).unwrap();
6867        span_eq!(rounded, 3.hours());
6868    }
6869
6870    #[test]
6871    fn span_sign() {
6872        assert_eq!(Span::new().get_sign(), b::Sign::Zero);
6873        assert_eq!(Span::new().days(1).get_sign(), b::Sign::Positive);
6874        assert_eq!(Span::new().days(-1).get_sign(), b::Sign::Negative);
6875        assert_eq!(Span::new().days(1).days(0).get_sign(), b::Sign::Zero);
6876        assert_eq!(Span::new().days(-1).days(0).get_sign(), b::Sign::Zero);
6877        assert_eq!(
6878            Span::new().years(1).days(1).days(0).get_sign(),
6879            b::Sign::Positive,
6880        );
6881        assert_eq!(
6882            Span::new().years(-1).days(-1).days(0).get_sign(),
6883            b::Sign::Negative,
6884        );
6885    }
6886
6887    #[test]
6888    fn span_size() {
6889        #[cfg(target_pointer_width = "64")]
6890        {
6891            #[cfg(debug_assertions)]
6892            {
6893                assert_eq!(core::mem::align_of::<Span>(), 8);
6894                assert_eq!(core::mem::size_of::<Span>(), 64);
6895            }
6896            #[cfg(not(debug_assertions))]
6897            {
6898                assert_eq!(core::mem::align_of::<Span>(), 8);
6899                assert_eq!(core::mem::size_of::<Span>(), 64);
6900            }
6901        }
6902    }
6903
6904    quickcheck::quickcheck! {
6905        fn prop_roundtrip_span_nanoseconds(span: Span) -> quickcheck::TestResult {
6906            let largest = span.largest_unit();
6907            if largest > Unit::Day {
6908                return quickcheck::TestResult::discard();
6909            }
6910            let dur = span.to_invariant_duration();
6911            let got = Span::from_invariant_duration(largest, dur).unwrap();
6912            quickcheck::TestResult::from_bool(dur == got.to_invariant_duration())
6913        }
6914    }
6915
6916    /// # `serde` deserializer compatibility test
6917    ///
6918    /// Serde YAML used to be unable to deserialize `jiff` types,
6919    /// as deserializing from bytes is not supported by the deserializer.
6920    ///
6921    /// - <https://github.com/BurntSushi/jiff/issues/138>
6922    /// - <https://github.com/BurntSushi/jiff/discussions/148>
6923    #[test]
6924    fn span_deserialize_yaml() {
6925        let expected = Span::new()
6926            .years(1)
6927            .months(2)
6928            .weeks(3)
6929            .days(4)
6930            .hours(5)
6931            .minutes(6)
6932            .seconds(7);
6933
6934        let deserialized: Span =
6935            serde_yaml::from_str("P1y2m3w4dT5h6m7s").unwrap();
6936
6937        span_eq!(deserialized, expected);
6938
6939        let deserialized: Span =
6940            serde_yaml::from_slice("P1y2m3w4dT5h6m7s".as_bytes()).unwrap();
6941
6942        span_eq!(deserialized, expected);
6943
6944        let cursor = Cursor::new(b"P1y2m3w4dT5h6m7s");
6945        let deserialized: Span = serde_yaml::from_reader(cursor).unwrap();
6946
6947        span_eq!(deserialized, expected);
6948    }
6949
6950    #[test]
6951    fn display() {
6952        let span = Span::new()
6953            .years(1)
6954            .months(2)
6955            .weeks(3)
6956            .days(4)
6957            .hours(5)
6958            .minutes(6)
6959            .seconds(7)
6960            .milliseconds(8)
6961            .microseconds(9)
6962            .nanoseconds(10);
6963        insta::assert_snapshot!(
6964            span,
6965            @"P1Y2M3W4DT5H6M7.00800901S",
6966        );
6967        insta::assert_snapshot!(
6968            alloc::format!("{span:#}"),
6969            @"1y 2mo 3w 4d 5h 6m 7s 8ms 9µs 10ns",
6970        );
6971    }
6972
6973    /// This test ensures that we can parse `humantime` formatted durations.
6974    #[test]
6975    fn humantime_compatibility_parse() {
6976        let dur = std::time::Duration::new(60 * 60 * 24 * 411, 123_456_789);
6977        let formatted = humantime::format_duration(dur).to_string();
6978        assert_eq!(
6979            formatted,
6980            "1year 1month 15days 7h 26m 24s 123ms 456us 789ns"
6981        );
6982        let expected = 1
6983            .year()
6984            .months(1)
6985            .days(15)
6986            .hours(7)
6987            .minutes(26)
6988            .seconds(24)
6989            .milliseconds(123)
6990            .microseconds(456)
6991            .nanoseconds(789);
6992        span_eq!(formatted.parse::<Span>().unwrap(), expected);
6993    }
6994
6995    /// This test ensures that we can print a `Span` that `humantime` can
6996    /// parse.
6997    ///
6998    /// Note that this isn't the default since `humantime`'s parser is
6999    /// pretty limited. e.g., It doesn't support things like `nsecs`
7000    /// despite supporting `secs`. And other reasons. See the docs on
7001    /// `Designator::HumanTime` for why we sadly provide a custom variant for
7002    /// it.
7003    #[test]
7004    fn humantime_compatibility_print() {
7005        static PRINTER: friendly::SpanPrinter = friendly::SpanPrinter::new()
7006            .designator(friendly::Designator::HumanTime);
7007
7008        let span = 1
7009            .year()
7010            .months(1)
7011            .days(15)
7012            .hours(7)
7013            .minutes(26)
7014            .seconds(24)
7015            .milliseconds(123)
7016            .microseconds(456)
7017            .nanoseconds(789);
7018        let formatted = PRINTER.span_to_string(&span);
7019        assert_eq!(formatted, "1y 1month 15d 7h 26m 24s 123ms 456us 789ns");
7020
7021        let dur = humantime::parse_duration(&formatted).unwrap();
7022        let expected =
7023            std::time::Duration::new(60 * 60 * 24 * 411, 123_456_789);
7024        assert_eq!(dur, expected);
7025    }
7026
7027    #[test]
7028    fn from_str() {
7029        let p = |s: &str| -> Result<Span, Error> { s.parse() };
7030
7031        insta::assert_snapshot!(
7032            p("1 day").unwrap(),
7033            @"P1D",
7034        );
7035        insta::assert_snapshot!(
7036            p("+1 day").unwrap(),
7037            @"P1D",
7038        );
7039        insta::assert_snapshot!(
7040            p("-1 day").unwrap(),
7041            @"-P1D",
7042        );
7043        insta::assert_snapshot!(
7044            p("P1d").unwrap(),
7045            @"P1D",
7046        );
7047        insta::assert_snapshot!(
7048            p("+P1d").unwrap(),
7049            @"P1D",
7050        );
7051        insta::assert_snapshot!(
7052            p("-P1d").unwrap(),
7053            @"-P1D",
7054        );
7055
7056        insta::assert_snapshot!(
7057            p("").unwrap_err(),
7058            @r#"an empty string is not a valid duration in either the ISO 8601 format or Jiff's "friendly" format"#,
7059        );
7060        insta::assert_snapshot!(
7061            p("+").unwrap_err(),
7062            @r#"found nothing after sign `+`, which is not a valid duration in either the ISO 8601 format or Jiff's "friendly" format"#,
7063        );
7064        insta::assert_snapshot!(
7065            p("-").unwrap_err(),
7066            @r#"found nothing after sign `-`, which is not a valid duration in either the ISO 8601 format or Jiff's "friendly" format"#,
7067        );
7068    }
7069
7070    #[test]
7071    fn serde_deserialize() {
7072        let p = |s: &str| -> Result<Span, serde_json::Error> {
7073            serde_json::from_str(&alloc::format!("\"{s}\""))
7074        };
7075
7076        insta::assert_snapshot!(
7077            p("1 day").unwrap(),
7078            @"P1D",
7079        );
7080        insta::assert_snapshot!(
7081            p("+1 day").unwrap(),
7082            @"P1D",
7083        );
7084        insta::assert_snapshot!(
7085            p("-1 day").unwrap(),
7086            @"-P1D",
7087        );
7088        insta::assert_snapshot!(
7089            p("P1d").unwrap(),
7090            @"P1D",
7091        );
7092        insta::assert_snapshot!(
7093            p("+P1d").unwrap(),
7094            @"P1D",
7095        );
7096        insta::assert_snapshot!(
7097            p("-P1d").unwrap(),
7098            @"-P1D",
7099        );
7100
7101        insta::assert_snapshot!(
7102            p("").unwrap_err(),
7103            @r#"an empty string is not a valid duration in either the ISO 8601 format or Jiff's "friendly" format at line 1 column 2"#,
7104        );
7105        insta::assert_snapshot!(
7106            p("+").unwrap_err(),
7107            @r#"found nothing after sign `+`, which is not a valid duration in either the ISO 8601 format or Jiff's "friendly" format at line 1 column 3"#,
7108        );
7109        insta::assert_snapshot!(
7110            p("-").unwrap_err(),
7111            @r#"found nothing after sign `-`, which is not a valid duration in either the ISO 8601 format or Jiff's "friendly" format at line 1 column 3"#,
7112        );
7113    }
7114
7115    // This ensures that adding maximum invariant durations doesn't overflow.
7116    #[test]
7117    fn maximum_invariant_duration() {
7118        let span = Span::new()
7119            .weeks(b::SpanWeeks::MAX)
7120            .days(b::SpanDays::MAX)
7121            .hours(b::SpanHours::MAX)
7122            .minutes(b::SpanMinutes::MAX)
7123            .seconds(b::SpanSeconds::MAX)
7124            .milliseconds(b::SpanMilliseconds::MAX)
7125            .microseconds(b::SpanMicroseconds::MAX)
7126            .nanoseconds(b::SpanNanoseconds::MAX);
7127
7128        let dur = span.to_invariant_duration();
7129        assert_eq!(dur.as_secs(), 4_426_974_863_236);
7130        assert_eq!(
7131            dur,
7132            // 1229715239h 47m 16s 854ms 775µs 807ns
7133            SignedDuration::new(
7134                1_229_715_239 * 60 * 60 + 47 * 60 + 16,
7135                854_775_807
7136            ),
7137        );
7138
7139        let sum = dur + dur;
7140        assert_eq!(sum.as_secs(), 8_853_949_726_473);
7141        assert_eq!(
7142            sum,
7143            // 2459430479h 34m 33s 709ms 551µs 614ns
7144            SignedDuration::new(
7145                2_459_430_479 * 60 * 60 + 34 * 60 + 33,
7146                709_551_614,
7147            ),
7148        );
7149    }
7150
7151    // This ensures that adding minimum invariant durations doesn't overflow.
7152    #[test]
7153    fn minimum_invariant_duration() {
7154        let span = Span::new()
7155            .weeks(b::SpanWeeks::MIN)
7156            .days(b::SpanDays::MIN)
7157            .hours(b::SpanHours::MIN)
7158            .minutes(b::SpanMinutes::MIN)
7159            .seconds(b::SpanSeconds::MIN)
7160            .milliseconds(b::SpanMilliseconds::MIN)
7161            .microseconds(b::SpanMicroseconds::MIN)
7162            .nanoseconds(b::SpanNanoseconds::MIN);
7163
7164        let dur = span.to_invariant_duration();
7165        assert_eq!(dur.as_secs(), -4_426_974_863_236);
7166        assert_eq!(
7167            dur,
7168            // -1229715239h 47m 16s 854ms 775µs 807ns
7169            -SignedDuration::new(
7170                1_229_715_239 * 60 * 60 + 47 * 60 + 16,
7171                854_775_807
7172            ),
7173        );
7174
7175        let sum = dur + dur;
7176        assert_eq!(sum.as_secs(), -8_853_949_726_473);
7177        assert_eq!(
7178            sum,
7179            // -2459430479h 34m 33s 709ms 551µs 614ns
7180            -SignedDuration::new(
7181                2_459_430_479 * 60 * 60 + 34 * 60 + 33,
7182                709_551_614,
7183            ),
7184        );
7185    }
7186}