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