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))
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))
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))
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))
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() > 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() < 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 == 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 != 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 != 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 != 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 != 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 != 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 != 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 != 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 != 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 != 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 != 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(|| {
2401 err!(
2402 "could not compute normalized relative span \
2403 from datetime {relative} and span {self}",
2404 relative = relative.kind,
2405 )
2406 })?;
2407 debug_assert!(relspan.span.largest_unit() <= Unit::Second);
2408 Ok(relspan.span.to_duration_invariant())
2409 }
2410
2411 /// Converts an entirely invariant span to a `SignedDuration`.
2412 ///
2413 /// Callers must ensure that this span has no units greater than weeks.
2414 /// If it does have non-zero units of days or weeks, then every day is
2415 /// considered 24 hours and every week 7 days. Generally speaking, callers
2416 /// should also ensure that if this span does have non-zero day/week units,
2417 /// then callers have either provided a civil relative date or the special
2418 /// `SpanRelativeTo::days_are_24_hours()` marker.
2419 #[inline]
2420 pub(crate) fn to_duration_invariant(&self) -> SignedDuration {
2421 // This guarantees, at compile time, that a maximal invariant Span
2422 // (that is, all units are days or lower and all units are set to their
2423 // maximum values) will still balance out to a number of seconds that
2424 // fits into a `i64`. This in turn implies that a `SignedDuration` can
2425 // represent all possible invariant positive spans.
2426 const _FITS_IN_U64: () = {
2427 debug_assert!(
2428 i64::MAX as i128
2429 > ((t::SpanWeeks::MAX
2430 * t::SECONDS_PER_CIVIL_WEEK.bound())
2431 + (t::SpanDays::MAX
2432 * t::SECONDS_PER_CIVIL_DAY.bound())
2433 + (t::SpanHours::MAX * t::SECONDS_PER_HOUR.bound())
2434 + (t::SpanMinutes::MAX
2435 * t::SECONDS_PER_MINUTE.bound())
2436 + t::SpanSeconds::MAX
2437 + (t::SpanMilliseconds::MAX
2438 / t::MILLIS_PER_SECOND.bound())
2439 + (t::SpanMicroseconds::MAX
2440 / t::MICROS_PER_SECOND.bound())
2441 + (t::SpanNanoseconds::MAX
2442 / t::NANOS_PER_SECOND.bound())),
2443 );
2444 ()
2445 };
2446
2447 let nanos = self.to_invariant_nanoseconds();
2448 debug_assert!(
2449 self.largest_unit() <= Unit::Week,
2450 "units must be weeks or lower"
2451 );
2452
2453 let seconds = nanos / t::NANOS_PER_SECOND;
2454 let seconds = i64::from(seconds);
2455 let subsec_nanos = nanos % t::NANOS_PER_SECOND;
2456 // OK because % 1_000_000_000 above guarantees that the result fits
2457 // in a i32.
2458 let subsec_nanos = i32::try_from(subsec_nanos).unwrap();
2459
2460 // SignedDuration::new can panic if |subsec_nanos| >= 1_000_000_000
2461 // and seconds == {i64::MIN,i64::MAX}. But this can never happen
2462 // because we guaranteed by construction above that |subsec_nanos| <
2463 // 1_000_000_000.
2464 SignedDuration::new(seconds, subsec_nanos)
2465 }
2466}
2467
2468/// Crate internal APIs that operate on ranged integer types.
2469impl Span {
2470 #[inline]
2471 pub(crate) fn years_ranged(self, years: impl RInto<t::SpanYears>) -> Span {
2472 let years = years.rinto();
2473 let mut span = Span { years: years.abs(), ..self };
2474 span.sign = self.resign(years, &span);
2475 span.units = span.units.set(Unit::Year, years == 0);
2476 span
2477 }
2478
2479 #[inline]
2480 pub(crate) fn months_ranged(
2481 self,
2482 months: impl RInto<t::SpanMonths>,
2483 ) -> Span {
2484 let months = months.rinto();
2485 let mut span = Span { months: months.abs(), ..self };
2486 span.sign = self.resign(months, &span);
2487 span.units = span.units.set(Unit::Month, months == 0);
2488 span
2489 }
2490
2491 #[inline]
2492 pub(crate) fn weeks_ranged(self, weeks: impl RInto<t::SpanWeeks>) -> Span {
2493 let weeks = weeks.rinto();
2494 let mut span = Span { weeks: weeks.abs(), ..self };
2495 span.sign = self.resign(weeks, &span);
2496 span.units = span.units.set(Unit::Week, weeks == 0);
2497 span
2498 }
2499
2500 #[inline]
2501 pub(crate) fn days_ranged(self, days: impl RInto<t::SpanDays>) -> Span {
2502 let days = days.rinto();
2503 let mut span = Span { days: days.abs(), ..self };
2504 span.sign = self.resign(days, &span);
2505 span.units = span.units.set(Unit::Day, days == 0);
2506 span
2507 }
2508
2509 #[inline]
2510 pub(crate) fn hours_ranged(self, hours: impl RInto<t::SpanHours>) -> Span {
2511 let hours = hours.rinto();
2512 let mut span = Span { hours: hours.abs(), ..self };
2513 span.sign = self.resign(hours, &span);
2514 span.units = span.units.set(Unit::Hour, hours == 0);
2515 span
2516 }
2517
2518 #[inline]
2519 pub(crate) fn minutes_ranged(
2520 self,
2521 minutes: impl RInto<t::SpanMinutes>,
2522 ) -> Span {
2523 let minutes = minutes.rinto();
2524 let mut span = Span { minutes: minutes.abs(), ..self };
2525 span.sign = self.resign(minutes, &span);
2526 span.units = span.units.set(Unit::Minute, minutes == 0);
2527 span
2528 }
2529
2530 #[inline]
2531 pub(crate) fn seconds_ranged(
2532 self,
2533 seconds: impl RInto<t::SpanSeconds>,
2534 ) -> Span {
2535 let seconds = seconds.rinto();
2536 let mut span = Span { seconds: seconds.abs(), ..self };
2537 span.sign = self.resign(seconds, &span);
2538 span.units = span.units.set(Unit::Second, seconds == 0);
2539 span
2540 }
2541
2542 #[inline]
2543 fn milliseconds_ranged(
2544 self,
2545 milliseconds: impl RInto<t::SpanMilliseconds>,
2546 ) -> Span {
2547 let milliseconds = milliseconds.rinto();
2548 let mut span = Span { milliseconds: milliseconds.abs(), ..self };
2549 span.sign = self.resign(milliseconds, &span);
2550 span.units = span.units.set(Unit::Millisecond, milliseconds == 0);
2551 span
2552 }
2553
2554 #[inline]
2555 fn microseconds_ranged(
2556 self,
2557 microseconds: impl RInto<t::SpanMicroseconds>,
2558 ) -> Span {
2559 let microseconds = microseconds.rinto();
2560 let mut span = Span { microseconds: microseconds.abs(), ..self };
2561 span.sign = self.resign(microseconds, &span);
2562 span.units = span.units.set(Unit::Microsecond, microseconds == 0);
2563 span
2564 }
2565
2566 #[inline]
2567 pub(crate) fn nanoseconds_ranged(
2568 self,
2569 nanoseconds: impl RInto<t::SpanNanoseconds>,
2570 ) -> Span {
2571 let nanoseconds = nanoseconds.rinto();
2572 let mut span = Span { nanoseconds: nanoseconds.abs(), ..self };
2573 span.sign = self.resign(nanoseconds, &span);
2574 span.units = span.units.set(Unit::Nanosecond, nanoseconds == 0);
2575 span
2576 }
2577
2578 #[inline]
2579 fn try_years_ranged(
2580 self,
2581 years: impl TryRInto<t::SpanYears>,
2582 ) -> Result<Span, Error> {
2583 let years = years.try_rinto("years")?;
2584 Ok(self.years_ranged(years))
2585 }
2586
2587 #[inline]
2588 fn try_months_ranged(
2589 self,
2590 months: impl TryRInto<t::SpanMonths>,
2591 ) -> Result<Span, Error> {
2592 let months = months.try_rinto("months")?;
2593 Ok(self.months_ranged(months))
2594 }
2595
2596 #[inline]
2597 fn try_weeks_ranged(
2598 self,
2599 weeks: impl TryRInto<t::SpanWeeks>,
2600 ) -> Result<Span, Error> {
2601 let weeks = weeks.try_rinto("weeks")?;
2602 Ok(self.weeks_ranged(weeks))
2603 }
2604
2605 #[inline]
2606 fn try_days_ranged(
2607 self,
2608 days: impl TryRInto<t::SpanDays>,
2609 ) -> Result<Span, Error> {
2610 let days = days.try_rinto("days")?;
2611 Ok(self.days_ranged(days))
2612 }
2613
2614 #[inline]
2615 pub(crate) fn try_hours_ranged(
2616 self,
2617 hours: impl TryRInto<t::SpanHours>,
2618 ) -> Result<Span, Error> {
2619 let hours = hours.try_rinto("hours")?;
2620 Ok(self.hours_ranged(hours))
2621 }
2622
2623 #[inline]
2624 pub(crate) fn try_minutes_ranged(
2625 self,
2626 minutes: impl TryRInto<t::SpanMinutes>,
2627 ) -> Result<Span, Error> {
2628 let minutes = minutes.try_rinto("minutes")?;
2629 Ok(self.minutes_ranged(minutes))
2630 }
2631
2632 #[inline]
2633 pub(crate) fn try_seconds_ranged(
2634 self,
2635 seconds: impl TryRInto<t::SpanSeconds>,
2636 ) -> Result<Span, Error> {
2637 let seconds = seconds.try_rinto("seconds")?;
2638 Ok(self.seconds_ranged(seconds))
2639 }
2640
2641 #[inline]
2642 pub(crate) fn try_milliseconds_ranged(
2643 self,
2644 milliseconds: impl TryRInto<t::SpanMilliseconds>,
2645 ) -> Result<Span, Error> {
2646 let milliseconds = milliseconds.try_rinto("milliseconds")?;
2647 Ok(self.milliseconds_ranged(milliseconds))
2648 }
2649
2650 #[inline]
2651 pub(crate) fn try_microseconds_ranged(
2652 self,
2653 microseconds: impl TryRInto<t::SpanMicroseconds>,
2654 ) -> Result<Span, Error> {
2655 let microseconds = microseconds.try_rinto("microseconds")?;
2656 Ok(self.microseconds_ranged(microseconds))
2657 }
2658
2659 #[inline]
2660 pub(crate) fn try_nanoseconds_ranged(
2661 self,
2662 nanoseconds: impl TryRInto<t::SpanNanoseconds>,
2663 ) -> Result<Span, Error> {
2664 let nanoseconds = nanoseconds.try_rinto("nanoseconds")?;
2665 Ok(self.nanoseconds_ranged(nanoseconds))
2666 }
2667
2668 #[inline]
2669 pub(crate) fn try_units_ranged(
2670 self,
2671 unit: Unit,
2672 value: impl RInto<NoUnits>,
2673 ) -> Result<Span, Error> {
2674 let value = value.rinto();
2675 match unit {
2676 Unit::Year => self.try_years_ranged(value),
2677 Unit::Month => self.try_months_ranged(value),
2678 Unit::Week => self.try_weeks_ranged(value),
2679 Unit::Day => self.try_days_ranged(value),
2680 Unit::Hour => self.try_hours_ranged(value),
2681 Unit::Minute => self.try_minutes_ranged(value),
2682 Unit::Second => self.try_seconds_ranged(value),
2683 Unit::Millisecond => self.try_milliseconds_ranged(value),
2684 Unit::Microsecond => self.try_microseconds_ranged(value),
2685 Unit::Nanosecond => self.try_nanoseconds_ranged(value),
2686 }
2687 }
2688
2689 #[inline]
2690 pub(crate) fn get_years_ranged(&self) -> t::SpanYears {
2691 self.years * self.sign
2692 }
2693
2694 #[inline]
2695 pub(crate) fn get_months_ranged(&self) -> t::SpanMonths {
2696 self.months * self.sign
2697 }
2698
2699 #[inline]
2700 pub(crate) fn get_weeks_ranged(&self) -> t::SpanWeeks {
2701 self.weeks * self.sign
2702 }
2703
2704 #[inline]
2705 pub(crate) fn get_days_ranged(&self) -> t::SpanDays {
2706 self.days * self.sign
2707 }
2708
2709 #[inline]
2710 pub(crate) fn get_hours_ranged(&self) -> t::SpanHours {
2711 self.hours * self.sign
2712 }
2713
2714 #[inline]
2715 pub(crate) fn get_minutes_ranged(&self) -> t::SpanMinutes {
2716 self.minutes * self.sign
2717 }
2718
2719 #[inline]
2720 pub(crate) fn get_seconds_ranged(&self) -> t::SpanSeconds {
2721 self.seconds * self.sign
2722 }
2723
2724 #[inline]
2725 pub(crate) fn get_milliseconds_ranged(&self) -> t::SpanMilliseconds {
2726 self.milliseconds * self.sign
2727 }
2728
2729 #[inline]
2730 pub(crate) fn get_microseconds_ranged(&self) -> t::SpanMicroseconds {
2731 self.microseconds * self.sign
2732 }
2733
2734 #[inline]
2735 pub(crate) fn get_nanoseconds_ranged(&self) -> t::SpanNanoseconds {
2736 self.nanoseconds * self.sign
2737 }
2738
2739 #[inline]
2740 fn get_sign_ranged(&self) -> ri8<-1, 1> {
2741 self.sign
2742 }
2743
2744 #[inline]
2745 fn get_units_ranged(&self, unit: Unit) -> NoUnits {
2746 match unit {
2747 Unit::Year => self.get_years_ranged().rinto(),
2748 Unit::Month => self.get_months_ranged().rinto(),
2749 Unit::Week => self.get_weeks_ranged().rinto(),
2750 Unit::Day => self.get_days_ranged().rinto(),
2751 Unit::Hour => self.get_hours_ranged().rinto(),
2752 Unit::Minute => self.get_minutes_ranged().rinto(),
2753 Unit::Second => self.get_seconds_ranged().rinto(),
2754 Unit::Millisecond => self.get_milliseconds_ranged().rinto(),
2755 Unit::Microsecond => self.get_microseconds_ranged().rinto(),
2756 Unit::Nanosecond => self.get_nanoseconds_ranged().rinto(),
2757 }
2758 }
2759}
2760
2761/// Crate internal helper routines.
2762impl Span {
2763 /// Converts the given number of nanoseconds to a `Span` whose units do not
2764 /// exceed `largest`.
2765 ///
2766 /// Note that `largest` is capped at `Unit::Week`. Note though that if
2767 /// any unit greater than `Unit::Week` is given, then it is treated as
2768 /// `Unit::Day`. The only way to get weeks in the `Span` returned is to
2769 /// specifically request `Unit::Week`.
2770 ///
2771 /// And also note that days in this context are civil days. That is, they
2772 /// are always 24 hours long. Callers needing to deal with variable length
2773 /// days should do so outside of this routine and should not provide a
2774 /// `largest` unit bigger than `Unit::Hour`.
2775 pub(crate) fn from_invariant_nanoseconds(
2776 largest: Unit,
2777 nanos: impl RInto<NoUnits128>,
2778 ) -> Result<Span, Error> {
2779 let nanos = nanos.rinto();
2780 let mut span = Span::new();
2781 match largest {
2782 Unit::Week => {
2783 let micros = nanos.div_ceil(t::NANOS_PER_MICRO);
2784 span = span.try_nanoseconds_ranged(
2785 nanos.rem_ceil(t::NANOS_PER_MICRO),
2786 )?;
2787 let millis = micros.div_ceil(t::MICROS_PER_MILLI);
2788 span = span.try_microseconds_ranged(
2789 micros.rem_ceil(t::MICROS_PER_MILLI),
2790 )?;
2791 let secs = millis.div_ceil(t::MILLIS_PER_SECOND);
2792 span = span.try_milliseconds_ranged(
2793 millis.rem_ceil(t::MILLIS_PER_SECOND),
2794 )?;
2795 let mins = secs.div_ceil(t::SECONDS_PER_MINUTE);
2796 span = span.try_seconds_ranged(
2797 secs.rem_ceil(t::SECONDS_PER_MINUTE),
2798 )?;
2799 let hours = mins.div_ceil(t::MINUTES_PER_HOUR);
2800 span = span
2801 .try_minutes_ranged(mins.rem_ceil(t::MINUTES_PER_HOUR))?;
2802 let days = hours.div_ceil(t::HOURS_PER_CIVIL_DAY);
2803 span = span.try_hours_ranged(
2804 hours.rem_ceil(t::HOURS_PER_CIVIL_DAY),
2805 )?;
2806 let weeks = days.div_ceil(t::DAYS_PER_CIVIL_WEEK);
2807 span = span
2808 .try_days_ranged(days.rem_ceil(t::DAYS_PER_CIVIL_WEEK))?;
2809 span = span.try_weeks_ranged(weeks)?;
2810 Ok(span)
2811 }
2812 Unit::Year | Unit::Month | Unit::Day => {
2813 // Unit::Year | Unit::Month | Unit::Week | Unit::Day => {
2814 let micros = nanos.div_ceil(t::NANOS_PER_MICRO);
2815 span = span.try_nanoseconds_ranged(
2816 nanos.rem_ceil(t::NANOS_PER_MICRO),
2817 )?;
2818 let millis = micros.div_ceil(t::MICROS_PER_MILLI);
2819 span = span.try_microseconds_ranged(
2820 micros.rem_ceil(t::MICROS_PER_MILLI),
2821 )?;
2822 let secs = millis.div_ceil(t::MILLIS_PER_SECOND);
2823 span = span.try_milliseconds_ranged(
2824 millis.rem_ceil(t::MILLIS_PER_SECOND),
2825 )?;
2826 let mins = secs.div_ceil(t::SECONDS_PER_MINUTE);
2827 span = span.try_seconds_ranged(
2828 secs.rem_ceil(t::SECONDS_PER_MINUTE),
2829 )?;
2830 let hours = mins.div_ceil(t::MINUTES_PER_HOUR);
2831 span = span
2832 .try_minutes_ranged(mins.rem_ceil(t::MINUTES_PER_HOUR))?;
2833 let days = hours.div_ceil(t::HOURS_PER_CIVIL_DAY);
2834 span = span.try_hours_ranged(
2835 hours.rem_ceil(t::HOURS_PER_CIVIL_DAY),
2836 )?;
2837 span = span.try_days_ranged(days)?;
2838 Ok(span)
2839 }
2840 Unit::Hour => {
2841 let micros = nanos.div_ceil(t::NANOS_PER_MICRO);
2842 span = span.try_nanoseconds_ranged(
2843 nanos.rem_ceil(t::NANOS_PER_MICRO),
2844 )?;
2845 let millis = micros.div_ceil(t::MICROS_PER_MILLI);
2846 span = span.try_microseconds_ranged(
2847 micros.rem_ceil(t::MICROS_PER_MILLI),
2848 )?;
2849 let secs = millis.div_ceil(t::MILLIS_PER_SECOND);
2850 span = span.try_milliseconds_ranged(
2851 millis.rem_ceil(t::MILLIS_PER_SECOND),
2852 )?;
2853 let mins = secs.div_ceil(t::SECONDS_PER_MINUTE);
2854 span = span.try_seconds_ranged(
2855 secs.rem_ceil(t::SECONDS_PER_MINUTE),
2856 )?;
2857 let hours = mins.div_ceil(t::MINUTES_PER_HOUR);
2858 span = span
2859 .try_minutes_ranged(mins.rem_ceil(t::MINUTES_PER_HOUR))?;
2860 span = span.try_hours_ranged(hours)?;
2861 Ok(span)
2862 }
2863 Unit::Minute => {
2864 let micros = nanos.div_ceil(t::NANOS_PER_MICRO);
2865 span = span.try_nanoseconds_ranged(
2866 nanos.rem_ceil(t::NANOS_PER_MICRO),
2867 )?;
2868 let millis = micros.div_ceil(t::MICROS_PER_MILLI);
2869 span = span.try_microseconds_ranged(
2870 micros.rem_ceil(t::MICROS_PER_MILLI),
2871 )?;
2872 let secs = millis.div_ceil(t::MILLIS_PER_SECOND);
2873 span = span.try_milliseconds_ranged(
2874 millis.rem_ceil(t::MILLIS_PER_SECOND),
2875 )?;
2876 let mins = secs.div_ceil(t::SECONDS_PER_MINUTE);
2877 span =
2878 span.try_seconds(secs.rem_ceil(t::SECONDS_PER_MINUTE))?;
2879 span = span.try_minutes_ranged(mins)?;
2880 Ok(span)
2881 }
2882 Unit::Second => {
2883 let micros = nanos.div_ceil(t::NANOS_PER_MICRO);
2884 span = span.try_nanoseconds_ranged(
2885 nanos.rem_ceil(t::NANOS_PER_MICRO),
2886 )?;
2887 let millis = micros.div_ceil(t::MICROS_PER_MILLI);
2888 span = span.try_microseconds_ranged(
2889 micros.rem_ceil(t::MICROS_PER_MILLI),
2890 )?;
2891 let secs = millis.div_ceil(t::MILLIS_PER_SECOND);
2892 span = span.try_milliseconds_ranged(
2893 millis.rem_ceil(t::MILLIS_PER_SECOND),
2894 )?;
2895 span = span.try_seconds_ranged(secs)?;
2896 Ok(span)
2897 }
2898 Unit::Millisecond => {
2899 let micros = nanos.div_ceil(t::NANOS_PER_MICRO);
2900 span = span.try_nanoseconds_ranged(
2901 nanos.rem_ceil(t::NANOS_PER_MICRO),
2902 )?;
2903 let millis = micros.div_ceil(t::MICROS_PER_MILLI);
2904 span = span.try_microseconds_ranged(
2905 micros.rem_ceil(t::MICROS_PER_MILLI),
2906 )?;
2907 span = span.try_milliseconds_ranged(millis)?;
2908 Ok(span)
2909 }
2910 Unit::Microsecond => {
2911 let micros = nanos.div_ceil(t::NANOS_PER_MICRO);
2912 span = span.try_nanoseconds_ranged(
2913 nanos.rem_ceil(t::NANOS_PER_MICRO),
2914 )?;
2915 span = span.try_microseconds_ranged(micros)?;
2916 Ok(span)
2917 }
2918 Unit::Nanosecond => {
2919 span = span.try_nanoseconds_ranged(nanos)?;
2920 Ok(span)
2921 }
2922 }
2923 }
2924
2925 /// Converts the non-variable units of this `Span` to a total number of
2926 /// nanoseconds.
2927 ///
2928 /// This includes days and weeks, even though they can be of irregular
2929 /// length during time zone transitions. If this applies, then callers
2930 /// should set the days and weeks to `0` before calling this routine.
2931 ///
2932 /// All units above weeks are always ignored.
2933 #[inline]
2934 pub(crate) fn to_invariant_nanoseconds(&self) -> NoUnits128 {
2935 let mut nanos = NoUnits128::rfrom(self.get_nanoseconds_ranged());
2936 nanos += NoUnits128::rfrom(self.get_microseconds_ranged())
2937 * t::NANOS_PER_MICRO;
2938 nanos += NoUnits128::rfrom(self.get_milliseconds_ranged())
2939 * t::NANOS_PER_MILLI;
2940 nanos +=
2941 NoUnits128::rfrom(self.get_seconds_ranged()) * t::NANOS_PER_SECOND;
2942 nanos +=
2943 NoUnits128::rfrom(self.get_minutes_ranged()) * t::NANOS_PER_MINUTE;
2944 nanos +=
2945 NoUnits128::rfrom(self.get_hours_ranged()) * t::NANOS_PER_HOUR;
2946 nanos +=
2947 NoUnits128::rfrom(self.get_days_ranged()) * t::NANOS_PER_CIVIL_DAY;
2948 nanos += NoUnits128::rfrom(self.get_weeks_ranged())
2949 * t::NANOS_PER_CIVIL_WEEK;
2950 nanos
2951 }
2952
2953 /// Converts the non-variable units of this `Span` to a total number of
2954 /// seconds if there is no fractional second component. Otherwise,
2955 /// `None` is returned.
2956 ///
2957 /// This is useful for short-circuiting in arithmetic operations when
2958 /// it's faster to only deal with seconds. And in particular, acknowledges
2959 /// that nanosecond precision durations are somewhat rare.
2960 ///
2961 /// This includes days and weeks, even though they can be of irregular
2962 /// length during time zone transitions. If this applies, then callers
2963 /// should set the days and weeks to `0` before calling this routine.
2964 ///
2965 /// All units above weeks are always ignored.
2966 #[inline]
2967 pub(crate) fn to_invariant_seconds(&self) -> Option<NoUnits> {
2968 if self.has_fractional_seconds() {
2969 return None;
2970 }
2971 let mut seconds = NoUnits::rfrom(self.get_seconds_ranged());
2972 seconds +=
2973 NoUnits::rfrom(self.get_minutes_ranged()) * t::SECONDS_PER_MINUTE;
2974 seconds +=
2975 NoUnits::rfrom(self.get_hours_ranged()) * t::SECONDS_PER_HOUR;
2976 seconds +=
2977 NoUnits::rfrom(self.get_days_ranged()) * t::SECONDS_PER_CIVIL_DAY;
2978 seconds += NoUnits::rfrom(self.get_weeks_ranged())
2979 * t::SECONDS_PER_CIVIL_WEEK;
2980 Some(seconds)
2981 }
2982
2983 /// Rebalances the invariant units (days or lower) on this span so that
2984 /// the largest possible non-zero unit is the one given.
2985 ///
2986 /// Units above day are ignored and dropped.
2987 ///
2988 /// If the given unit is greater than days, then it is treated as-if it
2989 /// were days.
2990 ///
2991 /// # Errors
2992 ///
2993 /// This can return an error in the case of lop-sided units. For example,
2994 /// if this span has maximal values for all units, then rebalancing is
2995 /// not possible because the number of days after balancing would exceed
2996 /// the limit.
2997 #[cfg(test)] // currently only used in zic parser?
2998 #[inline]
2999 pub(crate) fn rebalance(self, unit: Unit) -> Result<Span, Error> {
3000 Span::from_invariant_nanoseconds(unit, self.to_invariant_nanoseconds())
3001 }
3002
3003 /// Returns true if and only if this span has at least one non-zero
3004 /// fractional second unit.
3005 #[inline]
3006 pub(crate) fn has_fractional_seconds(&self) -> bool {
3007 self.milliseconds != 0
3008 || self.microseconds != 0
3009 || self.nanoseconds != 0
3010 }
3011
3012 /// Returns an equivalent span, but with all non-calendar (units below
3013 /// days) set to zero.
3014 #[inline(always)]
3015 pub(crate) fn only_calendar(self) -> Span {
3016 let mut span = self;
3017 span.hours = t::SpanHours::N::<0>();
3018 span.minutes = t::SpanMinutes::N::<0>();
3019 span.seconds = t::SpanSeconds::N::<0>();
3020 span.milliseconds = t::SpanMilliseconds::N::<0>();
3021 span.microseconds = t::SpanMicroseconds::N::<0>();
3022 span.nanoseconds = t::SpanNanoseconds::N::<0>();
3023 if span.sign != 0
3024 && span.years == 0
3025 && span.months == 0
3026 && span.weeks == 0
3027 && span.days == 0
3028 {
3029 span.sign = t::Sign::N::<0>();
3030 }
3031 span.units = span.units.only_calendar();
3032 span
3033 }
3034
3035 /// Returns an equivalent span, but with all calendar (units above
3036 /// hours) set to zero.
3037 #[inline(always)]
3038 pub(crate) fn only_time(self) -> Span {
3039 let mut span = self;
3040 span.years = t::SpanYears::N::<0>();
3041 span.months = t::SpanMonths::N::<0>();
3042 span.weeks = t::SpanWeeks::N::<0>();
3043 span.days = t::SpanDays::N::<0>();
3044 if span.sign != 0
3045 && span.hours == 0
3046 && span.minutes == 0
3047 && span.seconds == 0
3048 && span.milliseconds == 0
3049 && span.microseconds == 0
3050 && span.nanoseconds == 0
3051 {
3052 span.sign = t::Sign::N::<0>();
3053 }
3054 span.units = span.units.only_time();
3055 span
3056 }
3057
3058 /// Returns an equivalent span, but with all units greater than or equal to
3059 /// the one given set to zero.
3060 #[inline(always)]
3061 pub(crate) fn only_lower(self, unit: Unit) -> Span {
3062 let mut span = self;
3063 // Unit::Nanosecond is the minimum, so nothing can be smaller than it.
3064 if unit <= Unit::Microsecond {
3065 span = span.microseconds_ranged(C(0));
3066 }
3067 if unit <= Unit::Millisecond {
3068 span = span.milliseconds_ranged(C(0));
3069 }
3070 if unit <= Unit::Second {
3071 span = span.seconds_ranged(C(0));
3072 }
3073 if unit <= Unit::Minute {
3074 span = span.minutes_ranged(C(0));
3075 }
3076 if unit <= Unit::Hour {
3077 span = span.hours_ranged(C(0));
3078 }
3079 if unit <= Unit::Day {
3080 span = span.days_ranged(C(0));
3081 }
3082 if unit <= Unit::Week {
3083 span = span.weeks_ranged(C(0));
3084 }
3085 if unit <= Unit::Month {
3086 span = span.months_ranged(C(0));
3087 }
3088 if unit <= Unit::Year {
3089 span = span.years_ranged(C(0));
3090 }
3091 span
3092 }
3093
3094 /// Returns an equivalent span, but with all units less than the one given
3095 /// set to zero.
3096 #[inline(always)]
3097 pub(crate) fn without_lower(self, unit: Unit) -> Span {
3098 let mut span = self;
3099 if unit > Unit::Nanosecond {
3100 span = span.nanoseconds_ranged(C(0));
3101 }
3102 if unit > Unit::Microsecond {
3103 span = span.microseconds_ranged(C(0));
3104 }
3105 if unit > Unit::Millisecond {
3106 span = span.milliseconds_ranged(C(0));
3107 }
3108 if unit > Unit::Second {
3109 span = span.seconds_ranged(C(0));
3110 }
3111 if unit > Unit::Minute {
3112 span = span.minutes_ranged(C(0));
3113 }
3114 if unit > Unit::Hour {
3115 span = span.hours_ranged(C(0));
3116 }
3117 if unit > Unit::Day {
3118 span = span.days_ranged(C(0));
3119 }
3120 if unit > Unit::Week {
3121 span = span.weeks_ranged(C(0));
3122 }
3123 if unit > Unit::Month {
3124 span = span.months_ranged(C(0));
3125 }
3126 // Unit::Year is the max, so nothing can be bigger than it.
3127 span
3128 }
3129
3130 /// Returns an error corresponding to the smallest non-time non-zero unit.
3131 ///
3132 /// If all non-time units are zero, then this returns `None`.
3133 #[inline(always)]
3134 pub(crate) fn smallest_non_time_non_zero_unit_error(
3135 &self,
3136 ) -> Option<Error> {
3137 let non_time_unit = self.largest_calendar_unit()?;
3138 Some(err!(
3139 "operation can only be performed with units of hours \
3140 or smaller, but found non-zero {unit} units \
3141 (operations on `Timestamp`, `tz::Offset` and `civil::Time` \
3142 don't support calendar units in a `Span`)",
3143 unit = non_time_unit.singular(),
3144 ))
3145 }
3146
3147 /// Returns the largest non-zero calendar unit, or `None` if there are no
3148 /// non-zero calendar units.
3149 #[inline]
3150 pub(crate) fn largest_calendar_unit(&self) -> Option<Unit> {
3151 self.units().only_calendar().largest_unit()
3152 }
3153
3154 /// Returns the largest non-zero unit in this span.
3155 ///
3156 /// If all components of this span are zero, then `Unit::Nanosecond` is
3157 /// returned.
3158 #[inline]
3159 pub(crate) fn largest_unit(&self) -> Unit {
3160 self.units().largest_unit().unwrap_or(Unit::Nanosecond)
3161 }
3162
3163 /// Returns the set of units on this `Span`.
3164 #[inline]
3165 pub(crate) fn units(&self) -> UnitSet {
3166 self.units
3167 }
3168
3169 /// Returns a string containing the value of all non-zero fields.
3170 ///
3171 /// This is useful for debugging. Normally, this would be the "alternate"
3172 /// debug impl (perhaps), but that's what insta uses and I preferred having
3173 /// the friendly format used there since it is much more terse.
3174 #[cfg(feature = "alloc")]
3175 #[allow(dead_code)]
3176 pub(crate) fn debug(&self) -> alloc::string::String {
3177 use core::fmt::Write;
3178
3179 let mut buf = alloc::string::String::new();
3180 write!(buf, "Span {{ sign: {:?}, units: {:?}", self.sign, self.units)
3181 .unwrap();
3182 if self.years != 0 {
3183 write!(buf, ", years: {:?}", self.years).unwrap();
3184 }
3185 if self.months != 0 {
3186 write!(buf, ", months: {:?}", self.months).unwrap();
3187 }
3188 if self.weeks != 0 {
3189 write!(buf, ", weeks: {:?}", self.weeks).unwrap();
3190 }
3191 if self.days != 0 {
3192 write!(buf, ", days: {:?}", self.days).unwrap();
3193 }
3194 if self.hours != 0 {
3195 write!(buf, ", hours: {:?}", self.hours).unwrap();
3196 }
3197 if self.minutes != 0 {
3198 write!(buf, ", minutes: {:?}", self.minutes).unwrap();
3199 }
3200 if self.seconds != 0 {
3201 write!(buf, ", seconds: {:?}", self.seconds).unwrap();
3202 }
3203 if self.milliseconds != 0 {
3204 write!(buf, ", milliseconds: {:?}", self.milliseconds).unwrap();
3205 }
3206 if self.microseconds != 0 {
3207 write!(buf, ", microseconds: {:?}", self.microseconds).unwrap();
3208 }
3209 if self.nanoseconds != 0 {
3210 write!(buf, ", nanoseconds: {:?}", self.nanoseconds).unwrap();
3211 }
3212 write!(buf, " }}").unwrap();
3213 buf
3214 }
3215
3216 /// Given some new units to set on this span and the span updates with the
3217 /// new units, this determines the what the sign of `new` should be.
3218 #[inline]
3219 fn resign(&self, units: impl RInto<NoUnits>, new: &Span) -> Sign {
3220 let units = units.rinto();
3221 // Negative units anywhere always makes the entire span negative.
3222 if units < 0 {
3223 return Sign::N::<-1>();
3224 }
3225 let mut new_is_zero = new.sign == 0 && units == 0;
3226 // When `units == 0` and it was previously non-zero, then `new.sign`
3227 // won't be `0` and thus `new_is_zero` will be false when it should
3228 // be true. So in this case, we need to re-check all the units to set
3229 // the sign correctly.
3230 if units == 0 {
3231 new_is_zero = new.years == 0
3232 && new.months == 0
3233 && new.weeks == 0
3234 && new.days == 0
3235 && new.hours == 0
3236 && new.minutes == 0
3237 && new.seconds == 0
3238 && new.milliseconds == 0
3239 && new.microseconds == 0
3240 && new.nanoseconds == 0;
3241 }
3242 match (self.is_zero(), new_is_zero) {
3243 (_, true) => Sign::N::<0>(),
3244 (true, false) => units.signum().rinto(),
3245 // If the old and new span are both non-zero, and we know our new
3246 // units are not negative, then the sign remains unchanged.
3247 (false, false) => new.sign,
3248 }
3249 }
3250}
3251
3252impl Default for Span {
3253 #[inline]
3254 fn default() -> Span {
3255 Span {
3256 sign: ri8::N::<0>(),
3257 units: UnitSet::empty(),
3258 years: C(0).rinto(),
3259 months: C(0).rinto(),
3260 weeks: C(0).rinto(),
3261 days: C(0).rinto(),
3262 hours: C(0).rinto(),
3263 minutes: C(0).rinto(),
3264 seconds: C(0).rinto(),
3265 milliseconds: C(0).rinto(),
3266 microseconds: C(0).rinto(),
3267 nanoseconds: C(0).rinto(),
3268 }
3269 }
3270}
3271
3272impl core::fmt::Debug for Span {
3273 #[inline]
3274 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
3275 use crate::fmt::StdFmtWrite;
3276
3277 friendly::DEFAULT_SPAN_PRINTER
3278 .print_span(self, StdFmtWrite(f))
3279 .map_err(|_| core::fmt::Error)
3280 }
3281}
3282
3283impl core::fmt::Display for Span {
3284 #[inline]
3285 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
3286 use crate::fmt::StdFmtWrite;
3287
3288 if f.alternate() {
3289 friendly::DEFAULT_SPAN_PRINTER
3290 .print_span(self, StdFmtWrite(f))
3291 .map_err(|_| core::fmt::Error)
3292 } else {
3293 temporal::DEFAULT_SPAN_PRINTER
3294 .print_span(self, StdFmtWrite(f))
3295 .map_err(|_| core::fmt::Error)
3296 }
3297 }
3298}
3299
3300impl core::str::FromStr for Span {
3301 type Err = Error;
3302
3303 #[inline]
3304 fn from_str(string: &str) -> Result<Span, Error> {
3305 parse_iso_or_friendly(string.as_bytes())
3306 }
3307}
3308
3309impl core::ops::Neg for Span {
3310 type Output = Span;
3311
3312 #[inline]
3313 fn neg(self) -> Span {
3314 self.negate()
3315 }
3316}
3317
3318/// This multiplies each unit in a span by an integer.
3319///
3320/// This panics on overflow. For checked arithmetic, use [`Span::checked_mul`].
3321impl core::ops::Mul<i64> for Span {
3322 type Output = Span;
3323
3324 #[inline]
3325 fn mul(self, rhs: i64) -> Span {
3326 self.checked_mul(rhs)
3327 .expect("multiplying `Span` by a scalar overflowed")
3328 }
3329}
3330
3331/// This multiplies each unit in a span by an integer.
3332///
3333/// This panics on overflow. For checked arithmetic, use [`Span::checked_mul`].
3334impl core::ops::Mul<Span> for i64 {
3335 type Output = Span;
3336
3337 #[inline]
3338 fn mul(self, rhs: Span) -> Span {
3339 rhs.checked_mul(self)
3340 .expect("multiplying `Span` by a scalar overflowed")
3341 }
3342}
3343
3344/// Converts a `Span` to a [`std::time::Duration`].
3345///
3346/// Note that this assumes that days are always 24 hours long.
3347///
3348/// # Errors
3349///
3350/// This can fail for only two reasons:
3351///
3352/// * The span is negative. This is an error because a `std::time::Duration` is
3353/// unsigned.)
3354/// * The span has any non-zero units greater than hours. This is an error
3355/// because it's impossible to determine the length of, e.g., a month without
3356/// a reference date.
3357///
3358/// This can never result in overflow because a `Duration` can represent a
3359/// bigger span of time than `Span` when limited to units of hours or lower.
3360///
3361/// If you need to convert a `Span` to a `Duration` that has non-zero
3362/// units bigger than hours, then please use [`Span::to_duration`] with a
3363/// corresponding relative date.
3364///
3365/// # Example: maximal span
3366///
3367/// This example shows the maximum possible span using units of hours or
3368/// smaller, and the corresponding `Duration` value:
3369///
3370/// ```
3371/// use std::time::Duration;
3372///
3373/// use jiff::Span;
3374///
3375/// let sp = Span::new()
3376/// .hours(175_307_616)
3377/// .minutes(10_518_456_960i64)
3378/// .seconds(631_107_417_600i64)
3379/// .milliseconds(631_107_417_600_000i64)
3380/// .microseconds(631_107_417_600_000_000i64)
3381/// .nanoseconds(9_223_372_036_854_775_807i64);
3382/// let duration = Duration::try_from(sp)?;
3383/// assert_eq!(duration, Duration::new(3_164_760_460_036, 854_775_807));
3384///
3385/// # Ok::<(), Box<dyn std::error::Error>>(())
3386/// ```
3387///
3388/// # Example: converting a negative span
3389///
3390/// Since a `Span` is signed and a `Duration` is unsigned, converting
3391/// a negative `Span` to `Duration` will always fail. One can use
3392/// [`Span::signum`] to get the sign of the span and [`Span::abs`] to make the
3393/// span positive before converting it to a `Duration`:
3394///
3395/// ```
3396/// use std::time::Duration;
3397///
3398/// use jiff::{Span, ToSpan};
3399///
3400/// let span = -86_400.seconds().nanoseconds(1);
3401/// let (sign, duration) = (span.signum(), Duration::try_from(span.abs())?);
3402/// assert_eq!((sign, duration), (-1, Duration::new(86_400, 1)));
3403///
3404/// # Ok::<(), Box<dyn std::error::Error>>(())
3405/// ```
3406impl TryFrom<Span> for UnsignedDuration {
3407 type Error = Error;
3408
3409 #[inline]
3410 fn try_from(sp: Span) -> Result<UnsignedDuration, Error> {
3411 // This isn't needed, but improves error messages.
3412 if sp.is_negative() {
3413 return Err(err!(
3414 "cannot convert negative span {sp:?} \
3415 to unsigned std::time::Duration",
3416 ));
3417 }
3418 SignedDuration::try_from(sp).and_then(UnsignedDuration::try_from)
3419 }
3420}
3421
3422/// Converts a [`std::time::Duration`] to a `Span`.
3423///
3424/// The span returned from this conversion will only ever have non-zero units
3425/// of seconds or smaller.
3426///
3427/// # Errors
3428///
3429/// This only fails when the given `Duration` overflows the maximum number of
3430/// seconds representable by a `Span`.
3431///
3432/// # Example
3433///
3434/// This shows a basic conversion:
3435///
3436/// ```
3437/// use std::time::Duration;
3438///
3439/// use jiff::{Span, ToSpan};
3440///
3441/// let duration = Duration::new(86_400, 123_456_789);
3442/// let span = Span::try_from(duration)?;
3443/// // A duration-to-span conversion always results in a span with
3444/// // non-zero units no bigger than seconds.
3445/// assert_eq!(
3446/// span.fieldwise(),
3447/// 86_400.seconds().milliseconds(123).microseconds(456).nanoseconds(789),
3448/// );
3449///
3450/// # Ok::<(), Box<dyn std::error::Error>>(())
3451/// ```
3452///
3453/// # Example: rounding
3454///
3455/// This example shows how to convert a `Duration` to a `Span`, and then round
3456/// it up to bigger units given a relative date:
3457///
3458/// ```
3459/// use std::time::Duration;
3460///
3461/// use jiff::{civil::date, Span, SpanRound, ToSpan, Unit};
3462///
3463/// let duration = Duration::new(450 * 86_401, 0);
3464/// let span = Span::try_from(duration)?;
3465/// // We get back a simple span of just seconds:
3466/// assert_eq!(span.fieldwise(), Span::new().seconds(450 * 86_401));
3467/// // But we can balance it up to bigger units:
3468/// let options = SpanRound::new()
3469/// .largest(Unit::Year)
3470/// .relative(date(2024, 1, 1));
3471/// assert_eq!(
3472/// span.round(options)?,
3473/// 1.year().months(2).days(25).minutes(7).seconds(30).fieldwise(),
3474/// );
3475///
3476/// # Ok::<(), Box<dyn std::error::Error>>(())
3477/// ```
3478impl TryFrom<UnsignedDuration> for Span {
3479 type Error = Error;
3480
3481 #[inline]
3482 fn try_from(d: UnsignedDuration) -> Result<Span, Error> {
3483 let seconds = i64::try_from(d.as_secs()).map_err(|_| {
3484 err!("seconds from {d:?} overflows a 64-bit signed integer")
3485 })?;
3486 let nanoseconds = i64::from(d.subsec_nanos());
3487 let milliseconds = nanoseconds / t::NANOS_PER_MILLI.value();
3488 let microseconds = (nanoseconds % t::NANOS_PER_MILLI.value())
3489 / t::NANOS_PER_MICRO.value();
3490 let nanoseconds = nanoseconds % t::NANOS_PER_MICRO.value();
3491
3492 let span = Span::new().try_seconds(seconds).with_context(|| {
3493 err!("duration {d:?} overflows limits of a Jiff `Span`")
3494 })?;
3495 // These are all OK because `Duration::subsec_nanos` is guaranteed to
3496 // return less than 1_000_000_000 nanoseconds. And splitting that up
3497 // into millis, micros and nano components is guaranteed to fit into
3498 // the limits of a `Span`.
3499 Ok(span
3500 .milliseconds(milliseconds)
3501 .microseconds(microseconds)
3502 .nanoseconds(nanoseconds))
3503 }
3504}
3505
3506/// Converts a `Span` to a [`SignedDuration`].
3507///
3508/// Note that this assumes that days are always 24 hours long.
3509///
3510/// # Errors
3511///
3512/// This can fail for only when the span has any non-zero units greater than
3513/// hours. This is an error because it's impossible to determine the length of,
3514/// e.g., a month without a reference date.
3515///
3516/// This can never result in overflow because a `SignedDuration` can represent
3517/// a bigger span of time than `Span` when limited to units of hours or lower.
3518///
3519/// If you need to convert a `Span` to a `SignedDuration` that has non-zero
3520/// units bigger than hours, then please use [`Span::to_duration`] with a
3521/// corresponding relative date.
3522///
3523/// # Example: maximal span
3524///
3525/// This example shows the maximum possible span using units of hours or
3526/// smaller, and the corresponding `SignedDuration` value:
3527///
3528/// ```
3529/// use jiff::{SignedDuration, Span};
3530///
3531/// let sp = Span::new()
3532/// .hours(175_307_616)
3533/// .minutes(10_518_456_960i64)
3534/// .seconds(631_107_417_600i64)
3535/// .milliseconds(631_107_417_600_000i64)
3536/// .microseconds(631_107_417_600_000_000i64)
3537/// .nanoseconds(9_223_372_036_854_775_807i64);
3538/// let duration = SignedDuration::try_from(sp)?;
3539/// assert_eq!(duration, SignedDuration::new(3_164_760_460_036, 854_775_807));
3540///
3541/// # Ok::<(), Box<dyn std::error::Error>>(())
3542/// ```
3543impl TryFrom<Span> for SignedDuration {
3544 type Error = Error;
3545
3546 #[inline]
3547 fn try_from(sp: Span) -> Result<SignedDuration, Error> {
3548 requires_relative_date_err(sp.largest_unit()).context(
3549 "failed to convert span to duration without relative datetime \
3550 (must use `Span::to_duration` instead)",
3551 )?;
3552 Ok(sp.to_duration_invariant())
3553 }
3554}
3555
3556/// Converts a [`SignedDuration`] to a `Span`.
3557///
3558/// The span returned from this conversion will only ever have non-zero units
3559/// of seconds or smaller.
3560///
3561/// # Errors
3562///
3563/// This only fails when the given `SignedDuration` overflows the maximum
3564/// number of seconds representable by a `Span`.
3565///
3566/// # Example
3567///
3568/// This shows a basic conversion:
3569///
3570/// ```
3571/// use jiff::{SignedDuration, Span, ToSpan};
3572///
3573/// let duration = SignedDuration::new(86_400, 123_456_789);
3574/// let span = Span::try_from(duration)?;
3575/// // A duration-to-span conversion always results in a span with
3576/// // non-zero units no bigger than seconds.
3577/// assert_eq!(
3578/// span.fieldwise(),
3579/// 86_400.seconds().milliseconds(123).microseconds(456).nanoseconds(789),
3580/// );
3581///
3582/// # Ok::<(), Box<dyn std::error::Error>>(())
3583/// ```
3584///
3585/// # Example: rounding
3586///
3587/// This example shows how to convert a `SignedDuration` to a `Span`, and then
3588/// round it up to bigger units given a relative date:
3589///
3590/// ```
3591/// use jiff::{civil::date, SignedDuration, Span, SpanRound, ToSpan, Unit};
3592///
3593/// let duration = SignedDuration::new(450 * 86_401, 0);
3594/// let span = Span::try_from(duration)?;
3595/// // We get back a simple span of just seconds:
3596/// assert_eq!(span.fieldwise(), Span::new().seconds(450 * 86_401));
3597/// // But we can balance it up to bigger units:
3598/// let options = SpanRound::new()
3599/// .largest(Unit::Year)
3600/// .relative(date(2024, 1, 1));
3601/// assert_eq!(
3602/// span.round(options)?,
3603/// 1.year().months(2).days(25).minutes(7).seconds(30).fieldwise(),
3604/// );
3605///
3606/// # Ok::<(), Box<dyn std::error::Error>>(())
3607/// ```
3608impl TryFrom<SignedDuration> for Span {
3609 type Error = Error;
3610
3611 #[inline]
3612 fn try_from(d: SignedDuration) -> Result<Span, Error> {
3613 let seconds = d.as_secs();
3614 let nanoseconds = i64::from(d.subsec_nanos());
3615 let milliseconds = nanoseconds / t::NANOS_PER_MILLI.value();
3616 let microseconds = (nanoseconds % t::NANOS_PER_MILLI.value())
3617 / t::NANOS_PER_MICRO.value();
3618 let nanoseconds = nanoseconds % t::NANOS_PER_MICRO.value();
3619
3620 let span = Span::new().try_seconds(seconds).with_context(|| {
3621 err!("signed duration {d:?} overflows limits of a Jiff `Span`")
3622 })?;
3623 // These are all OK because `|SignedDuration::subsec_nanos|` is
3624 // guaranteed to return less than 1_000_000_000 nanoseconds. And
3625 // splitting that up into millis, micros and nano components is
3626 // guaranteed to fit into the limits of a `Span`.
3627 Ok(span
3628 .milliseconds(milliseconds)
3629 .microseconds(microseconds)
3630 .nanoseconds(nanoseconds))
3631 }
3632}
3633
3634#[cfg(feature = "serde")]
3635impl serde::Serialize for Span {
3636 #[inline]
3637 fn serialize<S: serde::Serializer>(
3638 &self,
3639 serializer: S,
3640 ) -> Result<S::Ok, S::Error> {
3641 serializer.collect_str(self)
3642 }
3643}
3644
3645#[cfg(feature = "serde")]
3646impl<'de> serde::Deserialize<'de> for Span {
3647 #[inline]
3648 fn deserialize<D: serde::Deserializer<'de>>(
3649 deserializer: D,
3650 ) -> Result<Span, D::Error> {
3651 use serde::de;
3652
3653 struct SpanVisitor;
3654
3655 impl<'de> de::Visitor<'de> for SpanVisitor {
3656 type Value = Span;
3657
3658 fn expecting(
3659 &self,
3660 f: &mut core::fmt::Formatter,
3661 ) -> core::fmt::Result {
3662 f.write_str("a span duration string")
3663 }
3664
3665 #[inline]
3666 fn visit_bytes<E: de::Error>(
3667 self,
3668 value: &[u8],
3669 ) -> Result<Span, E> {
3670 parse_iso_or_friendly(value).map_err(de::Error::custom)
3671 }
3672
3673 #[inline]
3674 fn visit_str<E: de::Error>(self, value: &str) -> Result<Span, E> {
3675 self.visit_bytes(value.as_bytes())
3676 }
3677 }
3678
3679 deserializer.deserialize_str(SpanVisitor)
3680 }
3681}
3682
3683#[cfg(test)]
3684impl quickcheck::Arbitrary for Span {
3685 fn arbitrary(g: &mut quickcheck::Gen) -> Span {
3686 // In order to sample from the full space of possible spans, we need
3687 // to provide a relative datetime. But if we do that, then it's
3688 // possible the span plus the datetime overflows. So we pick one
3689 // datetime and shrink the size of the span we can produce.
3690 type Nanos = ri64<-631_107_417_600_000_000, 631_107_417_600_000_000>;
3691 let nanos = Nanos::arbitrary(g).get();
3692 let relative =
3693 SpanRelativeTo::from(DateTime::constant(0, 1, 1, 0, 0, 0, 0));
3694 let round =
3695 SpanRound::new().largest(Unit::arbitrary(g)).relative(relative);
3696 Span::new().nanoseconds(nanos).round(round).unwrap()
3697 }
3698
3699 fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Self>> {
3700 alloc::boxed::Box::new(
3701 (
3702 (
3703 self.get_years_ranged(),
3704 self.get_months_ranged(),
3705 self.get_weeks_ranged(),
3706 self.get_days_ranged(),
3707 ),
3708 (
3709 self.get_hours_ranged(),
3710 self.get_minutes_ranged(),
3711 self.get_seconds_ranged(),
3712 self.get_milliseconds_ranged(),
3713 ),
3714 (
3715 self.get_microseconds_ranged(),
3716 self.get_nanoseconds_ranged(),
3717 ),
3718 )
3719 .shrink()
3720 .filter_map(
3721 |(
3722 (years, months, weeks, days),
3723 (hours, minutes, seconds, milliseconds),
3724 (microseconds, nanoseconds),
3725 )| {
3726 let span = Span::new()
3727 .years_ranged(years)
3728 .months_ranged(months)
3729 .weeks_ranged(weeks)
3730 .days_ranged(days)
3731 .hours_ranged(hours)
3732 .minutes_ranged(minutes)
3733 .seconds_ranged(seconds)
3734 .milliseconds_ranged(milliseconds)
3735 .microseconds_ranged(microseconds)
3736 .nanoseconds_ranged(nanoseconds);
3737 Some(span)
3738 },
3739 ),
3740 )
3741 }
3742}
3743
3744/// A wrapper for [`Span`] that implements the `Hash`, `Eq` and `PartialEq`
3745/// traits.
3746///
3747/// A `SpanFieldwise` is meant to make it easy to compare two spans in a "dumb"
3748/// way based purely on its unit values, while still providing a speed bump
3749/// to avoid accidentally doing this comparison on `Span` directly. This is
3750/// distinct from something like [`Span::compare`] that performs a comparison
3751/// on the actual elapsed time of two spans.
3752///
3753/// It is generally discouraged to use `SpanFieldwise` since spans that
3754/// represent an equivalent elapsed amount of time may compare unequal.
3755/// However, in some cases, it is useful to be able to assert precise field
3756/// values. For example, Jiff itself makes heavy use of fieldwise comparisons
3757/// for tests.
3758///
3759/// # Construction
3760///
3761/// While callers may use `SpanFieldwise(span)` (where `span` has type [`Span`])
3762/// to construct a value of this type, callers may find [`Span::fieldwise`]
3763/// more convenient. Namely, `Span::fieldwise` may avoid the need to explicitly
3764/// import `SpanFieldwise`.
3765///
3766/// # Trait implementations
3767///
3768/// In addition to implementing the `Hash`, `Eq` and `PartialEq` traits, this
3769/// type also provides `PartialEq` impls for comparing a `Span` with a
3770/// `SpanFieldwise`. This simplifies comparisons somewhat while still requiring
3771/// that at least one of the values has an explicit fieldwise comparison type.
3772///
3773/// # Safety
3774///
3775/// This type is guaranteed to have the same layout in memory as [`Span`].
3776///
3777/// # Example: the difference between `SpanFieldwise` and [`Span::compare`]
3778///
3779/// In short, `SpanFieldwise` considers `2 hours` and `120 minutes` to be
3780/// distinct values, but `Span::compare` considers them to be equivalent:
3781///
3782/// ```
3783/// use std::cmp::Ordering;
3784/// use jiff::ToSpan;
3785///
3786/// assert_ne!(120.minutes().fieldwise(), 2.hours().fieldwise());
3787/// assert_eq!(120.minutes().compare(2.hours())?, Ordering::Equal);
3788///
3789/// // These comparisons are allowed between a `Span` and a `SpanFieldwise`.
3790/// // Namely, as long as one value is "fieldwise," then the comparison is OK.
3791/// assert_ne!(120.minutes().fieldwise(), 2.hours());
3792/// assert_ne!(120.minutes(), 2.hours().fieldwise());
3793///
3794/// # Ok::<(), Box<dyn std::error::Error>>(())
3795/// ```
3796#[derive(Clone, Copy, Debug, Default)]
3797#[repr(transparent)]
3798pub struct SpanFieldwise(pub Span);
3799
3800// Exists so that things like `-1.day().fieldwise()` works as expected.
3801impl core::ops::Neg for SpanFieldwise {
3802 type Output = SpanFieldwise;
3803
3804 #[inline]
3805 fn neg(self) -> SpanFieldwise {
3806 SpanFieldwise(self.0.negate())
3807 }
3808}
3809
3810impl Eq for SpanFieldwise {}
3811
3812impl PartialEq for SpanFieldwise {
3813 fn eq(&self, rhs: &SpanFieldwise) -> bool {
3814 self.0.sign == rhs.0.sign
3815 && self.0.years == rhs.0.years
3816 && self.0.months == rhs.0.months
3817 && self.0.weeks == rhs.0.weeks
3818 && self.0.days == rhs.0.days
3819 && self.0.hours == rhs.0.hours
3820 && self.0.minutes == rhs.0.minutes
3821 && self.0.seconds == rhs.0.seconds
3822 && self.0.milliseconds == rhs.0.milliseconds
3823 && self.0.microseconds == rhs.0.microseconds
3824 && self.0.nanoseconds == rhs.0.nanoseconds
3825 }
3826}
3827
3828impl<'a> PartialEq<SpanFieldwise> for &'a SpanFieldwise {
3829 fn eq(&self, rhs: &SpanFieldwise) -> bool {
3830 *self == rhs
3831 }
3832}
3833
3834impl PartialEq<Span> for SpanFieldwise {
3835 fn eq(&self, rhs: &Span) -> bool {
3836 self == rhs.fieldwise()
3837 }
3838}
3839
3840impl PartialEq<SpanFieldwise> for Span {
3841 fn eq(&self, rhs: &SpanFieldwise) -> bool {
3842 self.fieldwise() == *rhs
3843 }
3844}
3845
3846impl<'a> PartialEq<SpanFieldwise> for &'a Span {
3847 fn eq(&self, rhs: &SpanFieldwise) -> bool {
3848 self.fieldwise() == *rhs
3849 }
3850}
3851
3852impl core::hash::Hash for SpanFieldwise {
3853 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
3854 self.0.sign.hash(state);
3855 self.0.years.hash(state);
3856 self.0.months.hash(state);
3857 self.0.weeks.hash(state);
3858 self.0.days.hash(state);
3859 self.0.hours.hash(state);
3860 self.0.minutes.hash(state);
3861 self.0.seconds.hash(state);
3862 self.0.milliseconds.hash(state);
3863 self.0.microseconds.hash(state);
3864 self.0.nanoseconds.hash(state);
3865 }
3866}
3867
3868impl From<Span> for SpanFieldwise {
3869 fn from(span: Span) -> SpanFieldwise {
3870 SpanFieldwise(span)
3871 }
3872}
3873
3874impl From<SpanFieldwise> for Span {
3875 fn from(span: SpanFieldwise) -> Span {
3876 span.0
3877 }
3878}
3879
3880/// A trait for enabling concise literals for creating [`Span`] values.
3881///
3882/// In short, this trait lets you write something like `5.seconds()` or
3883/// `1.day()` to create a [`Span`]. Once a `Span` has been created, you can
3884/// use its mutator methods to add more fields. For example,
3885/// `1.day().hours(10)` is equivalent to `Span::new().days(1).hours(10)`.
3886///
3887/// This trait is implemented for the following integer types: `i8`, `i16`,
3888/// `i32` and `i64`.
3889///
3890/// Note that this trait is provided as a convenience and should generally
3891/// only be used for literals in your source code. You should not use this
3892/// trait on numbers provided by end users. Namely, if the number provided
3893/// is not within Jiff's span limits, then these trait methods will panic.
3894/// Instead, use fallible mutator constructors like [`Span::try_days`]
3895/// or [`Span::try_seconds`].
3896///
3897/// # Example
3898///
3899/// ```
3900/// use jiff::ToSpan;
3901///
3902/// assert_eq!(5.days().to_string(), "P5D");
3903/// assert_eq!(5.days().hours(10).to_string(), "P5DT10H");
3904///
3905/// // Negation works and it doesn't matter where the sign goes. It can be
3906/// // applied to the span itself or to the integer.
3907/// assert_eq!((-5.days()).to_string(), "-P5D");
3908/// assert_eq!((-5).days().to_string(), "-P5D");
3909/// ```
3910///
3911/// # Example: alternative via span parsing
3912///
3913/// Another way of tersely building a `Span` value is by parsing a ISO 8601
3914/// duration string:
3915///
3916/// ```
3917/// use jiff::Span;
3918///
3919/// let span = "P5y2m15dT23h30m10s".parse::<Span>()?;
3920/// assert_eq!(
3921/// span.fieldwise(),
3922/// Span::new().years(5).months(2).days(15).hours(23).minutes(30).seconds(10),
3923/// );
3924///
3925/// # Ok::<(), Box<dyn std::error::Error>>(())
3926/// ```
3927pub trait ToSpan: Sized {
3928 /// Create a new span from this integer in units of years.
3929 ///
3930 /// # Panics
3931 ///
3932 /// When `Span::new().years(self)` would panic.
3933 fn years(self) -> Span;
3934
3935 /// Create a new span from this integer in units of months.
3936 ///
3937 /// # Panics
3938 ///
3939 /// When `Span::new().months(self)` would panic.
3940 fn months(self) -> Span;
3941
3942 /// Create a new span from this integer in units of weeks.
3943 ///
3944 /// # Panics
3945 ///
3946 /// When `Span::new().weeks(self)` would panic.
3947 fn weeks(self) -> Span;
3948
3949 /// Create a new span from this integer in units of days.
3950 ///
3951 /// # Panics
3952 ///
3953 /// When `Span::new().days(self)` would panic.
3954 fn days(self) -> Span;
3955
3956 /// Create a new span from this integer in units of hours.
3957 ///
3958 /// # Panics
3959 ///
3960 /// When `Span::new().hours(self)` would panic.
3961 fn hours(self) -> Span;
3962
3963 /// Create a new span from this integer in units of minutes.
3964 ///
3965 /// # Panics
3966 ///
3967 /// When `Span::new().minutes(self)` would panic.
3968 fn minutes(self) -> Span;
3969
3970 /// Create a new span from this integer in units of seconds.
3971 ///
3972 /// # Panics
3973 ///
3974 /// When `Span::new().seconds(self)` would panic.
3975 fn seconds(self) -> Span;
3976
3977 /// Create a new span from this integer in units of milliseconds.
3978 ///
3979 /// # Panics
3980 ///
3981 /// When `Span::new().milliseconds(self)` would panic.
3982 fn milliseconds(self) -> Span;
3983
3984 /// Create a new span from this integer in units of microseconds.
3985 ///
3986 /// # Panics
3987 ///
3988 /// When `Span::new().microseconds(self)` would panic.
3989 fn microseconds(self) -> Span;
3990
3991 /// Create a new span from this integer in units of nanoseconds.
3992 ///
3993 /// # Panics
3994 ///
3995 /// When `Span::new().nanoseconds(self)` would panic.
3996 fn nanoseconds(self) -> Span;
3997
3998 /// Equivalent to `years()`, but reads better for singular units.
3999 #[inline]
4000 fn year(self) -> Span {
4001 self.years()
4002 }
4003
4004 /// Equivalent to `months()`, but reads better for singular units.
4005 #[inline]
4006 fn month(self) -> Span {
4007 self.months()
4008 }
4009
4010 /// Equivalent to `weeks()`, but reads better for singular units.
4011 #[inline]
4012 fn week(self) -> Span {
4013 self.weeks()
4014 }
4015
4016 /// Equivalent to `days()`, but reads better for singular units.
4017 #[inline]
4018 fn day(self) -> Span {
4019 self.days()
4020 }
4021
4022 /// Equivalent to `hours()`, but reads better for singular units.
4023 #[inline]
4024 fn hour(self) -> Span {
4025 self.hours()
4026 }
4027
4028 /// Equivalent to `minutes()`, but reads better for singular units.
4029 #[inline]
4030 fn minute(self) -> Span {
4031 self.minutes()
4032 }
4033
4034 /// Equivalent to `seconds()`, but reads better for singular units.
4035 #[inline]
4036 fn second(self) -> Span {
4037 self.seconds()
4038 }
4039
4040 /// Equivalent to `milliseconds()`, but reads better for singular units.
4041 #[inline]
4042 fn millisecond(self) -> Span {
4043 self.milliseconds()
4044 }
4045
4046 /// Equivalent to `microseconds()`, but reads better for singular units.
4047 #[inline]
4048 fn microsecond(self) -> Span {
4049 self.microseconds()
4050 }
4051
4052 /// Equivalent to `nanoseconds()`, but reads better for singular units.
4053 #[inline]
4054 fn nanosecond(self) -> Span {
4055 self.nanoseconds()
4056 }
4057}
4058
4059macro_rules! impl_to_span {
4060 ($ty:ty) => {
4061 impl ToSpan for $ty {
4062 #[inline]
4063 fn years(self) -> Span {
4064 Span::new().years(self)
4065 }
4066 #[inline]
4067 fn months(self) -> Span {
4068 Span::new().months(self)
4069 }
4070 #[inline]
4071 fn weeks(self) -> Span {
4072 Span::new().weeks(self)
4073 }
4074 #[inline]
4075 fn days(self) -> Span {
4076 Span::new().days(self)
4077 }
4078 #[inline]
4079 fn hours(self) -> Span {
4080 Span::new().hours(self)
4081 }
4082 #[inline]
4083 fn minutes(self) -> Span {
4084 Span::new().minutes(self)
4085 }
4086 #[inline]
4087 fn seconds(self) -> Span {
4088 Span::new().seconds(self)
4089 }
4090 #[inline]
4091 fn milliseconds(self) -> Span {
4092 Span::new().milliseconds(self)
4093 }
4094 #[inline]
4095 fn microseconds(self) -> Span {
4096 Span::new().microseconds(self)
4097 }
4098 #[inline]
4099 fn nanoseconds(self) -> Span {
4100 Span::new().nanoseconds(self)
4101 }
4102 }
4103 };
4104}
4105
4106impl_to_span!(i8);
4107impl_to_span!(i16);
4108impl_to_span!(i32);
4109impl_to_span!(i64);
4110
4111/// A way to refer to a single calendar or clock unit.
4112///
4113/// This type is principally used in APIs involving a [`Span`], which is a
4114/// duration of time. For example, routines like [`Zoned::until`] permit
4115/// specifying the largest unit of the span returned:
4116///
4117/// ```
4118/// use jiff::{Unit, Zoned};
4119///
4120/// let zdt1: Zoned = "2024-07-06 17:40-04[America/New_York]".parse()?;
4121/// let zdt2: Zoned = "2024-11-05 08:00-05[America/New_York]".parse()?;
4122/// let span = zdt1.until((Unit::Year, &zdt2))?;
4123/// assert_eq!(format!("{span:#}"), "3mo 29d 14h 20m");
4124///
4125/// # Ok::<(), Box<dyn std::error::Error>>(())
4126/// ```
4127///
4128/// But a `Unit` is also used in APIs for rounding datetimes themselves:
4129///
4130/// ```
4131/// use jiff::{Unit, Zoned};
4132///
4133/// let zdt: Zoned = "2024-07-06 17:44:22.158-04[America/New_York]".parse()?;
4134/// let nearest_minute = zdt.round(Unit::Minute)?;
4135/// assert_eq!(
4136/// nearest_minute.to_string(),
4137/// "2024-07-06T17:44:00-04:00[America/New_York]",
4138/// );
4139///
4140/// # Ok::<(), Box<dyn std::error::Error>>(())
4141/// ```
4142///
4143/// # Example: ordering
4144///
4145/// This example demonstrates that `Unit` has an ordering defined such that
4146/// bigger units compare greater than smaller units.
4147///
4148/// ```
4149/// use jiff::Unit;
4150///
4151/// assert!(Unit::Year > Unit::Nanosecond);
4152/// assert!(Unit::Day > Unit::Hour);
4153/// assert!(Unit::Hour > Unit::Minute);
4154/// assert!(Unit::Hour > Unit::Minute);
4155/// assert_eq!(Unit::Hour, Unit::Hour);
4156/// ```
4157#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
4158pub enum Unit {
4159 /// A Gregorian calendar year. It usually has 365 days for non-leap years,
4160 /// and 366 days for leap years.
4161 Year = 9,
4162 /// A Gregorian calendar month. It usually has one of 28, 29, 30 or 31
4163 /// days.
4164 Month = 8,
4165 /// A week is 7 days that either begins on Sunday or Monday.
4166 Week = 7,
4167 /// A day is usually 24 hours, but some days may have different lengths
4168 /// due to time zone transitions.
4169 Day = 6,
4170 /// An hour is always 60 minutes.
4171 Hour = 5,
4172 /// A minute is always 60 seconds. (Jiff behaves as if leap seconds do not
4173 /// exist.)
4174 Minute = 4,
4175 /// A second is always 1,000 milliseconds.
4176 Second = 3,
4177 /// A millisecond is always 1,000 microseconds.
4178 Millisecond = 2,
4179 /// A microsecond is always 1,000 nanoseconds.
4180 Microsecond = 1,
4181 /// A nanosecond is the smallest granularity of time supported by Jiff.
4182 Nanosecond = 0,
4183}
4184
4185impl Unit {
4186 /// Returns the next biggest unit, if one exists.
4187 pub(crate) fn next(&self) -> Option<Unit> {
4188 match *self {
4189 Unit::Year => None,
4190 Unit::Month => Some(Unit::Year),
4191 Unit::Week => Some(Unit::Month),
4192 Unit::Day => Some(Unit::Week),
4193 Unit::Hour => Some(Unit::Day),
4194 Unit::Minute => Some(Unit::Hour),
4195 Unit::Second => Some(Unit::Minute),
4196 Unit::Millisecond => Some(Unit::Second),
4197 Unit::Microsecond => Some(Unit::Millisecond),
4198 Unit::Nanosecond => Some(Unit::Microsecond),
4199 }
4200 }
4201
4202 /// Returns the number of nanoseconds in this unit as a 128-bit integer.
4203 ///
4204 /// # Panics
4205 ///
4206 /// When this unit is always variable. That is, years or months.
4207 pub(crate) fn nanoseconds(self) -> NoUnits128 {
4208 match self {
4209 Unit::Nanosecond => Constant(1),
4210 Unit::Microsecond => t::NANOS_PER_MICRO,
4211 Unit::Millisecond => t::NANOS_PER_MILLI,
4212 Unit::Second => t::NANOS_PER_SECOND,
4213 Unit::Minute => t::NANOS_PER_MINUTE,
4214 Unit::Hour => t::NANOS_PER_HOUR,
4215 Unit::Day => t::NANOS_PER_CIVIL_DAY,
4216 Unit::Week => t::NANOS_PER_CIVIL_WEEK,
4217 unit => unreachable!("{unit:?} has no definitive time interval"),
4218 }
4219 .rinto()
4220 }
4221
4222 /// Returns true when this unit is definitively variable.
4223 ///
4224 /// In effect, this is any unit bigger than 'day', because any such unit
4225 /// can vary in time depending on its reference point. A 'day' can as well,
4226 /// but we sorta special case 'day' to mean '24 hours' for cases where
4227 /// the user is dealing with civil time.
4228 fn is_variable(self) -> bool {
4229 matches!(self, Unit::Year | Unit::Month | Unit::Week | Unit::Day)
4230 }
4231
4232 /// A human readable singular description of this unit of time.
4233 pub(crate) fn singular(&self) -> &'static str {
4234 match *self {
4235 Unit::Year => "year",
4236 Unit::Month => "month",
4237 Unit::Week => "week",
4238 Unit::Day => "day",
4239 Unit::Hour => "hour",
4240 Unit::Minute => "minute",
4241 Unit::Second => "second",
4242 Unit::Millisecond => "millisecond",
4243 Unit::Microsecond => "microsecond",
4244 Unit::Nanosecond => "nanosecond",
4245 }
4246 }
4247
4248 /// A human readable plural description of this unit of time.
4249 pub(crate) fn plural(&self) -> &'static str {
4250 match *self {
4251 Unit::Year => "years",
4252 Unit::Month => "months",
4253 Unit::Week => "weeks",
4254 Unit::Day => "days",
4255 Unit::Hour => "hours",
4256 Unit::Minute => "minutes",
4257 Unit::Second => "seconds",
4258 Unit::Millisecond => "milliseconds",
4259 Unit::Microsecond => "microseconds",
4260 Unit::Nanosecond => "nanoseconds",
4261 }
4262 }
4263
4264 /// A very succinct label corresponding to this unit.
4265 pub(crate) fn compact(&self) -> &'static str {
4266 match *self {
4267 Unit::Year => "y",
4268 Unit::Month => "mo",
4269 Unit::Week => "w",
4270 Unit::Day => "d",
4271 Unit::Hour => "h",
4272 Unit::Minute => "m",
4273 Unit::Second => "s",
4274 Unit::Millisecond => "ms",
4275 Unit::Microsecond => "µs",
4276 Unit::Nanosecond => "ns",
4277 }
4278 }
4279
4280 /// The inverse of `unit as usize`.
4281 fn from_usize(n: usize) -> Option<Unit> {
4282 match n {
4283 0 => Some(Unit::Nanosecond),
4284 1 => Some(Unit::Microsecond),
4285 2 => Some(Unit::Millisecond),
4286 3 => Some(Unit::Second),
4287 4 => Some(Unit::Minute),
4288 5 => Some(Unit::Hour),
4289 6 => Some(Unit::Day),
4290 7 => Some(Unit::Week),
4291 8 => Some(Unit::Month),
4292 9 => Some(Unit::Year),
4293 _ => None,
4294 }
4295 }
4296}
4297
4298#[cfg(test)]
4299impl quickcheck::Arbitrary for Unit {
4300 fn arbitrary(g: &mut quickcheck::Gen) -> Unit {
4301 Unit::from_usize(usize::arbitrary(g) % 10).unwrap()
4302 }
4303
4304 fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Self>> {
4305 alloc::boxed::Box::new(
4306 (*self as usize)
4307 .shrink()
4308 .map(|n| Unit::from_usize(n % 10).unwrap()),
4309 )
4310 }
4311}
4312
4313/// Options for [`Span::checked_add`] and [`Span::checked_sub`].
4314///
4315/// This type provides a way to ergonomically add two spans with an optional
4316/// relative datetime. Namely, a relative datetime is only needed when at least
4317/// one of the two spans being added (or subtracted) has a non-zero calendar
4318/// unit (years, months, weeks or days). Otherwise, an error will be returned.
4319///
4320/// Callers may use [`SpanArithmetic::days_are_24_hours`] to opt into 24-hour
4321/// invariant days (and 7-day weeks) without providing a relative datetime.
4322///
4323/// The main way to construct values of this type is with its `From` trait
4324/// implementations:
4325///
4326/// * `From<Span> for SpanArithmetic` adds (or subtracts) the given span to the
4327/// receiver in [`Span::checked_add`] (or [`Span::checked_sub`]).
4328/// * `From<(Span, civil::Date)> for SpanArithmetic` adds (or subtracts)
4329/// the given span to the receiver in [`Span::checked_add`] (or
4330/// [`Span::checked_sub`]), relative to the given date. There are also `From`
4331/// implementations for `civil::DateTime`, `Zoned` and [`SpanRelativeTo`].
4332///
4333/// # Example
4334///
4335/// ```
4336/// use jiff::ToSpan;
4337///
4338/// assert_eq!(
4339/// 1.hour().checked_add(30.minutes())?,
4340/// 1.hour().minutes(30).fieldwise(),
4341/// );
4342///
4343/// # Ok::<(), Box<dyn std::error::Error>>(())
4344/// ```
4345#[derive(Clone, Copy, Debug)]
4346pub struct SpanArithmetic<'a> {
4347 duration: Duration,
4348 relative: Option<SpanRelativeTo<'a>>,
4349}
4350
4351impl<'a> SpanArithmetic<'a> {
4352 /// This is a convenience function for setting the relative option on
4353 /// this configuration to [`SpanRelativeTo::days_are_24_hours`].
4354 ///
4355 /// # Example
4356 ///
4357 /// When doing arithmetic on spans involving days, either a relative
4358 /// datetime must be provided, or a special assertion opting into 24-hour
4359 /// days is required. Otherwise, you get an error.
4360 ///
4361 /// ```
4362 /// use jiff::{SpanArithmetic, ToSpan};
4363 ///
4364 /// let span1 = 2.days().hours(12);
4365 /// let span2 = 12.hours();
4366 /// // No relative date provided, which results in an error.
4367 /// assert_eq!(
4368 /// span1.checked_add(span2).unwrap_err().to_string(),
4369 /// "using unit 'day' in a span or configuration requires that \
4370 /// either a relative reference time be given or \
4371 /// `SpanRelativeTo::days_are_24_hours()` is used to indicate \
4372 /// invariant 24-hour days, but neither were provided",
4373 /// );
4374 /// let sum = span1.checked_add(
4375 /// SpanArithmetic::from(span2).days_are_24_hours(),
4376 /// )?;
4377 /// assert_eq!(sum, 3.days().fieldwise());
4378 ///
4379 /// # Ok::<(), Box<dyn std::error::Error>>(())
4380 /// ```
4381 #[inline]
4382 pub fn days_are_24_hours(self) -> SpanArithmetic<'a> {
4383 self.relative(SpanRelativeTo::days_are_24_hours())
4384 }
4385}
4386
4387impl<'a> SpanArithmetic<'a> {
4388 #[inline]
4389 fn relative<R: Into<SpanRelativeTo<'a>>>(
4390 self,
4391 relative: R,
4392 ) -> SpanArithmetic<'a> {
4393 SpanArithmetic { relative: Some(relative.into()), ..self }
4394 }
4395
4396 #[inline]
4397 fn checked_add(self, span1: Span) -> Result<Span, Error> {
4398 match self.duration.to_signed()? {
4399 SDuration::Span(span2) => {
4400 span1.checked_add_span(self.relative, &span2)
4401 }
4402 SDuration::Absolute(dur2) => {
4403 span1.checked_add_duration(self.relative, dur2)
4404 }
4405 }
4406 }
4407}
4408
4409impl From<Span> for SpanArithmetic<'static> {
4410 fn from(span: Span) -> SpanArithmetic<'static> {
4411 let duration = Duration::from(span);
4412 SpanArithmetic { duration, relative: None }
4413 }
4414}
4415
4416impl<'a> From<&'a Span> for SpanArithmetic<'static> {
4417 fn from(span: &'a Span) -> SpanArithmetic<'static> {
4418 let duration = Duration::from(*span);
4419 SpanArithmetic { duration, relative: None }
4420 }
4421}
4422
4423impl From<(Span, Date)> for SpanArithmetic<'static> {
4424 #[inline]
4425 fn from((span, date): (Span, Date)) -> SpanArithmetic<'static> {
4426 SpanArithmetic::from(span).relative(date)
4427 }
4428}
4429
4430impl From<(Span, DateTime)> for SpanArithmetic<'static> {
4431 #[inline]
4432 fn from((span, datetime): (Span, DateTime)) -> SpanArithmetic<'static> {
4433 SpanArithmetic::from(span).relative(datetime)
4434 }
4435}
4436
4437impl<'a> From<(Span, &'a Zoned)> for SpanArithmetic<'a> {
4438 #[inline]
4439 fn from((span, zoned): (Span, &'a Zoned)) -> SpanArithmetic<'a> {
4440 SpanArithmetic::from(span).relative(zoned)
4441 }
4442}
4443
4444impl<'a> From<(Span, SpanRelativeTo<'a>)> for SpanArithmetic<'a> {
4445 #[inline]
4446 fn from(
4447 (span, relative): (Span, SpanRelativeTo<'a>),
4448 ) -> SpanArithmetic<'a> {
4449 SpanArithmetic::from(span).relative(relative)
4450 }
4451}
4452
4453impl<'a> From<(&'a Span, Date)> for SpanArithmetic<'static> {
4454 #[inline]
4455 fn from((span, date): (&'a Span, Date)) -> SpanArithmetic<'static> {
4456 SpanArithmetic::from(span).relative(date)
4457 }
4458}
4459
4460impl<'a> From<(&'a Span, DateTime)> for SpanArithmetic<'static> {
4461 #[inline]
4462 fn from(
4463 (span, datetime): (&'a Span, DateTime),
4464 ) -> SpanArithmetic<'static> {
4465 SpanArithmetic::from(span).relative(datetime)
4466 }
4467}
4468
4469impl<'a, 'b> From<(&'a Span, &'b Zoned)> for SpanArithmetic<'b> {
4470 #[inline]
4471 fn from((span, zoned): (&'a Span, &'b Zoned)) -> SpanArithmetic<'b> {
4472 SpanArithmetic::from(span).relative(zoned)
4473 }
4474}
4475
4476impl<'a, 'b> From<(&'a Span, SpanRelativeTo<'b>)> for SpanArithmetic<'b> {
4477 #[inline]
4478 fn from(
4479 (span, relative): (&'a Span, SpanRelativeTo<'b>),
4480 ) -> SpanArithmetic<'b> {
4481 SpanArithmetic::from(span).relative(relative)
4482 }
4483}
4484
4485impl From<SignedDuration> for SpanArithmetic<'static> {
4486 fn from(duration: SignedDuration) -> SpanArithmetic<'static> {
4487 let duration = Duration::from(duration);
4488 SpanArithmetic { duration, relative: None }
4489 }
4490}
4491
4492impl From<(SignedDuration, Date)> for SpanArithmetic<'static> {
4493 #[inline]
4494 fn from(
4495 (duration, date): (SignedDuration, Date),
4496 ) -> SpanArithmetic<'static> {
4497 SpanArithmetic::from(duration).relative(date)
4498 }
4499}
4500
4501impl From<(SignedDuration, DateTime)> for SpanArithmetic<'static> {
4502 #[inline]
4503 fn from(
4504 (duration, datetime): (SignedDuration, DateTime),
4505 ) -> SpanArithmetic<'static> {
4506 SpanArithmetic::from(duration).relative(datetime)
4507 }
4508}
4509
4510impl<'a> From<(SignedDuration, &'a Zoned)> for SpanArithmetic<'a> {
4511 #[inline]
4512 fn from(
4513 (duration, zoned): (SignedDuration, &'a Zoned),
4514 ) -> SpanArithmetic<'a> {
4515 SpanArithmetic::from(duration).relative(zoned)
4516 }
4517}
4518
4519impl From<UnsignedDuration> for SpanArithmetic<'static> {
4520 fn from(duration: UnsignedDuration) -> SpanArithmetic<'static> {
4521 let duration = Duration::from(duration);
4522 SpanArithmetic { duration, relative: None }
4523 }
4524}
4525
4526impl From<(UnsignedDuration, Date)> for SpanArithmetic<'static> {
4527 #[inline]
4528 fn from(
4529 (duration, date): (UnsignedDuration, Date),
4530 ) -> SpanArithmetic<'static> {
4531 SpanArithmetic::from(duration).relative(date)
4532 }
4533}
4534
4535impl From<(UnsignedDuration, DateTime)> for SpanArithmetic<'static> {
4536 #[inline]
4537 fn from(
4538 (duration, datetime): (UnsignedDuration, DateTime),
4539 ) -> SpanArithmetic<'static> {
4540 SpanArithmetic::from(duration).relative(datetime)
4541 }
4542}
4543
4544impl<'a> From<(UnsignedDuration, &'a Zoned)> for SpanArithmetic<'a> {
4545 #[inline]
4546 fn from(
4547 (duration, zoned): (UnsignedDuration, &'a Zoned),
4548 ) -> SpanArithmetic<'a> {
4549 SpanArithmetic::from(duration).relative(zoned)
4550 }
4551}
4552
4553/// Options for [`Span::compare`].
4554///
4555/// This type provides a way to ergonomically compare two spans with an
4556/// optional relative datetime. Namely, a relative datetime is only needed when
4557/// at least one of the two spans being compared has a non-zero calendar unit
4558/// (years, months, weeks or days). Otherwise, an error will be returned.
4559///
4560/// Callers may use [`SpanCompare::days_are_24_hours`] to opt into 24-hour
4561/// invariant days (and 7-day weeks) without providing a relative datetime.
4562///
4563/// The main way to construct values of this type is with its `From` trait
4564/// implementations:
4565///
4566/// * `From<Span> for SpanCompare` compares the given span to the receiver
4567/// in [`Span::compare`].
4568/// * `From<(Span, civil::Date)> for SpanCompare` compares the given span
4569/// to the receiver in [`Span::compare`], relative to the given date. There
4570/// are also `From` implementations for `civil::DateTime`, `Zoned` and
4571/// [`SpanRelativeTo`].
4572///
4573/// # Example
4574///
4575/// ```
4576/// use jiff::ToSpan;
4577///
4578/// let span1 = 3.hours();
4579/// let span2 = 180.minutes();
4580/// assert_eq!(span1.compare(span2)?, std::cmp::Ordering::Equal);
4581///
4582/// # Ok::<(), Box<dyn std::error::Error>>(())
4583/// ```
4584#[derive(Clone, Copy, Debug)]
4585pub struct SpanCompare<'a> {
4586 span: Span,
4587 relative: Option<SpanRelativeTo<'a>>,
4588}
4589
4590impl<'a> SpanCompare<'a> {
4591 /// This is a convenience function for setting the relative option on
4592 /// this configuration to [`SpanRelativeTo::days_are_24_hours`].
4593 ///
4594 /// # Example
4595 ///
4596 /// When comparing spans involving days, either a relative datetime must be
4597 /// provided, or a special assertion opting into 24-hour days is
4598 /// required. Otherwise, you get an error.
4599 ///
4600 /// ```
4601 /// use jiff::{SpanCompare, ToSpan, Unit};
4602 ///
4603 /// let span1 = 2.days().hours(12);
4604 /// let span2 = 60.hours();
4605 /// // No relative date provided, which results in an error.
4606 /// assert_eq!(
4607 /// span1.compare(span2).unwrap_err().to_string(),
4608 /// "using unit 'day' in a span or configuration requires that \
4609 /// either a relative reference time be given or \
4610 /// `SpanRelativeTo::days_are_24_hours()` is used to indicate \
4611 /// invariant 24-hour days, but neither were provided",
4612 /// );
4613 /// let ordering = span1.compare(
4614 /// SpanCompare::from(span2).days_are_24_hours(),
4615 /// )?;
4616 /// assert_eq!(ordering, std::cmp::Ordering::Equal);
4617 ///
4618 /// # Ok::<(), Box<dyn std::error::Error>>(())
4619 /// ```
4620 #[inline]
4621 pub fn days_are_24_hours(self) -> SpanCompare<'a> {
4622 self.relative(SpanRelativeTo::days_are_24_hours())
4623 }
4624}
4625
4626impl<'a> SpanCompare<'a> {
4627 #[inline]
4628 fn new(span: Span) -> SpanCompare<'static> {
4629 SpanCompare { span, relative: None }
4630 }
4631
4632 #[inline]
4633 fn relative<R: Into<SpanRelativeTo<'a>>>(
4634 self,
4635 relative: R,
4636 ) -> SpanCompare<'a> {
4637 SpanCompare { relative: Some(relative.into()), ..self }
4638 }
4639
4640 fn compare(self, span: Span) -> Result<Ordering, Error> {
4641 let (span1, span2) = (span, self.span);
4642 let unit = span1.largest_unit().max(span2.largest_unit());
4643 let start = match self.relative {
4644 Some(r) => match r.to_relative(unit)? {
4645 Some(r) => r,
4646 None => {
4647 let nanos1 = span1.to_invariant_nanoseconds();
4648 let nanos2 = span2.to_invariant_nanoseconds();
4649 return Ok(nanos1.cmp(&nanos2));
4650 }
4651 },
4652 None => {
4653 requires_relative_date_err(unit)?;
4654 let nanos1 = span1.to_invariant_nanoseconds();
4655 let nanos2 = span2.to_invariant_nanoseconds();
4656 return Ok(nanos1.cmp(&nanos2));
4657 }
4658 };
4659 let end1 = start.checked_add(span1)?.to_nanosecond();
4660 let end2 = start.checked_add(span2)?.to_nanosecond();
4661 Ok(end1.cmp(&end2))
4662 }
4663}
4664
4665impl From<Span> for SpanCompare<'static> {
4666 fn from(span: Span) -> SpanCompare<'static> {
4667 SpanCompare::new(span)
4668 }
4669}
4670
4671impl<'a> From<&'a Span> for SpanCompare<'static> {
4672 fn from(span: &'a Span) -> SpanCompare<'static> {
4673 SpanCompare::new(*span)
4674 }
4675}
4676
4677impl From<(Span, Date)> for SpanCompare<'static> {
4678 #[inline]
4679 fn from((span, date): (Span, Date)) -> SpanCompare<'static> {
4680 SpanCompare::from(span).relative(date)
4681 }
4682}
4683
4684impl From<(Span, DateTime)> for SpanCompare<'static> {
4685 #[inline]
4686 fn from((span, datetime): (Span, DateTime)) -> SpanCompare<'static> {
4687 SpanCompare::from(span).relative(datetime)
4688 }
4689}
4690
4691impl<'a> From<(Span, &'a Zoned)> for SpanCompare<'a> {
4692 #[inline]
4693 fn from((span, zoned): (Span, &'a Zoned)) -> SpanCompare<'a> {
4694 SpanCompare::from(span).relative(zoned)
4695 }
4696}
4697
4698impl<'a> From<(Span, SpanRelativeTo<'a>)> for SpanCompare<'a> {
4699 #[inline]
4700 fn from((span, relative): (Span, SpanRelativeTo<'a>)) -> SpanCompare<'a> {
4701 SpanCompare::from(span).relative(relative)
4702 }
4703}
4704
4705impl<'a> From<(&'a Span, Date)> for SpanCompare<'static> {
4706 #[inline]
4707 fn from((span, date): (&'a Span, Date)) -> SpanCompare<'static> {
4708 SpanCompare::from(span).relative(date)
4709 }
4710}
4711
4712impl<'a> From<(&'a Span, DateTime)> for SpanCompare<'static> {
4713 #[inline]
4714 fn from((span, datetime): (&'a Span, DateTime)) -> SpanCompare<'static> {
4715 SpanCompare::from(span).relative(datetime)
4716 }
4717}
4718
4719impl<'a, 'b> From<(&'a Span, &'b Zoned)> for SpanCompare<'b> {
4720 #[inline]
4721 fn from((span, zoned): (&'a Span, &'b Zoned)) -> SpanCompare<'b> {
4722 SpanCompare::from(span).relative(zoned)
4723 }
4724}
4725
4726impl<'a, 'b> From<(&'a Span, SpanRelativeTo<'b>)> for SpanCompare<'b> {
4727 #[inline]
4728 fn from(
4729 (span, relative): (&'a Span, SpanRelativeTo<'b>),
4730 ) -> SpanCompare<'b> {
4731 SpanCompare::from(span).relative(relative)
4732 }
4733}
4734
4735/// Options for [`Span::total`].
4736///
4737/// This type provides a way to ergonomically determine the number of a
4738/// particular unit in a span, with a potentially fractional component, with
4739/// an optional relative datetime. Namely, a relative datetime is only needed
4740/// when the span has a non-zero calendar unit (years, months, weeks or days).
4741/// Otherwise, an error will be returned.
4742///
4743/// Callers may use [`SpanTotal::days_are_24_hours`] to opt into 24-hour
4744/// invariant days (and 7-day weeks) without providing a relative datetime.
4745///
4746/// The main way to construct values of this type is with its `From` trait
4747/// implementations:
4748///
4749/// * `From<Unit> for SpanTotal` computes a total for the given unit in the
4750/// receiver span for [`Span::total`].
4751/// * `From<(Unit, civil::Date)> for SpanTotal` computes a total for the given
4752/// unit in the receiver span for [`Span::total`], relative to the given date.
4753/// There are also `From` implementations for `civil::DateTime`, `Zoned` and
4754/// [`SpanRelativeTo`].
4755///
4756/// # Example
4757///
4758/// This example shows how to find the number of seconds in a particular span:
4759///
4760/// ```
4761/// use jiff::{ToSpan, Unit};
4762///
4763/// let span = 3.hours().minutes(10);
4764/// assert_eq!(span.total(Unit::Second)?, 11_400.0);
4765///
4766/// # Ok::<(), Box<dyn std::error::Error>>(())
4767/// ```
4768///
4769/// # Example: 24 hour days
4770///
4771/// This shows how to find the total number of 24 hour days in `123,456,789`
4772/// seconds.
4773///
4774/// ```
4775/// use jiff::{SpanTotal, ToSpan, Unit};
4776///
4777/// let span = 123_456_789.seconds();
4778/// assert_eq!(
4779/// span.total(SpanTotal::from(Unit::Day).days_are_24_hours())?,
4780/// 1428.8980208333332,
4781/// );
4782///
4783/// # Ok::<(), Box<dyn std::error::Error>>(())
4784/// ```
4785///
4786/// # Example: DST is taken into account
4787///
4788/// The month of March 2024 in `America/New_York` had 31 days, but one of those
4789/// days was 23 hours long due a transition into daylight saving time:
4790///
4791/// ```
4792/// use jiff::{civil::date, ToSpan, Unit};
4793///
4794/// let span = 744.hours();
4795/// let relative = date(2024, 3, 1).in_tz("America/New_York")?;
4796/// // Because of the short day, 744 hours is actually a little *more* than
4797/// // 1 month starting from 2024-03-01.
4798/// assert_eq!(span.total((Unit::Month, &relative))?, 1.0013888888888889);
4799///
4800/// # Ok::<(), Box<dyn std::error::Error>>(())
4801/// ```
4802///
4803/// Now compare what happens when the relative datetime is civil and not
4804/// time zone aware:
4805///
4806/// ```
4807/// use jiff::{civil::date, ToSpan, Unit};
4808///
4809/// let span = 744.hours();
4810/// let relative = date(2024, 3, 1);
4811/// assert_eq!(span.total((Unit::Month, relative))?, 1.0);
4812///
4813/// # Ok::<(), Box<dyn std::error::Error>>(())
4814/// ```
4815#[derive(Clone, Copy, Debug)]
4816pub struct SpanTotal<'a> {
4817 unit: Unit,
4818 relative: Option<SpanRelativeTo<'a>>,
4819}
4820
4821impl<'a> SpanTotal<'a> {
4822 /// This is a convenience function for setting the relative option on
4823 /// this configuration to [`SpanRelativeTo::days_are_24_hours`].
4824 ///
4825 /// # Example
4826 ///
4827 /// When computing the total duration for spans involving days, either a
4828 /// relative datetime must be provided, or a special assertion opting into
4829 /// 24-hour days is required. Otherwise, you get an error.
4830 ///
4831 /// ```
4832 /// use jiff::{civil::date, SpanTotal, ToSpan, Unit};
4833 ///
4834 /// let span = 2.days().hours(12);
4835 ///
4836 /// // No relative date provided, which results in an error.
4837 /// assert_eq!(
4838 /// span.total(Unit::Hour).unwrap_err().to_string(),
4839 /// "using unit 'day' in a span or configuration requires that either \
4840 /// a relative reference time be given or \
4841 /// `SpanRelativeTo::days_are_24_hours()` is used to indicate \
4842 /// invariant 24-hour days, but neither were provided",
4843 /// );
4844 ///
4845 /// // If we can assume all days are 24 hours, then we can assert it:
4846 /// let total = span.total(
4847 /// SpanTotal::from(Unit::Hour).days_are_24_hours(),
4848 /// )?;
4849 /// assert_eq!(total, 60.0);
4850 ///
4851 /// // Or provide a relative datetime, which is preferred if possible:
4852 /// let total = span.total((Unit::Hour, date(2025, 1, 26)))?;
4853 /// assert_eq!(total, 60.0);
4854 ///
4855 /// # Ok::<(), Box<dyn std::error::Error>>(())
4856 /// ```
4857 #[inline]
4858 pub fn days_are_24_hours(self) -> SpanTotal<'a> {
4859 self.relative(SpanRelativeTo::days_are_24_hours())
4860 }
4861}
4862
4863impl<'a> SpanTotal<'a> {
4864 #[inline]
4865 fn new(unit: Unit) -> SpanTotal<'static> {
4866 SpanTotal { unit, relative: None }
4867 }
4868
4869 #[inline]
4870 fn relative<R: Into<SpanRelativeTo<'a>>>(
4871 self,
4872 relative: R,
4873 ) -> SpanTotal<'a> {
4874 SpanTotal { relative: Some(relative.into()), ..self }
4875 }
4876
4877 fn total(self, span: Span) -> Result<f64, Error> {
4878 let max_unit = self.unit.max(span.largest_unit());
4879 let relative = match self.relative {
4880 Some(r) => match r.to_relative(max_unit)? {
4881 Some(r) => r,
4882 None => {
4883 return Ok(self.total_invariant(span));
4884 }
4885 },
4886 None => {
4887 requires_relative_date_err(max_unit)?;
4888 return Ok(self.total_invariant(span));
4889 }
4890 };
4891 let relspan = relative.into_relative_span(self.unit, span)?;
4892 if !self.unit.is_variable() {
4893 return Ok(self.total_invariant(relspan.span));
4894 }
4895
4896 assert!(self.unit >= Unit::Day);
4897 let sign = relspan.span.get_sign_ranged();
4898 let (relative_start, relative_end) = match relspan.kind {
4899 RelativeSpanKind::Civil { start, end } => {
4900 let start = Relative::Civil(start);
4901 let end = Relative::Civil(end);
4902 (start, end)
4903 }
4904 RelativeSpanKind::Zoned { start, end } => {
4905 let start = Relative::Zoned(start);
4906 let end = Relative::Zoned(end);
4907 (start, end)
4908 }
4909 };
4910 let (relative0, relative1) = clamp_relative_span(
4911 &relative_start,
4912 relspan.span.without_lower(self.unit),
4913 self.unit,
4914 sign.rinto(),
4915 )?;
4916 let denom = (relative1 - relative0).get() as f64;
4917 let numer = (relative_end.to_nanosecond() - relative0).get() as f64;
4918 let unit_val = relspan.span.get_units_ranged(self.unit).get() as f64;
4919 Ok(unit_val + (numer / denom) * (sign.get() as f64))
4920 }
4921
4922 #[inline]
4923 fn total_invariant(&self, span: Span) -> f64 {
4924 assert!(self.unit <= Unit::Week);
4925 let nanos = span.to_invariant_nanoseconds();
4926 (nanos.get() as f64) / (self.unit.nanoseconds().get() as f64)
4927 }
4928}
4929
4930impl From<Unit> for SpanTotal<'static> {
4931 #[inline]
4932 fn from(unit: Unit) -> SpanTotal<'static> {
4933 SpanTotal::new(unit)
4934 }
4935}
4936
4937impl From<(Unit, Date)> for SpanTotal<'static> {
4938 #[inline]
4939 fn from((unit, date): (Unit, Date)) -> SpanTotal<'static> {
4940 SpanTotal::from(unit).relative(date)
4941 }
4942}
4943
4944impl From<(Unit, DateTime)> for SpanTotal<'static> {
4945 #[inline]
4946 fn from((unit, datetime): (Unit, DateTime)) -> SpanTotal<'static> {
4947 SpanTotal::from(unit).relative(datetime)
4948 }
4949}
4950
4951impl<'a> From<(Unit, &'a Zoned)> for SpanTotal<'a> {
4952 #[inline]
4953 fn from((unit, zoned): (Unit, &'a Zoned)) -> SpanTotal<'a> {
4954 SpanTotal::from(unit).relative(zoned)
4955 }
4956}
4957
4958impl<'a> From<(Unit, SpanRelativeTo<'a>)> for SpanTotal<'a> {
4959 #[inline]
4960 fn from((unit, relative): (Unit, SpanRelativeTo<'a>)) -> SpanTotal<'a> {
4961 SpanTotal::from(unit).relative(relative)
4962 }
4963}
4964
4965/// Options for [`Span::round`].
4966///
4967/// This type provides a way to configure the rounding of a span. This
4968/// includes setting the smallest unit (i.e., the unit to round), the
4969/// largest unit, the rounding increment, the rounding mode (e.g., "ceil" or
4970/// "truncate") and the datetime that the span is relative to.
4971///
4972/// `Span::round` accepts anything that implements `Into<SpanRound>`. There are
4973/// a few key trait implementations that make this convenient:
4974///
4975/// * `From<Unit> for SpanRound` will construct a rounding configuration where
4976/// the smallest unit is set to the one given.
4977/// * `From<(Unit, i64)> for SpanRound` will construct a rounding configuration
4978/// where the smallest unit and the rounding increment are set to the ones
4979/// given.
4980///
4981/// In order to set other options (like the largest unit, the rounding mode
4982/// and the relative datetime), one must explicitly create a `SpanRound` and
4983/// pass it to `Span::round`.
4984///
4985/// # Example
4986///
4987/// This example shows how to find how many full 3 month quarters are in a
4988/// particular span of time.
4989///
4990/// ```
4991/// use jiff::{civil::date, RoundMode, SpanRound, ToSpan, Unit};
4992///
4993/// let span1 = 10.months().days(15);
4994/// let round = SpanRound::new()
4995/// .smallest(Unit::Month)
4996/// .increment(3)
4997/// .mode(RoundMode::Trunc)
4998/// // A relative datetime must be provided when
4999/// // rounding involves calendar units.
5000/// .relative(date(2024, 1, 1));
5001/// let span2 = span1.round(round)?;
5002/// assert_eq!(span2.get_months() / 3, 3);
5003///
5004/// # Ok::<(), Box<dyn std::error::Error>>(())
5005/// ```
5006#[derive(Clone, Copy, Debug)]
5007pub struct SpanRound<'a> {
5008 largest: Option<Unit>,
5009 smallest: Unit,
5010 mode: RoundMode,
5011 increment: i64,
5012 relative: Option<SpanRelativeTo<'a>>,
5013}
5014
5015impl<'a> SpanRound<'a> {
5016 /// Create a new default configuration for rounding a span via
5017 /// [`Span::round`].
5018 ///
5019 /// The default configuration does no rounding.
5020 #[inline]
5021 pub fn new() -> SpanRound<'static> {
5022 SpanRound {
5023 largest: None,
5024 smallest: Unit::Nanosecond,
5025 mode: RoundMode::HalfExpand,
5026 increment: 1,
5027 relative: None,
5028 }
5029 }
5030
5031 /// Set the smallest units allowed in the span returned. These are the
5032 /// units that the span is rounded to.
5033 ///
5034 /// # Errors
5035 ///
5036 /// The smallest units must be no greater than the largest units. If this
5037 /// is violated, then rounding a span with this configuration will result
5038 /// in an error.
5039 ///
5040 /// If a smallest unit bigger than days is selected without a relative
5041 /// datetime reference point, then an error is returned when using this
5042 /// configuration with [`Span::round`].
5043 ///
5044 /// # Example
5045 ///
5046 /// A basic example that rounds to the nearest minute:
5047 ///
5048 /// ```
5049 /// use jiff::{ToSpan, Unit};
5050 ///
5051 /// let span = 15.minutes().seconds(46);
5052 /// assert_eq!(span.round(Unit::Minute)?, 16.minutes().fieldwise());
5053 ///
5054 /// # Ok::<(), Box<dyn std::error::Error>>(())
5055 /// ```
5056 #[inline]
5057 pub fn smallest(self, unit: Unit) -> SpanRound<'a> {
5058 SpanRound { smallest: unit, ..self }
5059 }
5060
5061 /// Set the largest units allowed in the span returned.
5062 ///
5063 /// When a largest unit is not specified, then it defaults to the largest
5064 /// non-zero unit that is at least as big as the configured smallest
5065 /// unit. For example, given a span of `2 months 17 hours`, the default
5066 /// largest unit would be `Unit::Month`. The default implies that a span's
5067 /// units do not get "bigger" than what was given.
5068 ///
5069 /// Once a largest unit is set, there is no way to change this rounding
5070 /// configuration back to using the "automatic" default. Instead, callers
5071 /// must create a new configuration.
5072 ///
5073 /// If a largest unit is set and no other options are set, then the
5074 /// rounding operation can be said to be a "re-balancing." That is, the
5075 /// span won't lose precision, but the way in which it is expressed may
5076 /// change.
5077 ///
5078 /// # Errors
5079 ///
5080 /// The largest units, when set, must be at least as big as the smallest
5081 /// units (which defaults to [`Unit::Nanosecond`]). If this is violated,
5082 /// then rounding a span with this configuration will result in an error.
5083 ///
5084 /// If a largest unit bigger than days is selected without a relative
5085 /// datetime reference point, then an error is returned when using this
5086 /// configuration with [`Span::round`].
5087 ///
5088 /// # Example: re-balancing
5089 ///
5090 /// This shows how a span can be re-balanced without losing precision:
5091 ///
5092 /// ```
5093 /// use jiff::{SpanRound, ToSpan, Unit};
5094 ///
5095 /// let span = 86_401_123_456_789i64.nanoseconds();
5096 /// assert_eq!(
5097 /// span.round(SpanRound::new().largest(Unit::Hour))?.fieldwise(),
5098 /// 24.hours().seconds(1).milliseconds(123).microseconds(456).nanoseconds(789),
5099 /// );
5100 ///
5101 /// # Ok::<(), Box<dyn std::error::Error>>(())
5102 /// ```
5103 ///
5104 /// If you need to use a largest unit bigger than hours, then you must
5105 /// provide a relative datetime as a reference point (otherwise an error
5106 /// will occur):
5107 ///
5108 /// ```
5109 /// use jiff::{civil::date, SpanRound, ToSpan, Unit};
5110 ///
5111 /// let span = 3_968_000.seconds();
5112 /// let round = SpanRound::new()
5113 /// .largest(Unit::Day)
5114 /// .relative(date(2024, 7, 1));
5115 /// assert_eq!(
5116 /// span.round(round)?,
5117 /// 45.days().hours(22).minutes(13).seconds(20).fieldwise(),
5118 /// );
5119 ///
5120 /// # Ok::<(), Box<dyn std::error::Error>>(())
5121 /// ```
5122 ///
5123 /// As a special case for days, one can instead opt into invariant 24-hour
5124 /// days (and 7-day weeks) without providing an explicit relative date:
5125 ///
5126 /// ```
5127 /// use jiff::{SpanRound, ToSpan, Unit};
5128 ///
5129 /// let span = 86_401_123_456_789i64.nanoseconds();
5130 /// assert_eq!(
5131 /// span.round(
5132 /// SpanRound::new().largest(Unit::Day).days_are_24_hours(),
5133 /// )?.fieldwise(),
5134 /// 1.day().seconds(1).milliseconds(123).microseconds(456).nanoseconds(789),
5135 /// );
5136 ///
5137 /// # Ok::<(), Box<dyn std::error::Error>>(())
5138 /// ```
5139 ///
5140 /// # Example: re-balancing while taking DST into account
5141 ///
5142 /// When given a zone aware relative datetime, rounding will even take
5143 /// DST into account:
5144 ///
5145 /// ```
5146 /// use jiff::{SpanRound, ToSpan, Unit, Zoned};
5147 ///
5148 /// let span = 2756.hours();
5149 /// let zdt = "2020-01-01T00:00+01:00[Europe/Rome]".parse::<Zoned>()?;
5150 /// let round = SpanRound::new().largest(Unit::Year).relative(&zdt);
5151 /// assert_eq!(
5152 /// span.round(round)?,
5153 /// 3.months().days(23).hours(21).fieldwise(),
5154 /// );
5155 ///
5156 /// # Ok::<(), Box<dyn std::error::Error>>(())
5157 /// ```
5158 ///
5159 /// Now compare with the same operation, but on a civil datetime (which is
5160 /// not aware of time zone):
5161 ///
5162 /// ```
5163 /// use jiff::{civil::DateTime, SpanRound, ToSpan, Unit};
5164 ///
5165 /// let span = 2756.hours();
5166 /// let dt = "2020-01-01T00:00".parse::<DateTime>()?;
5167 /// let round = SpanRound::new().largest(Unit::Year).relative(dt);
5168 /// assert_eq!(
5169 /// span.round(round)?,
5170 /// 3.months().days(23).hours(20).fieldwise(),
5171 /// );
5172 ///
5173 /// # Ok::<(), Box<dyn std::error::Error>>(())
5174 /// ```
5175 ///
5176 /// The result is 1 hour shorter. This is because, in the zone
5177 /// aware re-balancing, it accounts for the transition into DST at
5178 /// `2020-03-29T01:00Z`, which skips an hour. This makes the span one hour
5179 /// longer because one of the days in the span is actually only 23 hours
5180 /// long instead of 24 hours.
5181 #[inline]
5182 pub fn largest(self, unit: Unit) -> SpanRound<'a> {
5183 SpanRound { largest: Some(unit), ..self }
5184 }
5185
5186 /// Set the rounding mode.
5187 ///
5188 /// This defaults to [`RoundMode::HalfExpand`], which makes rounding work
5189 /// like how you were taught in school.
5190 ///
5191 /// # Example
5192 ///
5193 /// A basic example that rounds to the nearest minute, but changing its
5194 /// rounding mode to truncation:
5195 ///
5196 /// ```
5197 /// use jiff::{RoundMode, SpanRound, ToSpan, Unit};
5198 ///
5199 /// let span = 15.minutes().seconds(46);
5200 /// assert_eq!(
5201 /// span.round(SpanRound::new()
5202 /// .smallest(Unit::Minute)
5203 /// .mode(RoundMode::Trunc),
5204 /// )?,
5205 /// // The default round mode does rounding like
5206 /// // how you probably learned in school, and would
5207 /// // result in rounding up to 16 minutes. But we
5208 /// // change it to truncation here, which makes it
5209 /// // round down.
5210 /// 15.minutes().fieldwise(),
5211 /// );
5212 ///
5213 /// # Ok::<(), Box<dyn std::error::Error>>(())
5214 /// ```
5215 #[inline]
5216 pub fn mode(self, mode: RoundMode) -> SpanRound<'a> {
5217 SpanRound { mode, ..self }
5218 }
5219
5220 /// Set the rounding increment for the smallest unit.
5221 ///
5222 /// The default value is `1`. Other values permit rounding the smallest
5223 /// unit to the nearest integer increment specified. For example, if the
5224 /// smallest unit is set to [`Unit::Minute`], then a rounding increment of
5225 /// `30` would result in rounding in increments of a half hour. That is,
5226 /// the only minute value that could result would be `0` or `30`.
5227 ///
5228 /// # Errors
5229 ///
5230 /// When the smallest unit is less than days, the rounding increment must
5231 /// divide evenly into the next highest unit after the smallest unit
5232 /// configured (and must not be equivalent to it). For example, if the
5233 /// smallest unit is [`Unit::Nanosecond`], then *some* of the valid values
5234 /// for the rounding increment are `1`, `2`, `4`, `5`, `100` and `500`.
5235 /// Namely, any integer that divides evenly into `1,000` nanoseconds since
5236 /// there are `1,000` nanoseconds in the next highest unit (microseconds).
5237 ///
5238 /// The error will occur when computing the span, and not when setting
5239 /// the increment here.
5240 ///
5241 /// # Example
5242 ///
5243 /// This shows how to round a span to the nearest 5 minute increment:
5244 ///
5245 /// ```
5246 /// use jiff::{ToSpan, Unit};
5247 ///
5248 /// let span = 4.hours().minutes(2).seconds(30);
5249 /// assert_eq!(
5250 /// span.round((Unit::Minute, 5))?,
5251 /// 4.hours().minutes(5).fieldwise(),
5252 /// );
5253 ///
5254 /// # Ok::<(), Box<dyn std::error::Error>>(())
5255 /// ```
5256 #[inline]
5257 pub fn increment(self, increment: i64) -> SpanRound<'a> {
5258 SpanRound { increment, ..self }
5259 }
5260
5261 /// Set the relative datetime to use when rounding a span.
5262 ///
5263 /// A relative datetime is only required when calendar units (units greater
5264 /// than days) are involved. This includes having calendar units in the
5265 /// original span, or calendar units in the configured smallest or largest
5266 /// unit. A relative datetime is required when calendar units are used
5267 /// because the duration of a particular calendar unit (like 1 month or 1
5268 /// year) is variable and depends on the date. For example, 1 month from
5269 /// 2024-01-01 is 31 days, but 1 month from 2024-02-01 is 29 days.
5270 ///
5271 /// A relative datetime is provided by anything that implements
5272 /// `Into<SpanRelativeTo>`. There are a few convenience trait
5273 /// implementations provided:
5274 ///
5275 /// * `From<&Zoned> for SpanRelativeTo` uses a zone aware datetime to do
5276 /// rounding. In this case, rounding will take time zone transitions into
5277 /// account. In particular, when using a zoned relative datetime, not all
5278 /// days are necessarily 24 hours.
5279 /// * `From<civil::DateTime> for SpanRelativeTo` uses a civil datetime. In
5280 /// this case, all days will be considered 24 hours long.
5281 /// * `From<civil::Date> for SpanRelativeTo` uses a civil date. In this
5282 /// case, all days will be considered 24 hours long.
5283 ///
5284 /// Note that one can impose 24-hour days without providing a reference
5285 /// date via [`SpanRelativeTo::days_are_24_hours`].
5286 ///
5287 /// # Errors
5288 ///
5289 /// If rounding involves a calendar unit (units bigger than hours) and no
5290 /// relative datetime is provided, then this configuration will lead to
5291 /// an error when used with [`Span::round`].
5292 ///
5293 /// # Example
5294 ///
5295 /// This example shows very precisely how a DST transition can impact
5296 /// rounding and re-balancing. For example, consider the day `2024-11-03`
5297 /// in `America/New_York`. On this day, the 1 o'clock hour was repeated,
5298 /// making the day 24 hours long. This will be taken into account when
5299 /// rounding if a zoned datetime is provided as a reference point:
5300 ///
5301 /// ```
5302 /// use jiff::{SpanRound, ToSpan, Unit, Zoned};
5303 ///
5304 /// let zdt = "2024-11-03T00-04[America/New_York]".parse::<Zoned>()?;
5305 /// let round = SpanRound::new().largest(Unit::Hour).relative(&zdt);
5306 /// assert_eq!(1.day().round(round)?, 25.hours().fieldwise());
5307 ///
5308 /// # Ok::<(), Box<dyn std::error::Error>>(())
5309 /// ```
5310 ///
5311 /// And similarly for `2024-03-10`, where the 2 o'clock hour was skipped
5312 /// entirely:
5313 ///
5314 /// ```
5315 /// use jiff::{SpanRound, ToSpan, Unit, Zoned};
5316 ///
5317 /// let zdt = "2024-03-10T00-05[America/New_York]".parse::<Zoned>()?;
5318 /// let round = SpanRound::new().largest(Unit::Hour).relative(&zdt);
5319 /// assert_eq!(1.day().round(round)?, 23.hours().fieldwise());
5320 ///
5321 /// # Ok::<(), Box<dyn std::error::Error>>(())
5322 /// ```
5323 #[inline]
5324 pub fn relative<R: Into<SpanRelativeTo<'a>>>(
5325 self,
5326 relative: R,
5327 ) -> SpanRound<'a> {
5328 SpanRound { relative: Some(relative.into()), ..self }
5329 }
5330
5331 /// This is a convenience function for setting the relative option on
5332 /// this configuration to [`SpanRelativeTo::days_are_24_hours`].
5333 ///
5334 /// # Example
5335 ///
5336 /// When rounding spans involving days, either a relative datetime must be
5337 /// provided, or a special assertion opting into 24-hour days is
5338 /// required. Otherwise, you get an error.
5339 ///
5340 /// ```
5341 /// use jiff::{SpanRound, ToSpan, Unit};
5342 ///
5343 /// let span = 2.days().hours(12);
5344 /// // No relative date provided, which results in an error.
5345 /// assert_eq!(
5346 /// span.round(Unit::Day).unwrap_err().to_string(),
5347 /// "error with `smallest` rounding option: using unit 'day' in a \
5348 /// span or configuration requires that either a relative reference \
5349 /// time be given or `SpanRelativeTo::days_are_24_hours()` is used \
5350 /// to indicate invariant 24-hour days, but neither were provided",
5351 /// );
5352 /// let rounded = span.round(
5353 /// SpanRound::new().smallest(Unit::Day).days_are_24_hours(),
5354 /// )?;
5355 /// assert_eq!(rounded, 3.days().fieldwise());
5356 ///
5357 /// # Ok::<(), Box<dyn std::error::Error>>(())
5358 /// ```
5359 #[inline]
5360 pub fn days_are_24_hours(self) -> SpanRound<'a> {
5361 self.relative(SpanRelativeTo::days_are_24_hours())
5362 }
5363
5364 /// Returns the configured smallest unit on this round configuration.
5365 #[inline]
5366 pub(crate) fn get_smallest(&self) -> Unit {
5367 self.smallest
5368 }
5369
5370 /// Returns the configured largest unit on this round configuration.
5371 #[inline]
5372 pub(crate) fn get_largest(&self) -> Option<Unit> {
5373 self.largest
5374 }
5375
5376 /// Returns true only when rounding a span *may* change it. When it
5377 /// returns false, and if the span is already balanced according to
5378 /// the largest unit in this round configuration, then it is guaranteed
5379 /// that rounding is a no-op.
5380 ///
5381 /// This is useful to avoid rounding calls after doing span arithmetic
5382 /// on datetime types. This works because the "largest" unit is used to
5383 /// construct a balanced span for the difference between two datetimes.
5384 /// So we already know the span has been balanced. If this weren't the
5385 /// case, then the largest unit being different from the one in the span
5386 /// could result in rounding making a change. (And indeed, in the general
5387 /// case of span rounding below, we do a more involved check for this.)
5388 #[inline]
5389 pub(crate) fn rounding_may_change_span_ignore_largest(&self) -> bool {
5390 self.smallest > Unit::Nanosecond || self.increment > 1
5391 }
5392
5393 /// Does the actual span rounding.
5394 fn round(&self, span: Span) -> Result<Span, Error> {
5395 let existing_largest = span.largest_unit();
5396 let mode = self.mode;
5397 let smallest = self.smallest;
5398 let largest =
5399 self.largest.unwrap_or_else(|| smallest.max(existing_largest));
5400 let max = existing_largest.max(largest);
5401 let increment = increment::for_span(smallest, self.increment)?;
5402 if largest < smallest {
5403 return Err(err!(
5404 "largest unit ('{largest}') cannot be smaller than \
5405 smallest unit ('{smallest}')",
5406 largest = largest.singular(),
5407 smallest = smallest.singular(),
5408 ));
5409 }
5410 let relative = match self.relative {
5411 Some(ref r) => {
5412 match r.to_relative(max)? {
5413 Some(r) => r,
5414 None => {
5415 // If our reference point is civil time, then its units
5416 // are invariant as long as we are using day-or-lower
5417 // everywhere. That is, the length of the duration is
5418 // independent of the reference point. In which case,
5419 // rounding is a simple matter of converting the span
5420 // to a number of nanoseconds and then rounding that.
5421 return Ok(round_span_invariant(
5422 span, smallest, largest, increment, mode,
5423 )?);
5424 }
5425 }
5426 }
5427 None => {
5428 // This is only okay if none of our units are above 'day'.
5429 // That is, a reference point is only necessary when there is
5430 // no reasonable invariant interpretation of the span. And this
5431 // is only true when everything is less than 'day'.
5432 requires_relative_date_err(smallest)
5433 .context("error with `smallest` rounding option")?;
5434 if let Some(largest) = self.largest {
5435 requires_relative_date_err(largest)
5436 .context("error with `largest` rounding option")?;
5437 }
5438 requires_relative_date_err(existing_largest).context(
5439 "error with largest unit in span to be rounded",
5440 )?;
5441 assert!(max <= Unit::Week);
5442 return Ok(round_span_invariant(
5443 span, smallest, largest, increment, mode,
5444 )?);
5445 }
5446 };
5447 relative.round(span, smallest, largest, increment, mode)
5448 }
5449}
5450
5451impl Default for SpanRound<'static> {
5452 fn default() -> SpanRound<'static> {
5453 SpanRound::new()
5454 }
5455}
5456
5457impl From<Unit> for SpanRound<'static> {
5458 fn from(unit: Unit) -> SpanRound<'static> {
5459 SpanRound::default().smallest(unit)
5460 }
5461}
5462
5463impl From<(Unit, i64)> for SpanRound<'static> {
5464 fn from((unit, increment): (Unit, i64)) -> SpanRound<'static> {
5465 SpanRound::default().smallest(unit).increment(increment)
5466 }
5467}
5468
5469/// A relative datetime for use with [`Span`] APIs.
5470///
5471/// A relative datetime can be one of the following: [`civil::Date`](Date),
5472/// [`civil::DateTime`](DateTime) or [`Zoned`]. It can be constructed from any
5473/// of the preceding types via `From` trait implementations.
5474///
5475/// A relative datetime is used to indicate how the calendar units of a `Span`
5476/// should be interpreted. For example, the span "1 month" does not have a
5477/// fixed meaning. One month from `2024-03-01` is 31 days, but one month from
5478/// `2024-04-01` is 30 days. Similar for years.
5479///
5480/// When a relative datetime in time zone aware (i.e., it is a `Zoned`), then
5481/// a `Span` will also consider its day units to be variable in length. For
5482/// example, `2024-03-10` in `America/New_York` was only 23 hours long, where
5483/// as `2024-11-03` in `America/New_York` was 25 hours long. When a relative
5484/// datetime is civil, then days are considered to always be of a fixed 24
5485/// hour length.
5486///
5487/// This type is principally used as an input to one of several different
5488/// [`Span`] APIs:
5489///
5490/// * [`Span::round`] rounds spans. A relative datetime is necessary when
5491/// dealing with calendar units. (But spans without calendar units can be
5492/// rounded without providing a relative datetime.)
5493/// * Span arithmetic via [`Span::checked_add`] and [`Span::checked_sub`].
5494/// A relative datetime is needed when adding or subtracting spans with
5495/// calendar units.
5496/// * Span comarisons via [`Span::compare`] require a relative datetime when
5497/// comparing spans with calendar units.
5498/// * Computing the "total" duration as a single floating point number via
5499/// [`Span::total`] also requires a relative datetime when dealing with
5500/// calendar units.
5501///
5502/// # Example
5503///
5504/// This example shows how to round a span with larger calendar units to
5505/// smaller units:
5506///
5507/// ```
5508/// use jiff::{SpanRound, ToSpan, Unit, Zoned};
5509///
5510/// let zdt: Zoned = "2012-01-01[Antarctica/Troll]".parse()?;
5511/// let round = SpanRound::new().largest(Unit::Day).relative(&zdt);
5512/// assert_eq!(1.year().round(round)?, 366.days().fieldwise());
5513///
5514/// // If you tried this without a relative datetime, it would fail:
5515/// let round = SpanRound::new().largest(Unit::Day);
5516/// assert!(1.year().round(round).is_err());
5517///
5518/// # Ok::<(), Box<dyn std::error::Error>>(())
5519/// ```
5520#[derive(Clone, Copy, Debug)]
5521pub struct SpanRelativeTo<'a> {
5522 kind: SpanRelativeToKind<'a>,
5523}
5524
5525impl<'a> SpanRelativeTo<'a> {
5526 /// Creates a special marker that indicates all days ought to be assumed
5527 /// to be 24 hours without providing a relative reference time.
5528 ///
5529 /// This is relevant to the following APIs:
5530 ///
5531 /// * [`Span::checked_add`]
5532 /// * [`Span::checked_sub`]
5533 /// * [`Span::compare`]
5534 /// * [`Span::total`]
5535 /// * [`Span::round`]
5536 /// * [`Span::to_duration`]
5537 ///
5538 /// Specifically, in a previous version of Jiff, the above APIs permitted
5539 /// _silently_ assuming that days are always 24 hours when a relative
5540 /// reference date wasn't provided. In the current version of Jiff, this
5541 /// silent interpretation no longer happens and instead an error will
5542 /// occur.
5543 ///
5544 /// If you need to use these APIs with spans that contain non-zero units
5545 /// of days or weeks but without a relative reference date, then you may
5546 /// use this routine to create a special marker for `SpanRelativeTo` that
5547 /// permits the APIs above to assume days are always 24 hours.
5548 ///
5549 /// # Motivation
5550 ///
5551 /// The purpose of the marker is two-fold:
5552 ///
5553 /// * Requiring the marker is important for improving the consistency of
5554 /// `Span` APIs. Previously, some APIs (like [`Timestamp::checked_add`])
5555 /// would always return an error if the `Span` given had non-zero
5556 /// units of days or greater. On the other hand, other APIs (like
5557 /// [`Span::checked_add`]) would autoamtically assume days were always
5558 /// 24 hours if no relative reference time was given and either span had
5559 /// non-zero units of days. With this marker, APIs _never_ assume days are
5560 /// always 24 hours automatically.
5561 /// * When it _is_ appropriate to assume all days are 24 hours
5562 /// (for example, when only dealing with spans derived from
5563 /// [`civil`](crate::civil) datetimes) and where providing a relative
5564 /// reference datetime doesn't make sense. In this case, one _could_
5565 /// provide a "dummy" reference date since the precise date in civil time
5566 /// doesn't impact the length of a day. But a marker like the one returned
5567 /// here is more explicit for the purpose of assuming days are always 24
5568 /// hours.
5569 ///
5570 /// With that said, ideally, callers should provide a relative reference
5571 /// datetime if possible.
5572 ///
5573 /// See [Issue #48] for more discussion on this topic.
5574 ///
5575 /// # Example: different interpretations of "1 day"
5576 ///
5577 /// This example shows how "1 day" can be interpreted differently via the
5578 /// [`Span::total`] API:
5579 ///
5580 /// ```
5581 /// use jiff::{SpanRelativeTo, ToSpan, Unit, Zoned};
5582 ///
5583 /// let span = 1.day();
5584 ///
5585 /// // An error because days aren't always 24 hours:
5586 /// assert_eq!(
5587 /// span.total(Unit::Hour).unwrap_err().to_string(),
5588 /// "using unit 'day' in a span or configuration requires that either \
5589 /// a relative reference time be given or \
5590 /// `SpanRelativeTo::days_are_24_hours()` is used to indicate \
5591 /// invariant 24-hour days, but neither were provided",
5592 /// );
5593 /// // Opt into invariant 24 hour days without a relative date:
5594 /// let marker = SpanRelativeTo::days_are_24_hours();
5595 /// let hours = span.total((Unit::Hour, marker))?;
5596 /// assert_eq!(hours, 24.0);
5597 /// // Days can be shorter than 24 hours:
5598 /// let zdt: Zoned = "2024-03-10[America/New_York]".parse()?;
5599 /// let hours = span.total((Unit::Hour, &zdt))?;
5600 /// assert_eq!(hours, 23.0);
5601 /// // Days can be longer than 24 hours:
5602 /// let zdt: Zoned = "2024-11-03[America/New_York]".parse()?;
5603 /// let hours = span.total((Unit::Hour, &zdt))?;
5604 /// assert_eq!(hours, 25.0);
5605 ///
5606 /// # Ok::<(), Box<dyn std::error::Error>>(())
5607 /// ```
5608 ///
5609 /// Similar behavior applies to the other APIs listed above.
5610 ///
5611 /// # Example: different interpretations of "1 week"
5612 ///
5613 /// This example shows how "1 week" can be interpreted differently via the
5614 /// [`Span::total`] API:
5615 ///
5616 /// ```
5617 /// use jiff::{SpanRelativeTo, ToSpan, Unit, Zoned};
5618 ///
5619 /// let span = 1.week();
5620 ///
5621 /// // An error because days aren't always 24 hours:
5622 /// assert_eq!(
5623 /// span.total(Unit::Hour).unwrap_err().to_string(),
5624 /// "using unit 'week' in a span or configuration requires that either \
5625 /// a relative reference time be given or \
5626 /// `SpanRelativeTo::days_are_24_hours()` is used to indicate \
5627 /// invariant 24-hour days, but neither were provided",
5628 /// );
5629 /// // Opt into invariant 24 hour days without a relative date:
5630 /// let marker = SpanRelativeTo::days_are_24_hours();
5631 /// let hours = span.total((Unit::Hour, marker))?;
5632 /// assert_eq!(hours, 168.0);
5633 /// // Weeks can be shorter than 24*7 hours:
5634 /// let zdt: Zoned = "2024-03-10[America/New_York]".parse()?;
5635 /// let hours = span.total((Unit::Hour, &zdt))?;
5636 /// assert_eq!(hours, 167.0);
5637 /// // Weeks can be longer than 24*7 hours:
5638 /// let zdt: Zoned = "2024-11-03[America/New_York]".parse()?;
5639 /// let hours = span.total((Unit::Hour, &zdt))?;
5640 /// assert_eq!(hours, 169.0);
5641 ///
5642 /// # Ok::<(), Box<dyn std::error::Error>>(())
5643 /// ```
5644 ///
5645 /// # Example: working with [`civil::Date`](crate::civil::Date)
5646 ///
5647 /// A `Span` returned by computing the difference in time between two
5648 /// [`civil::Date`](crate::civil::Date)s will have a non-zero number of
5649 /// days. In older versions of Jiff, if one wanted to add spans returned by
5650 /// these APIs, you could do so without futzing with relative dates. But
5651 /// now you either need to provide a relative date:
5652 ///
5653 /// ```
5654 /// use jiff::{civil::date, ToSpan};
5655 ///
5656 /// let d1 = date(2025, 1, 18);
5657 /// let d2 = date(2025, 1, 26);
5658 /// let d3 = date(2025, 2, 14);
5659 ///
5660 /// let span1 = d2 - d1;
5661 /// let span2 = d3 - d2;
5662 /// let total = span1.checked_add((span2, d1))?;
5663 /// assert_eq!(total, 27.days().fieldwise());
5664 ///
5665 /// # Ok::<(), Box<dyn std::error::Error>>(())
5666 /// ```
5667 ///
5668 /// Or you can provide a marker indicating that days are always 24 hours.
5669 /// This is fine for this use case since one is only doing civil calendar
5670 /// arithmetic and not working with time zones:
5671 ///
5672 /// ```
5673 /// use jiff::{civil::date, SpanRelativeTo, ToSpan};
5674 ///
5675 /// let d1 = date(2025, 1, 18);
5676 /// let d2 = date(2025, 1, 26);
5677 /// let d3 = date(2025, 2, 14);
5678 ///
5679 /// let span1 = d2 - d1;
5680 /// let span2 = d3 - d2;
5681 /// let total = span1.checked_add(
5682 /// (span2, SpanRelativeTo::days_are_24_hours()),
5683 /// )?;
5684 /// assert_eq!(total, 27.days().fieldwise());
5685 ///
5686 /// # Ok::<(), Box<dyn std::error::Error>>(())
5687 /// ```
5688 ///
5689 /// [Issue #48]: https://github.com/BurntSushi/jiff/issues/48
5690 #[inline]
5691 pub const fn days_are_24_hours() -> SpanRelativeTo<'static> {
5692 let kind = SpanRelativeToKind::DaysAre24Hours;
5693 SpanRelativeTo { kind }
5694 }
5695
5696 /// Converts this public API relative datetime into a more versatile
5697 /// internal representation of the same concept.
5698 ///
5699 /// Basically, the internal `Relative` type is `Cow` which means it isn't
5700 /// `Copy`. But it can present a more uniform API. The public API type
5701 /// doesn't have `Cow` so that it can be `Copy`.
5702 ///
5703 /// We also take this opportunity to attach some convenient data, such
5704 /// as a timestamp when the relative datetime type is civil.
5705 ///
5706 /// This can return `None` if this `SpanRelativeTo` isn't actually a
5707 /// datetime but a "marker" indicating some unit (like days) should be
5708 /// treated as invariant. Or `None` is returned when the given unit is
5709 /// always invariant (hours or smaller).
5710 ///
5711 /// # Errors
5712 ///
5713 /// If there was a problem doing this conversion, then an error is
5714 /// returned. In practice, this only occurs for a civil datetime near the
5715 /// civil datetime minimum and maximum values.
5716 fn to_relative(&self, unit: Unit) -> Result<Option<Relative<'a>>, Error> {
5717 if !unit.is_variable() {
5718 return Ok(None);
5719 }
5720 match self.kind {
5721 SpanRelativeToKind::Civil(dt) => {
5722 Ok(Some(Relative::Civil(RelativeCivil::new(dt)?)))
5723 }
5724 SpanRelativeToKind::Zoned(zdt) => {
5725 Ok(Some(Relative::Zoned(RelativeZoned {
5726 zoned: DumbCow::Borrowed(zdt),
5727 })))
5728 }
5729 SpanRelativeToKind::DaysAre24Hours => {
5730 if matches!(unit, Unit::Year | Unit::Month) {
5731 return Err(err!(
5732 "using unit '{unit}' in span or configuration \
5733 requires that a relative reference time be given \
5734 (`SpanRelativeTo::days_are_24_hours()` was given \
5735 but this only permits using days and weeks \
5736 without a relative reference time)",
5737 unit = unit.singular(),
5738 ));
5739 }
5740 Ok(None)
5741 }
5742 }
5743 }
5744}
5745
5746#[derive(Clone, Copy, Debug)]
5747enum SpanRelativeToKind<'a> {
5748 Civil(DateTime),
5749 Zoned(&'a Zoned),
5750 DaysAre24Hours,
5751}
5752
5753impl<'a> From<&'a Zoned> for SpanRelativeTo<'a> {
5754 fn from(zdt: &'a Zoned) -> SpanRelativeTo<'a> {
5755 SpanRelativeTo { kind: SpanRelativeToKind::Zoned(zdt) }
5756 }
5757}
5758
5759impl From<DateTime> for SpanRelativeTo<'static> {
5760 fn from(dt: DateTime) -> SpanRelativeTo<'static> {
5761 SpanRelativeTo { kind: SpanRelativeToKind::Civil(dt) }
5762 }
5763}
5764
5765impl From<Date> for SpanRelativeTo<'static> {
5766 fn from(date: Date) -> SpanRelativeTo<'static> {
5767 let dt = DateTime::from_parts(date, Time::midnight());
5768 SpanRelativeTo { kind: SpanRelativeToKind::Civil(dt) }
5769 }
5770}
5771
5772impl<'a> core::fmt::Display for SpanRelativeToKind<'a> {
5773 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
5774 match *self {
5775 SpanRelativeToKind::Civil(dt) => core::fmt::Display::fmt(&dt, f),
5776 SpanRelativeToKind::Zoned(zdt) => core::fmt::Display::fmt(zdt, f),
5777 SpanRelativeToKind::DaysAre24Hours => write!(f, "TODO"),
5778 }
5779 }
5780}
5781
5782/// A bit set that keeps track of all non-zero units on a `Span`.
5783///
5784/// Because of alignment, adding this to a `Span` does not make it any bigger.
5785///
5786/// The benefit of this bit set is to make it extremely cheap to enable fast
5787/// paths in various places. For example, doing arithmetic on a `Date` with an
5788/// arbitrary `Span` is pretty involved. But if you know the `Span` only
5789/// consists of non-zero units of days (and zero for all other units), then you
5790/// can take a much cheaper path.
5791#[derive(Clone, Copy)]
5792pub(crate) struct UnitSet(u16);
5793
5794impl UnitSet {
5795 /// Return a bit set representing all units as zero.
5796 #[inline]
5797 fn empty() -> UnitSet {
5798 UnitSet(0)
5799 }
5800
5801 /// Set the given `unit` to `is_zero` status in this set.
5802 ///
5803 /// When `is_zero` is false, the unit is added to this set. Otherwise,
5804 /// the unit is removed from this set.
5805 #[inline]
5806 fn set(self, unit: Unit, is_zero: bool) -> UnitSet {
5807 let bit = 1 << unit as usize;
5808 if is_zero {
5809 UnitSet(self.0 & !bit)
5810 } else {
5811 UnitSet(self.0 | bit)
5812 }
5813 }
5814
5815 /// Returns true if and only if no units are in this set.
5816 #[inline]
5817 pub(crate) fn is_empty(&self) -> bool {
5818 self.0 == 0
5819 }
5820
5821 /// Returns true if and only if this `Span` contains precisely one
5822 /// non-zero unit corresponding to the unit given.
5823 #[inline]
5824 pub(crate) fn contains_only(self, unit: Unit) -> bool {
5825 self.0 == (1 << unit as usize)
5826 }
5827
5828 /// Returns this set, but with only calendar units.
5829 #[inline]
5830 pub(crate) fn only_calendar(self) -> UnitSet {
5831 UnitSet(self.0 & 0b0000_0011_1100_0000)
5832 }
5833
5834 /// Returns this set, but with only time units.
5835 #[inline]
5836 pub(crate) fn only_time(self) -> UnitSet {
5837 UnitSet(self.0 & 0b0000_0000_0011_1111)
5838 }
5839
5840 /// Returns the largest unit in this set, or `None` if none are present.
5841 #[inline]
5842 pub(crate) fn largest_unit(self) -> Option<Unit> {
5843 let zeros = usize::try_from(self.0.leading_zeros()).ok()?;
5844 15usize.checked_sub(zeros).and_then(Unit::from_usize)
5845 }
5846}
5847
5848// N.B. This `Debug` impl isn't typically used.
5849//
5850// This is because the `Debug` impl for `Span` just emits itself in the
5851// friendly duration format, which doesn't include internal representation
5852// details like this set. It is included in `Span::debug`, but this isn't
5853// part of the public crate API.
5854impl core::fmt::Debug for UnitSet {
5855 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
5856 write!(f, "{{")?;
5857 let mut units = *self;
5858 let mut i = 0;
5859 while let Some(unit) = units.largest_unit() {
5860 if i > 0 {
5861 write!(f, ", ")?;
5862 }
5863 i += 1;
5864 write!(f, "{}", unit.compact())?;
5865 units = units.set(unit, false);
5866 }
5867 if i == 0 {
5868 write!(f, "∅")?;
5869 }
5870 write!(f, "}}")
5871 }
5872}
5873
5874/// An internal abstraction for managing a relative datetime for use in some
5875/// `Span` APIs.
5876///
5877/// This is effectively the same as a `SpanRelativeTo`, but uses a `Cow<Zoned>`
5878/// instead of a `&Zoned`. This makes it non-`Copy`, but allows us to craft a
5879/// more uniform API. (i.e., `relative + span = relative` instead of `relative
5880/// + span = owned_relative` or whatever.) Note that the `Copy` impl on
5881/// `SpanRelativeTo` means it has to accept a `&Zoned`. It can't ever take a
5882/// `Zoned` since it is non-Copy.
5883///
5884/// NOTE: Separately from above, I think it's plausible that this type could be
5885/// designed a bit differently. Namely, something like this:
5886///
5887/// ```text
5888/// struct Relative<'a> {
5889/// tz: Option<&'a TimeZone>,
5890/// dt: DateTime,
5891/// ts: Timestamp,
5892/// }
5893/// ```
5894///
5895/// That is, we do zone aware stuff but without an actual `Zoned` type. But I
5896/// think in order to make that work, we would need to expose most of the
5897/// `Zoned` API as functions on its component types (DateTime, Timestamp and
5898/// TimeZone). I think we are likely to want to do that for public API reasons,
5899/// but I'd like to resist it since I think it will add a lot of complexity.
5900/// Or maybe we need a `Unzoned` type that is `DateTime` and `Timestamp`, but
5901/// requires passing the time zone in to each of its methods. That might work
5902/// quite well, even if it was just an internal type.
5903///
5904/// Anyway, I'm not 100% sure the above would work, but I think it would. It
5905/// would be nicer because everything would be `Copy` all the time. We'd never
5906/// need a `Cow<TimeZone>` for example, because we never need to change or
5907/// create a new time zone.
5908#[derive(Clone, Debug)]
5909enum Relative<'a> {
5910 Civil(RelativeCivil),
5911 Zoned(RelativeZoned<'a>),
5912}
5913
5914impl<'a> Relative<'a> {
5915 /// Adds the given span to this relative datetime.
5916 ///
5917 /// This defers to either [`DateTime::checked_add`] or
5918 /// [`Zoned::checked_add`], depending on the type of relative datetime.
5919 ///
5920 /// The `Relative` datetime returned is guaranteed to have the same
5921 /// internal datetie type as `self`.
5922 ///
5923 /// # Errors
5924 ///
5925 /// This returns an error in the same cases as the underlying checked
5926 /// arithmetic APIs. In general, this occurs when adding the given `span`
5927 /// would result in overflow.
5928 fn checked_add(&self, span: Span) -> Result<Relative, Error> {
5929 match *self {
5930 Relative::Civil(dt) => Ok(Relative::Civil(dt.checked_add(span)?)),
5931 Relative::Zoned(ref zdt) => {
5932 Ok(Relative::Zoned(zdt.checked_add(span)?))
5933 }
5934 }
5935 }
5936
5937 fn checked_add_duration(
5938 &self,
5939 duration: SignedDuration,
5940 ) -> Result<Relative, Error> {
5941 match *self {
5942 Relative::Civil(dt) => {
5943 Ok(Relative::Civil(dt.checked_add_duration(duration)?))
5944 }
5945 Relative::Zoned(ref zdt) => {
5946 Ok(Relative::Zoned(zdt.checked_add_duration(duration)?))
5947 }
5948 }
5949 }
5950
5951 /// Returns the span of time from this relative datetime to the one given,
5952 /// with units as large as `largest`.
5953 ///
5954 /// # Errors
5955 ///
5956 /// This returns an error in the same cases as when the underlying
5957 /// [`DateTime::until`] or [`Zoned::until`] fail. Because this doesn't
5958 /// set or expose any rounding configuration, this can generally only
5959 /// occur when `largest` is `Unit::Nanosecond` and the span of time
5960 /// between `self` and `other` is too big to represent as a 64-bit integer
5961 /// nanosecond count.
5962 ///
5963 /// # Panics
5964 ///
5965 /// This panics if `self` and `other` are different internal datetime
5966 /// types. For example, if `self` was a civil datetime and `other` were
5967 /// a zoned datetime.
5968 fn until(&self, largest: Unit, other: &Relative) -> Result<Span, Error> {
5969 match (self, other) {
5970 (&Relative::Civil(ref dt1), &Relative::Civil(ref dt2)) => {
5971 dt1.until(largest, dt2)
5972 }
5973 (&Relative::Zoned(ref zdt1), &Relative::Zoned(ref zdt2)) => {
5974 zdt1.until(largest, zdt2)
5975 }
5976 // This would be bad if `Relative` were a public API, but in
5977 // practice, this case never occurs because we don't mixup our
5978 // `Relative` datetime types.
5979 _ => unreachable!(),
5980 }
5981 }
5982
5983 /// Converts this relative datetime to a nanosecond in UTC time.
5984 ///
5985 /// # Errors
5986 ///
5987 /// If there was a problem doing this conversion, then an error is
5988 /// returned. In practice, this only occurs for a civil datetime near the
5989 /// civil datetime minimum and maximum values.
5990 fn to_nanosecond(&self) -> NoUnits128 {
5991 match *self {
5992 Relative::Civil(dt) => dt.timestamp.as_nanosecond_ranged().rinto(),
5993 Relative::Zoned(ref zdt) => {
5994 zdt.zoned.timestamp().as_nanosecond_ranged().rinto()
5995 }
5996 }
5997 }
5998
5999 /// Create a balanced span of time relative to this datetime.
6000 ///
6001 /// The relative span returned has the same internal datetime type
6002 /// (civil or zoned) as this relative datetime.
6003 ///
6004 /// # Errors
6005 ///
6006 /// This returns an error when the span in this range cannot be
6007 /// represented. In general, this only occurs when asking for largest units
6008 /// of `Unit::Nanosecond` *and* when the span is too big to fit into a
6009 /// 64-bit nanosecond count.
6010 ///
6011 /// This can also return an error in other extreme cases, such as when
6012 /// adding the given span to this relative datetime results in overflow,
6013 /// or if this relative datetime is a civil datetime and it couldn't be
6014 /// converted to a timestamp in UTC.
6015 fn into_relative_span(
6016 self,
6017 largest: Unit,
6018 span: Span,
6019 ) -> Result<RelativeSpan<'a>, Error> {
6020 let kind = match self {
6021 Relative::Civil(start) => {
6022 let end = start.checked_add(span)?;
6023 RelativeSpanKind::Civil { start, end }
6024 }
6025 Relative::Zoned(start) => {
6026 let end = start.checked_add(span)?;
6027 RelativeSpanKind::Zoned { start, end }
6028 }
6029 };
6030 let relspan = kind.into_relative_span(largest)?;
6031 if span.get_sign_ranged() != 0
6032 && relspan.span.get_sign_ranged() != 0
6033 && span.get_sign_ranged() != relspan.span.get_sign_ranged()
6034 {
6035 // I haven't quite figured out when this case is hit. I think it's
6036 // actually impossible right? Balancing a duration should not flip
6037 // the sign.
6038 //
6039 // ref: https://github.com/fullcalendar/temporal-polyfill/blob/9e001042864394247181d1a5d591c18057ce32d2/packages/temporal-polyfill/src/internal/durationMath.ts#L236-L238
6040 unreachable!(
6041 "balanced span should have same sign as original span"
6042 )
6043 }
6044 Ok(relspan)
6045 }
6046
6047 /// Rounds the given span using the given rounding configuration.
6048 fn round(
6049 self,
6050 span: Span,
6051 smallest: Unit,
6052 largest: Unit,
6053 increment: NoUnits128,
6054 mode: RoundMode,
6055 ) -> Result<Span, Error> {
6056 let relspan = self.into_relative_span(largest, span)?;
6057 if relspan.span.get_sign_ranged() == 0 {
6058 return Ok(relspan.span);
6059 }
6060 let nudge = match relspan.kind {
6061 RelativeSpanKind::Civil { start, end } => {
6062 if smallest > Unit::Day {
6063 Nudge::relative_calendar(
6064 relspan.span,
6065 &Relative::Civil(start),
6066 &Relative::Civil(end),
6067 smallest,
6068 increment,
6069 mode,
6070 )?
6071 } else {
6072 let relative_end = end.timestamp.as_nanosecond_ranged();
6073 Nudge::relative_invariant(
6074 relspan.span,
6075 relative_end.rinto(),
6076 smallest,
6077 largest,
6078 increment,
6079 mode,
6080 )?
6081 }
6082 }
6083 RelativeSpanKind::Zoned { ref start, ref end } => {
6084 if smallest >= Unit::Day {
6085 Nudge::relative_calendar(
6086 relspan.span,
6087 // FIXME: Find a way to drop these clones.
6088 &Relative::Zoned(start.clone()),
6089 &Relative::Zoned(end.clone()),
6090 smallest,
6091 increment,
6092 mode,
6093 )?
6094 } else if largest >= Unit::Day {
6095 // This is a special case for zoned datetimes when rounding
6096 // could bleed into variable units.
6097 Nudge::relative_zoned_time(
6098 relspan.span,
6099 start,
6100 smallest,
6101 increment,
6102 mode,
6103 )?
6104 } else {
6105 // Otherwise, rounding is the same as civil datetime.
6106 let relative_end =
6107 end.zoned.timestamp().as_nanosecond_ranged();
6108 Nudge::relative_invariant(
6109 relspan.span,
6110 relative_end.rinto(),
6111 smallest,
6112 largest,
6113 increment,
6114 mode,
6115 )?
6116 }
6117 }
6118 };
6119 nudge.bubble(&relspan, smallest, largest)
6120 }
6121}
6122
6123/// A balanced span between a range of civil or zoned datetimes.
6124///
6125/// The span is always balanced up to a certain unit as given to
6126/// `RelativeSpanKind::into_relative_span`.
6127#[derive(Clone, Debug)]
6128struct RelativeSpan<'a> {
6129 span: Span,
6130 kind: RelativeSpanKind<'a>,
6131}
6132
6133/// A civil or zoned datetime range of time.
6134#[derive(Clone, Debug)]
6135enum RelativeSpanKind<'a> {
6136 Civil { start: RelativeCivil, end: RelativeCivil },
6137 Zoned { start: RelativeZoned<'a>, end: RelativeZoned<'a> },
6138}
6139
6140impl<'a> RelativeSpanKind<'a> {
6141 /// Create a balanced `RelativeSpan` from this range of time.
6142 ///
6143 /// # Errors
6144 ///
6145 /// This returns an error when the span in this range cannot be
6146 /// represented. In general, this only occurs when asking for largest units
6147 /// of `Unit::Nanosecond` *and* when the span is too big to fit into a
6148 /// 64-bit nanosecond count.
6149 fn into_relative_span(
6150 self,
6151 largest: Unit,
6152 ) -> Result<RelativeSpan<'a>, Error> {
6153 let span = match self {
6154 RelativeSpanKind::Civil { ref start, ref end } => start
6155 .datetime
6156 .until((largest, end.datetime))
6157 .with_context(|| {
6158 err!(
6159 "failed to get span between {start} and {end} \
6160 with largest unit as {unit}",
6161 start = start.datetime,
6162 end = end.datetime,
6163 unit = largest.plural(),
6164 )
6165 })?,
6166 RelativeSpanKind::Zoned { ref start, ref end } => start
6167 .zoned
6168 .until((largest, &*end.zoned))
6169 .with_context(|| {
6170 err!(
6171 "failed to get span between {start} and {end} \
6172 with largest unit as {unit}",
6173 start = start.zoned,
6174 end = end.zoned,
6175 unit = largest.plural(),
6176 )
6177 })?,
6178 };
6179 Ok(RelativeSpan { span, kind: self })
6180 }
6181}
6182
6183/// A wrapper around a civil datetime and a timestamp corresponding to that
6184/// civil datetime in UTC.
6185///
6186/// Haphazardly interpreting a civil datetime in UTC is an odd and *usually*
6187/// incorrect thing to do. But the way we use it here is basically just to give
6188/// it an "anchoring" point such that we can represent it using a single
6189/// integer for rounding purposes. It is only used in a context *relative* to
6190/// another civil datetime interpreted in UTC. In this fashion, the selection
6191/// of UTC specifically doesn't really matter. We could use any time zone.
6192/// (Although, it must be a time zone without any transitions, otherwise we
6193/// could wind up with time zone aware results in a context where that would
6194/// be unexpected since this is civil time.)
6195#[derive(Clone, Copy, Debug)]
6196struct RelativeCivil {
6197 datetime: DateTime,
6198 timestamp: Timestamp,
6199}
6200
6201impl RelativeCivil {
6202 /// Creates a new relative wrapper around the given civil datetime.
6203 ///
6204 /// This wrapper bundles a timestamp for the given datetime by interpreting
6205 /// it as being in UTC. This is an "odd" thing to do, but it's only used
6206 /// in the context of determining the length of time between two civil
6207 /// datetimes. So technically, any time zone without transitions could be
6208 /// used.
6209 ///
6210 /// # Errors
6211 ///
6212 /// This returns an error if the datetime could not be converted to a
6213 /// timestamp. This only occurs near the minimum and maximum civil datetime
6214 /// values.
6215 fn new(datetime: DateTime) -> Result<RelativeCivil, Error> {
6216 let timestamp = datetime
6217 .to_zoned(TimeZone::UTC)
6218 .with_context(|| {
6219 err!("failed to convert {datetime} to timestamp")
6220 })?
6221 .timestamp();
6222 Ok(RelativeCivil { datetime, timestamp })
6223 }
6224
6225 /// Returns the result of [`DateTime::checked_add`].
6226 ///
6227 /// # Errors
6228 ///
6229 /// Returns an error in the same cases as `DateTime::checked_add`. That is,
6230 /// when adding the span to this zoned datetime would overflow.
6231 ///
6232 /// This also returns an error if the resulting datetime could not be
6233 /// converted to a timestamp in UTC. This only occurs near the minimum and
6234 /// maximum datetime values.
6235 fn checked_add(&self, span: Span) -> Result<RelativeCivil, Error> {
6236 let datetime = self.datetime.checked_add(span).with_context(|| {
6237 err!("failed to add {span} to {dt}", dt = self.datetime)
6238 })?;
6239 let timestamp = datetime
6240 .to_zoned(TimeZone::UTC)
6241 .with_context(|| {
6242 err!("failed to convert {datetime} to timestamp")
6243 })?
6244 .timestamp();
6245 Ok(RelativeCivil { datetime, timestamp })
6246 }
6247
6248 /// Returns the result of [`DateTime::checked_add`] with an absolute
6249 /// duration.
6250 ///
6251 /// # Errors
6252 ///
6253 /// Returns an error in the same cases as `DateTime::checked_add`. That is,
6254 /// when adding the span to this zoned datetime would overflow.
6255 ///
6256 /// This also returns an error if the resulting datetime could not be
6257 /// converted to a timestamp in UTC. This only occurs near the minimum and
6258 /// maximum datetime values.
6259 fn checked_add_duration(
6260 &self,
6261 duration: SignedDuration,
6262 ) -> Result<RelativeCivil, Error> {
6263 let datetime =
6264 self.datetime.checked_add(duration).with_context(|| {
6265 err!("failed to add {duration:?} to {dt}", dt = self.datetime)
6266 })?;
6267 let timestamp = datetime
6268 .to_zoned(TimeZone::UTC)
6269 .with_context(|| {
6270 err!("failed to convert {datetime} to timestamp")
6271 })?
6272 .timestamp();
6273 Ok(RelativeCivil { datetime, timestamp })
6274 }
6275
6276 /// Returns the result of [`DateTime::until`].
6277 ///
6278 /// # Errors
6279 ///
6280 /// Returns an error in the same cases as `DateTime::until`. That is, when
6281 /// the span for the given largest unit cannot be represented. This can
6282 /// generally only happen when `largest` is `Unit::Nanosecond` and the span
6283 /// cannot be represented as a 64-bit integer of nanoseconds.
6284 fn until(
6285 &self,
6286 largest: Unit,
6287 other: &RelativeCivil,
6288 ) -> Result<Span, Error> {
6289 self.datetime.until((largest, other.datetime)).with_context(|| {
6290 err!(
6291 "failed to get span between {dt1} and {dt2} \
6292 with largest unit as {unit}",
6293 unit = largest.plural(),
6294 dt1 = self.datetime,
6295 dt2 = other.datetime,
6296 )
6297 })
6298 }
6299}
6300
6301/// A simple wrapper around a possibly borrowed `Zoned`.
6302#[derive(Clone, Debug)]
6303struct RelativeZoned<'a> {
6304 zoned: DumbCow<'a, Zoned>,
6305}
6306
6307impl<'a> RelativeZoned<'a> {
6308 /// Returns the result of [`Zoned::checked_add`].
6309 ///
6310 /// # Errors
6311 ///
6312 /// Returns an error in the same cases as `Zoned::checked_add`. That is,
6313 /// when adding the span to this zoned datetime would overflow.
6314 fn checked_add(
6315 &self,
6316 span: Span,
6317 ) -> Result<RelativeZoned<'static>, Error> {
6318 let zoned = self.zoned.checked_add(span).with_context(|| {
6319 err!("failed to add {span} to {zoned}", zoned = self.zoned)
6320 })?;
6321 Ok(RelativeZoned { zoned: DumbCow::Owned(zoned) })
6322 }
6323
6324 /// Returns the result of [`Zoned::checked_add`] with an absolute duration.
6325 ///
6326 /// # Errors
6327 ///
6328 /// Returns an error in the same cases as `Zoned::checked_add`. That is,
6329 /// when adding the span to this zoned datetime would overflow.
6330 fn checked_add_duration(
6331 &self,
6332 duration: SignedDuration,
6333 ) -> Result<RelativeZoned<'static>, Error> {
6334 let zoned = self.zoned.checked_add(duration).with_context(|| {
6335 err!("failed to add {duration:?} to {zoned}", zoned = self.zoned)
6336 })?;
6337 Ok(RelativeZoned { zoned: DumbCow::Owned(zoned) })
6338 }
6339
6340 /// Returns the result of [`Zoned::until`].
6341 ///
6342 /// # Errors
6343 ///
6344 /// Returns an error in the same cases as `Zoned::until`. That is, when
6345 /// the span for the given largest unit cannot be represented. This can
6346 /// generally only happen when `largest` is `Unit::Nanosecond` and the span
6347 /// cannot be represented as a 64-bit integer of nanoseconds.
6348 fn until(
6349 &self,
6350 largest: Unit,
6351 other: &RelativeZoned<'a>,
6352 ) -> Result<Span, Error> {
6353 self.zoned.until((largest, &*other.zoned)).with_context(|| {
6354 err!(
6355 "failed to get span between {zdt1} and {zdt2} \
6356 with largest unit as {unit}",
6357 unit = largest.plural(),
6358 zdt1 = self.zoned,
6359 zdt2 = other.zoned,
6360 )
6361 })
6362 }
6363}
6364
6365// The code below is the "core" rounding logic for spans. It was greatly
6366// inspired by this gist[1] and the fullcalendar Temporal polyfill[2]. In
6367// particular, the algorithm implemented below is a major simplification from
6368// how Temporal used to work[3]. Parts of it are still in rough and unclear
6369// shape IMO.
6370//
6371// [1]: https://gist.github.com/arshaw/36d3152c21482bcb78ea2c69591b20e0
6372// [2]: https://github.com/fullcalendar/temporal-polyfill
6373// [3]: https://github.com/tc39/proposal-temporal/issues/2792
6374
6375/// The result of a span rounding strategy. There are three:
6376///
6377/// * Rounding spans relative to civil datetimes using only invariant
6378/// units (days or less). This is achieved by converting the span to a simple
6379/// integer number of nanoseconds and then rounding that.
6380/// * Rounding spans relative to either a civil datetime or a zoned datetime
6381/// where rounding might involve changing non-uniform units. That is, when
6382/// the smallest unit is greater than days for civil datetimes and greater
6383/// than hours for zoned datetimes.
6384/// * Rounding spans relative to a zoned datetime whose smallest unit is
6385/// less than days.
6386///
6387/// Each of these might produce a bottom heavy span that needs to be
6388/// re-balanced. This type represents that result via one of three constructors
6389/// corresponding to each of the above strategies, and then provides a routine
6390/// for rebalancing via "bubbling."
6391#[derive(Debug)]
6392struct Nudge {
6393 /// A possibly bottom heavy rounded span.
6394 span: Span,
6395 /// The nanosecond timestamp corresponding to `relative + span`, where
6396 /// `span` is the (possibly bottom heavy) rounded span.
6397 rounded_relative_end: NoUnits128,
6398 /// Whether rounding may have created a bottom heavy span such that a
6399 /// calendar unit might need to be incremented after re-balancing smaller
6400 /// units.
6401 grew_big_unit: bool,
6402}
6403
6404impl Nudge {
6405 /// Performs rounding on the given span limited to invariant units.
6406 ///
6407 /// For civil datetimes, this means the smallest unit must be days or less,
6408 /// but the largest unit can be bigger. For zoned datetimes, this means
6409 /// that *both* the largest and smallest unit must be hours or less. This
6410 /// is because zoned datetimes with rounding that can spill up to days
6411 /// requires special handling.
6412 ///
6413 /// It works by converting the span to a single integer number of
6414 /// nanoseconds, rounding it and then converting back to a span.
6415 fn relative_invariant(
6416 balanced: Span,
6417 relative_end: NoUnits128,
6418 smallest: Unit,
6419 largest: Unit,
6420 increment: NoUnits128,
6421 mode: RoundMode,
6422 ) -> Result<Nudge, Error> {
6423 // Ensures this is only called when rounding invariant units.
6424 assert!(smallest <= Unit::Week);
6425
6426 let sign = balanced.get_sign_ranged();
6427 let balanced_nanos = balanced.to_invariant_nanoseconds();
6428 let rounded_nanos = mode.round_by_unit_in_nanoseconds(
6429 balanced_nanos,
6430 smallest,
6431 increment,
6432 );
6433 let span = Span::from_invariant_nanoseconds(largest, rounded_nanos)
6434 .with_context(|| {
6435 err!(
6436 "failed to convert rounded nanoseconds {rounded_nanos} \
6437 to span for largest unit as {unit}",
6438 unit = largest.plural(),
6439 )
6440 })?
6441 .years_ranged(balanced.get_years_ranged())
6442 .months_ranged(balanced.get_months_ranged())
6443 .weeks_ranged(balanced.get_weeks_ranged());
6444
6445 let diff_nanos = rounded_nanos - balanced_nanos;
6446 let diff_days = rounded_nanos.div_ceil(t::NANOS_PER_CIVIL_DAY)
6447 - balanced_nanos.div_ceil(t::NANOS_PER_CIVIL_DAY);
6448 let grew_big_unit = diff_days.signum() == sign;
6449 let rounded_relative_end = relative_end + diff_nanos;
6450 Ok(Nudge { span, rounded_relative_end, grew_big_unit })
6451 }
6452
6453 /// Performs rounding on the given span where the smallest unit configured
6454 /// implies that rounding will cover calendar or "non-uniform" units. (That
6455 /// is, units whose length can change based on the relative datetime.)
6456 fn relative_calendar(
6457 balanced: Span,
6458 relative_start: &Relative<'_>,
6459 relative_end: &Relative<'_>,
6460 smallest: Unit,
6461 increment: NoUnits128,
6462 mode: RoundMode,
6463 ) -> Result<Nudge, Error> {
6464 #[cfg(not(feature = "std"))]
6465 use crate::util::libm::Float;
6466
6467 assert!(smallest >= Unit::Day);
6468 let sign = balanced.get_sign_ranged();
6469 let truncated = increment
6470 * balanced.get_units_ranged(smallest).div_ceil(increment);
6471 let span = balanced
6472 .without_lower(smallest)
6473 .try_units_ranged(smallest, truncated)
6474 .with_context(|| {
6475 err!(
6476 "failed to set {unit} to {truncated} on span {balanced}",
6477 unit = smallest.singular()
6478 )
6479 })?;
6480 let (relative0, relative1) = clamp_relative_span(
6481 relative_start,
6482 span,
6483 smallest,
6484 NoUnits::try_rfrom("increment", increment)?
6485 .try_checked_mul("signed increment", sign)?,
6486 )?;
6487
6488 // FIXME: This is brutal. This is the only non-optional floating point
6489 // used so far in Jiff. We do expose floating point for things like
6490 // `Span::total`, but that's optional and not a core part of Jiff's
6491 // functionality. This is in the core part of Jiff's span rounding...
6492 let denom = (relative1 - relative0).get() as f64;
6493 let numer = (relative_end.to_nanosecond() - relative0).get() as f64;
6494 let exact = (truncated.get() as f64)
6495 + (numer / denom) * (sign.get() as f64) * (increment.get() as f64);
6496 let rounded = mode.round_float(exact, increment);
6497 let grew_big_unit =
6498 ((rounded.get() as f64) - exact).signum() == (sign.get() as f64);
6499
6500 let span =
6501 span.try_units_ranged(smallest, rounded).with_context(|| {
6502 err!(
6503 "failed to set {unit} to {truncated} on span {span}",
6504 unit = smallest.singular()
6505 )
6506 })?;
6507 let rounded_relative_end =
6508 if grew_big_unit { relative1 } else { relative0 };
6509 Ok(Nudge { span, rounded_relative_end, grew_big_unit })
6510 }
6511
6512 /// Performs rounding on the given span where the smallest unit is hours
6513 /// or less *and* the relative datetime is time zone aware.
6514 fn relative_zoned_time(
6515 balanced: Span,
6516 relative_start: &RelativeZoned<'_>,
6517 smallest: Unit,
6518 increment: NoUnits128,
6519 mode: RoundMode,
6520 ) -> Result<Nudge, Error> {
6521 let sign = balanced.get_sign_ranged();
6522 let time_nanos =
6523 balanced.only_lower(Unit::Day).to_invariant_nanoseconds();
6524 let mut rounded_time_nanos =
6525 mode.round_by_unit_in_nanoseconds(time_nanos, smallest, increment);
6526 let (relative0, relative1) = clamp_relative_span(
6527 // FIXME: Find a way to drop this clone.
6528 &Relative::Zoned(relative_start.clone()),
6529 balanced.without_lower(Unit::Day),
6530 Unit::Day,
6531 sign.rinto(),
6532 )?;
6533 let day_nanos = relative1 - relative0;
6534 let beyond_day_nanos = rounded_time_nanos - day_nanos;
6535
6536 let mut day_delta = NoUnits::N::<0>();
6537 let rounded_relative_end =
6538 if beyond_day_nanos == 0 || beyond_day_nanos.signum() == sign {
6539 day_delta += C(1);
6540 rounded_time_nanos = mode.round_by_unit_in_nanoseconds(
6541 beyond_day_nanos,
6542 smallest,
6543 increment,
6544 );
6545 relative1 + rounded_time_nanos
6546 } else {
6547 relative0 + rounded_time_nanos
6548 };
6549
6550 let span =
6551 Span::from_invariant_nanoseconds(Unit::Hour, rounded_time_nanos)
6552 .with_context(|| {
6553 err!(
6554 "failed to convert rounded nanoseconds \
6555 {rounded_time_nanos} to span for largest unit as {unit}",
6556 unit = Unit::Hour.plural(),
6557 )
6558 })?
6559 .years_ranged(balanced.get_years_ranged())
6560 .months_ranged(balanced.get_months_ranged())
6561 .weeks_ranged(balanced.get_weeks_ranged())
6562 .days_ranged(balanced.get_days_ranged() + day_delta);
6563 let grew_big_unit = day_delta != 0;
6564 Ok(Nudge { span, rounded_relative_end, grew_big_unit })
6565 }
6566
6567 /// This "bubbles" up the units in a potentially "bottom heavy" span to
6568 /// larger units. For example, P1m50d relative to March 1 is bottom heavy.
6569 /// This routine will bubble the days up to months to get P2m19d.
6570 ///
6571 /// # Errors
6572 ///
6573 /// This routine fails if any arithmetic on the individual units fails, or
6574 /// when span arithmetic on the relative datetime given fails.
6575 fn bubble(
6576 &self,
6577 relative: &RelativeSpan,
6578 smallest: Unit,
6579 largest: Unit,
6580 ) -> Result<Span, Error> {
6581 if !self.grew_big_unit || smallest == Unit::Week {
6582 return Ok(self.span);
6583 }
6584
6585 let smallest = smallest.max(Unit::Day);
6586 let mut balanced = self.span;
6587 let sign = balanced.get_sign_ranged();
6588 let mut unit = smallest;
6589 while let Some(u) = unit.next() {
6590 unit = u;
6591 if unit > largest {
6592 break;
6593 }
6594 // We only bubble smaller units up into weeks when the largest unit
6595 // is explicitly set to weeks. Otherwise, we leave it as-is.
6596 if unit == Unit::Week && largest != Unit::Week {
6597 continue;
6598 }
6599
6600 let span_start = balanced.without_lower(unit);
6601 let new_units = span_start
6602 .get_units_ranged(unit)
6603 .try_checked_add("bubble-units", sign)
6604 .with_context(|| {
6605 err!(
6606 "failed to add sign {sign} to {unit} value {value}",
6607 unit = unit.plural(),
6608 value = span_start.get_units_ranged(unit),
6609 )
6610 })?;
6611 let span_end = span_start
6612 .try_units_ranged(unit, new_units)
6613 .with_context(|| {
6614 err!(
6615 "failed to set {unit} to value \
6616 {new_units} on span {span_start}",
6617 unit = unit.plural(),
6618 )
6619 })?;
6620 let threshold = match relative.kind {
6621 RelativeSpanKind::Civil { ref start, .. } => {
6622 start.checked_add(span_end)?.timestamp
6623 }
6624 RelativeSpanKind::Zoned { ref start, .. } => {
6625 start.checked_add(span_end)?.zoned.timestamp()
6626 }
6627 };
6628 let beyond =
6629 self.rounded_relative_end - threshold.as_nanosecond_ranged();
6630 if beyond == 0 || beyond.signum() == sign {
6631 balanced = span_end;
6632 } else {
6633 break;
6634 }
6635 }
6636 Ok(balanced)
6637 }
6638}
6639
6640/// Rounds a span consisting of only invariant units.
6641///
6642/// This only applies when the max of the units in the span being rounded,
6643/// the largest configured unit and the smallest configured unit are all
6644/// invariant. That is, days or lower for spans without a relative datetime or
6645/// a relative civil datetime, and hours or lower for spans with a relative
6646/// zoned datetime.
6647///
6648/// All we do here is convert the span to an integer number of nanoseconds,
6649/// round that and then convert back. There aren't any tricky corner cases to
6650/// consider here.
6651fn round_span_invariant(
6652 span: Span,
6653 smallest: Unit,
6654 largest: Unit,
6655 increment: NoUnits128,
6656 mode: RoundMode,
6657) -> Result<Span, Error> {
6658 assert!(smallest <= Unit::Week);
6659 assert!(largest <= Unit::Week);
6660 let nanos = span.to_invariant_nanoseconds();
6661 let rounded =
6662 mode.round_by_unit_in_nanoseconds(nanos, smallest, increment);
6663 Span::from_invariant_nanoseconds(largest, rounded).with_context(|| {
6664 err!(
6665 "failed to convert rounded nanoseconds {rounded} \
6666 to span for largest unit as {unit}",
6667 unit = largest.plural(),
6668 )
6669 })
6670}
6671
6672/// Returns the nanosecond timestamps of `relative + span` and `relative +
6673/// {amount of unit} + span`.
6674///
6675/// This is useful for determining the actual length, in nanoseconds, of some
6676/// unit amount (usually a single unit). Usually, this is called with a span
6677/// whose units lower than `unit` are zeroed out and with an `amount` that
6678/// is `-1` or `1` or `0`. So for example, if `unit` were `Unit::Day`, then
6679/// you'd get back two nanosecond timestamps relative to the relative datetime
6680/// given that start exactly "one day" apart. (Which might be different than 24
6681/// hours, depending on the time zone.)
6682///
6683/// # Errors
6684///
6685/// This returns an error if adding the units overflows, or if doing the span
6686/// arithmetic on `relative` overflows.
6687fn clamp_relative_span(
6688 relative: &Relative<'_>,
6689 span: Span,
6690 unit: Unit,
6691 amount: NoUnits,
6692) -> Result<(NoUnits128, NoUnits128), Error> {
6693 let amount = span
6694 .get_units_ranged(unit)
6695 .try_checked_add("clamp-units", amount)
6696 .with_context(|| {
6697 err!(
6698 "failed to add {amount} to {unit} \
6699 value {value} on span {span}",
6700 unit = unit.plural(),
6701 value = span.get_units_ranged(unit),
6702 )
6703 })?;
6704 let span_amount =
6705 span.try_units_ranged(unit, amount).with_context(|| {
6706 err!(
6707 "failed to set {unit} unit to {amount} on span {span}",
6708 unit = unit.plural(),
6709 )
6710 })?;
6711 let relative0 = relative.checked_add(span)?.to_nanosecond();
6712 let relative1 = relative.checked_add(span_amount)?.to_nanosecond();
6713 Ok((relative0, relative1))
6714}
6715
6716/// A common parsing function that works in bytes.
6717///
6718/// Specifically, this parses either an ISO 8601 duration into a `Span` or
6719/// a "friendly" duration into a `Span`. It also tries to give decent error
6720/// messages.
6721///
6722/// This works because the friendly and ISO 8601 formats have non-overlapping
6723/// prefixes. Both can start with a `+` or `-`, but aside from that, an ISO
6724/// 8601 duration _always_ has to start with a `P` or `p`. We can utilize this
6725/// property to very quickly determine how to parse the input. We just need to
6726/// handle the possibly ambiguous case with a leading sign a little carefully
6727/// in order to ensure good error messages.
6728///
6729/// (We do the same thing for `SignedDuration`.)
6730#[inline(always)]
6731fn parse_iso_or_friendly(bytes: &[u8]) -> Result<Span, Error> {
6732 if bytes.is_empty() {
6733 return Err(err!(
6734 "an empty string is not a valid `Span`, \
6735 expected either a ISO 8601 or Jiff's 'friendly' \
6736 format",
6737 ));
6738 }
6739 let mut first = bytes[0];
6740 if first == b'+' || first == b'-' {
6741 if bytes.len() == 1 {
6742 return Err(err!(
6743 "found nothing after sign `{sign}`, \
6744 which is not a valid `Span`, \
6745 expected either a ISO 8601 or Jiff's 'friendly' \
6746 format",
6747 sign = escape::Byte(first),
6748 ));
6749 }
6750 first = bytes[1];
6751 }
6752 if first == b'P' || first == b'p' {
6753 temporal::DEFAULT_SPAN_PARSER.parse_span(bytes)
6754 } else {
6755 friendly::DEFAULT_SPAN_PARSER.parse_span(bytes)
6756 }
6757}
6758
6759fn requires_relative_date_err(unit: Unit) -> Result<(), Error> {
6760 if unit.is_variable() {
6761 return Err(if matches!(unit, Unit::Week | Unit::Day) {
6762 err!(
6763 "using unit '{unit}' in a span or configuration \
6764 requires that either a relative reference time be given \
6765 or `SpanRelativeTo::days_are_24_hours()` is used to \
6766 indicate invariant 24-hour days, \
6767 but neither were provided",
6768 unit = unit.singular(),
6769 )
6770 } else {
6771 err!(
6772 "using unit '{unit}' in a span or configuration \
6773 requires that a relative reference time be given, \
6774 but none was provided",
6775 unit = unit.singular(),
6776 )
6777 });
6778 }
6779 Ok(())
6780}
6781
6782#[cfg(test)]
6783mod tests {
6784 use std::io::Cursor;
6785
6786 use alloc::string::ToString;
6787
6788 use crate::{civil::date, RoundMode};
6789
6790 use super::*;
6791
6792 #[test]
6793 fn test_total() {
6794 if crate::tz::db().is_definitively_empty() {
6795 return;
6796 }
6797
6798 let span = 130.hours().minutes(20);
6799 let total = span.total(Unit::Second).unwrap();
6800 assert_eq!(total, 469200.0);
6801
6802 let span = 123456789.seconds();
6803 let total = span
6804 .total(SpanTotal::from(Unit::Day).days_are_24_hours())
6805 .unwrap();
6806 assert_eq!(total, 1428.8980208333332);
6807
6808 let span = 2756.hours();
6809 let dt = date(2020, 1, 1).at(0, 0, 0, 0);
6810 let zdt = dt.in_tz("Europe/Rome").unwrap();
6811 let total = span.total((Unit::Month, &zdt)).unwrap();
6812 assert_eq!(total, 3.7958333333333334);
6813 let total = span.total((Unit::Month, dt)).unwrap();
6814 assert_eq!(total, 3.7944444444444443);
6815 }
6816
6817 #[test]
6818 fn test_compare() {
6819 if crate::tz::db().is_definitively_empty() {
6820 return;
6821 }
6822
6823 let span1 = 79.hours().minutes(10);
6824 let span2 = 79.hours().seconds(630);
6825 let span3 = 78.hours().minutes(50);
6826 let mut array = [span1, span2, span3];
6827 array.sort_by(|sp1, sp2| sp1.compare(sp2).unwrap());
6828 assert_eq!(array, [span3, span1, span2].map(SpanFieldwise));
6829
6830 let day24 = SpanRelativeTo::days_are_24_hours();
6831 let span1 = 79.hours().minutes(10);
6832 let span2 = 3.days().hours(7).seconds(630);
6833 let span3 = 3.days().hours(6).minutes(50);
6834 let mut array = [span1, span2, span3];
6835 array.sort_by(|sp1, sp2| sp1.compare((sp2, day24)).unwrap());
6836 assert_eq!(array, [span3, span1, span2].map(SpanFieldwise));
6837
6838 let dt = date(2020, 11, 1).at(0, 0, 0, 0);
6839 let zdt = dt.in_tz("America/Los_Angeles").unwrap();
6840 array.sort_by(|sp1, sp2| sp1.compare((sp2, &zdt)).unwrap());
6841 assert_eq!(array, [span1, span3, span2].map(SpanFieldwise));
6842 }
6843
6844 #[test]
6845 fn test_checked_add() {
6846 let span1 = 1.hour();
6847 let span2 = 30.minutes();
6848 let sum = span1.checked_add(span2).unwrap();
6849 span_eq!(sum, 1.hour().minutes(30));
6850
6851 let span1 = 1.hour().minutes(30);
6852 let span2 = 2.hours().minutes(45);
6853 let sum = span1.checked_add(span2).unwrap();
6854 span_eq!(sum, 4.hours().minutes(15));
6855
6856 let span = 50
6857 .years()
6858 .months(50)
6859 .days(50)
6860 .hours(50)
6861 .minutes(50)
6862 .seconds(50)
6863 .milliseconds(500)
6864 .microseconds(500)
6865 .nanoseconds(500);
6866 let relative = date(1900, 1, 1).at(0, 0, 0, 0);
6867 let sum = span.checked_add((span, relative)).unwrap();
6868 let expected = 108
6869 .years()
6870 .months(7)
6871 .days(12)
6872 .hours(5)
6873 .minutes(41)
6874 .seconds(41)
6875 .milliseconds(1)
6876 .microseconds(1)
6877 .nanoseconds(0);
6878 span_eq!(sum, expected);
6879
6880 let span = 1.month().days(15);
6881 let relative = date(2000, 2, 1).at(0, 0, 0, 0);
6882 let sum = span.checked_add((span, relative)).unwrap();
6883 span_eq!(sum, 3.months());
6884 let relative = date(2000, 3, 1).at(0, 0, 0, 0);
6885 let sum = span.checked_add((span, relative)).unwrap();
6886 span_eq!(sum, 2.months().days(30));
6887 }
6888
6889 #[test]
6890 fn test_round_day_time() {
6891 let span = 29.seconds();
6892 let rounded = span.round(Unit::Minute).unwrap();
6893 span_eq!(rounded, 0.minute());
6894
6895 let span = 30.seconds();
6896 let rounded = span.round(Unit::Minute).unwrap();
6897 span_eq!(rounded, 1.minute());
6898
6899 let span = 8.seconds();
6900 let rounded = span
6901 .round(
6902 SpanRound::new()
6903 .smallest(Unit::Nanosecond)
6904 .largest(Unit::Microsecond),
6905 )
6906 .unwrap();
6907 span_eq!(rounded, 8_000_000.microseconds());
6908
6909 let span = 130.minutes();
6910 let rounded = span
6911 .round(SpanRound::new().largest(Unit::Day).days_are_24_hours())
6912 .unwrap();
6913 span_eq!(rounded, 2.hours().minutes(10));
6914
6915 let span = 10.minutes().seconds(52);
6916 let rounded = span.round(Unit::Minute).unwrap();
6917 span_eq!(rounded, 11.minutes());
6918
6919 let span = 10.minutes().seconds(52);
6920 let rounded = span
6921 .round(
6922 SpanRound::new().smallest(Unit::Minute).mode(RoundMode::Trunc),
6923 )
6924 .unwrap();
6925 span_eq!(rounded, 10.minutes());
6926
6927 let span = 2.hours().minutes(34).seconds(18);
6928 let rounded =
6929 span.round(SpanRound::new().largest(Unit::Second)).unwrap();
6930 span_eq!(rounded, 9258.seconds());
6931
6932 let span = 6.minutes();
6933 let rounded = span
6934 .round(
6935 SpanRound::new()
6936 .smallest(Unit::Minute)
6937 .increment(5)
6938 .mode(RoundMode::Ceil),
6939 )
6940 .unwrap();
6941 span_eq!(rounded, 10.minutes());
6942 }
6943
6944 #[test]
6945 fn test_round_relative_zoned_calendar() {
6946 if crate::tz::db().is_definitively_empty() {
6947 return;
6948 }
6949
6950 let span = 2756.hours();
6951 let relative =
6952 date(2020, 1, 1).at(0, 0, 0, 0).in_tz("America/New_York").unwrap();
6953 let options = SpanRound::new()
6954 .largest(Unit::Year)
6955 .smallest(Unit::Day)
6956 .relative(&relative);
6957 let rounded = span.round(options).unwrap();
6958 span_eq!(rounded, 3.months().days(24));
6959
6960 let span = 24.hours().nanoseconds(5);
6961 let relative = date(2000, 10, 29)
6962 .at(0, 0, 0, 0)
6963 .in_tz("America/Vancouver")
6964 .unwrap();
6965 let options = SpanRound::new()
6966 .largest(Unit::Day)
6967 .smallest(Unit::Minute)
6968 .relative(&relative)
6969 .mode(RoundMode::Expand)
6970 .increment(30);
6971 let rounded = span.round(options).unwrap();
6972 // It seems like this is the correct answer, although it apparently
6973 // differs from Temporal and the FullCalendar polyfill. I'm not sure
6974 // what accounts for the difference in the implementation.
6975 //
6976 // See: https://github.com/tc39/proposal-temporal/pull/2758#discussion_r1597255245
6977 span_eq!(rounded, 24.hours().minutes(30));
6978
6979 // Ref: https://github.com/tc39/proposal-temporal/issues/2816#issuecomment-2115608460
6980 let span = -1.month().hours(24);
6981 let relative: crate::Zoned = date(2024, 4, 11)
6982 .at(2, 0, 0, 0)
6983 .in_tz("America/New_York")
6984 .unwrap();
6985 let options =
6986 SpanRound::new().smallest(Unit::Millisecond).relative(&relative);
6987 let rounded = span.round(options).unwrap();
6988 span_eq!(rounded, -1.month().days(1).hours(1));
6989 let dt = relative.checked_add(span).unwrap();
6990 let diff = relative.until((Unit::Month, &dt)).unwrap();
6991 span_eq!(diff, -1.month().days(1).hours(1));
6992
6993 // Like the above, but don't use a datetime near a DST transition. In
6994 // this case, a day is a normal 24 hours. (Unlike above, where the
6995 // duration includes a 23 hour day, and so an additional hour has to be
6996 // added to the span to account for that.)
6997 let span = -1.month().hours(24);
6998 let relative = date(2024, 6, 11)
6999 .at(2, 0, 0, 0)
7000 .in_tz("America/New_York")
7001 .unwrap();
7002 let options =
7003 SpanRound::new().smallest(Unit::Millisecond).relative(&relative);
7004 let rounded = span.round(options).unwrap();
7005 span_eq!(rounded, -1.month().days(1));
7006 }
7007
7008 #[test]
7009 fn test_round_relative_zoned_time() {
7010 if crate::tz::db().is_definitively_empty() {
7011 return;
7012 }
7013
7014 let span = 2756.hours();
7015 let relative =
7016 date(2020, 1, 1).at(0, 0, 0, 0).in_tz("America/New_York").unwrap();
7017 let options = SpanRound::new().largest(Unit::Year).relative(&relative);
7018 let rounded = span.round(options).unwrap();
7019 span_eq!(rounded, 3.months().days(23).hours(21));
7020
7021 let span = 2756.hours();
7022 let relative =
7023 date(2020, 9, 1).at(0, 0, 0, 0).in_tz("America/New_York").unwrap();
7024 let options = SpanRound::new().largest(Unit::Year).relative(&relative);
7025 let rounded = span.round(options).unwrap();
7026 span_eq!(rounded, 3.months().days(23).hours(19));
7027
7028 let span = 3.hours();
7029 let relative =
7030 date(2020, 3, 8).at(0, 0, 0, 0).in_tz("America/New_York").unwrap();
7031 let options = SpanRound::new().largest(Unit::Year).relative(&relative);
7032 let rounded = span.round(options).unwrap();
7033 span_eq!(rounded, 3.hours());
7034 }
7035
7036 #[test]
7037 fn test_round_relative_day_time() {
7038 let span = 2756.hours();
7039 let options =
7040 SpanRound::new().largest(Unit::Year).relative(date(2020, 1, 1));
7041 let rounded = span.round(options).unwrap();
7042 span_eq!(rounded, 3.months().days(23).hours(20));
7043
7044 let span = 2756.hours();
7045 let options =
7046 SpanRound::new().largest(Unit::Year).relative(date(2020, 9, 1));
7047 let rounded = span.round(options).unwrap();
7048 span_eq!(rounded, 3.months().days(23).hours(20));
7049
7050 let span = 190.days();
7051 let options =
7052 SpanRound::new().largest(Unit::Year).relative(date(2020, 1, 1));
7053 let rounded = span.round(options).unwrap();
7054 span_eq!(rounded, 6.months().days(8));
7055
7056 let span = 30
7057 .days()
7058 .hours(23)
7059 .minutes(59)
7060 .seconds(59)
7061 .milliseconds(999)
7062 .microseconds(999)
7063 .nanoseconds(999);
7064 let options = SpanRound::new()
7065 .smallest(Unit::Microsecond)
7066 .largest(Unit::Year)
7067 .relative(date(2024, 5, 1));
7068 let rounded = span.round(options).unwrap();
7069 span_eq!(rounded, 1.month());
7070
7071 let span = 364
7072 .days()
7073 .hours(23)
7074 .minutes(59)
7075 .seconds(59)
7076 .milliseconds(999)
7077 .microseconds(999)
7078 .nanoseconds(999);
7079 let options = SpanRound::new()
7080 .smallest(Unit::Microsecond)
7081 .largest(Unit::Year)
7082 .relative(date(2023, 1, 1));
7083 let rounded = span.round(options).unwrap();
7084 span_eq!(rounded, 1.year());
7085
7086 let span = 365
7087 .days()
7088 .hours(23)
7089 .minutes(59)
7090 .seconds(59)
7091 .milliseconds(999)
7092 .microseconds(999)
7093 .nanoseconds(999);
7094 let options = SpanRound::new()
7095 .smallest(Unit::Microsecond)
7096 .largest(Unit::Year)
7097 .relative(date(2023, 1, 1));
7098 let rounded = span.round(options).unwrap();
7099 span_eq!(rounded, 1.year().days(1));
7100
7101 let span = 365
7102 .days()
7103 .hours(23)
7104 .minutes(59)
7105 .seconds(59)
7106 .milliseconds(999)
7107 .microseconds(999)
7108 .nanoseconds(999);
7109 let options = SpanRound::new()
7110 .smallest(Unit::Microsecond)
7111 .largest(Unit::Year)
7112 .relative(date(2024, 1, 1));
7113 let rounded = span.round(options).unwrap();
7114 span_eq!(rounded, 1.year());
7115
7116 let span = 3.hours();
7117 let options =
7118 SpanRound::new().largest(Unit::Year).relative(date(2020, 3, 8));
7119 let rounded = span.round(options).unwrap();
7120 span_eq!(rounded, 3.hours());
7121 }
7122
7123 #[test]
7124 fn span_sign() {
7125 assert_eq!(Span::new().get_sign_ranged(), 0);
7126 assert_eq!(Span::new().days(1).get_sign_ranged(), 1);
7127 assert_eq!(Span::new().days(-1).get_sign_ranged(), -1);
7128 assert_eq!(Span::new().days(1).days(0).get_sign_ranged(), 0);
7129 assert_eq!(Span::new().days(-1).days(0).get_sign_ranged(), 0);
7130 assert_eq!(Span::new().years(1).days(1).days(0).get_sign_ranged(), 1);
7131 assert_eq!(
7132 Span::new().years(-1).days(-1).days(0).get_sign_ranged(),
7133 -1
7134 );
7135 }
7136
7137 #[test]
7138 fn span_size() {
7139 #[cfg(target_pointer_width = "64")]
7140 {
7141 #[cfg(debug_assertions)]
7142 {
7143 assert_eq!(core::mem::align_of::<Span>(), 8);
7144 assert_eq!(core::mem::size_of::<Span>(), 184);
7145 }
7146 #[cfg(not(debug_assertions))]
7147 {
7148 assert_eq!(core::mem::align_of::<Span>(), 8);
7149 assert_eq!(core::mem::size_of::<Span>(), 64);
7150 }
7151 }
7152 }
7153
7154 quickcheck::quickcheck! {
7155 fn prop_roundtrip_span_nanoseconds(span: Span) -> quickcheck::TestResult {
7156 let largest = span.largest_unit();
7157 if largest > Unit::Day {
7158 return quickcheck::TestResult::discard();
7159 }
7160 let nanos = span.to_invariant_nanoseconds();
7161 let got = Span::from_invariant_nanoseconds(largest, nanos).unwrap();
7162 quickcheck::TestResult::from_bool(nanos == got.to_invariant_nanoseconds())
7163 }
7164 }
7165
7166 /// # `serde` deserializer compatibility test
7167 ///
7168 /// Serde YAML used to be unable to deserialize `jiff` types,
7169 /// as deserializing from bytes is not supported by the deserializer.
7170 ///
7171 /// - <https://github.com/BurntSushi/jiff/issues/138>
7172 /// - <https://github.com/BurntSushi/jiff/discussions/148>
7173 #[test]
7174 fn span_deserialize_yaml() {
7175 let expected = Span::new()
7176 .years(1)
7177 .months(2)
7178 .weeks(3)
7179 .days(4)
7180 .hours(5)
7181 .minutes(6)
7182 .seconds(7);
7183
7184 let deserialized: Span =
7185 serde_yaml::from_str("P1y2m3w4dT5h6m7s").unwrap();
7186
7187 span_eq!(deserialized, expected);
7188
7189 let deserialized: Span =
7190 serde_yaml::from_slice("P1y2m3w4dT5h6m7s".as_bytes()).unwrap();
7191
7192 span_eq!(deserialized, expected);
7193
7194 let cursor = Cursor::new(b"P1y2m3w4dT5h6m7s");
7195 let deserialized: Span = serde_yaml::from_reader(cursor).unwrap();
7196
7197 span_eq!(deserialized, expected);
7198 }
7199
7200 #[test]
7201 fn display() {
7202 let span = Span::new()
7203 .years(1)
7204 .months(2)
7205 .weeks(3)
7206 .days(4)
7207 .hours(5)
7208 .minutes(6)
7209 .seconds(7)
7210 .milliseconds(8)
7211 .microseconds(9)
7212 .nanoseconds(10);
7213 insta::assert_snapshot!(
7214 span,
7215 @"P1Y2M3W4DT5H6M7.00800901S",
7216 );
7217 insta::assert_snapshot!(
7218 alloc::format!("{span:#}"),
7219 @"1y 2mo 3w 4d 5h 6m 7s 8ms 9µs 10ns",
7220 );
7221 }
7222
7223 /// This test ensures that we can parse `humantime` formatted durations.
7224 #[test]
7225 fn humantime_compatibility_parse() {
7226 let dur = std::time::Duration::new(60 * 60 * 24 * 411, 123_456_789);
7227 let formatted = humantime::format_duration(dur).to_string();
7228 assert_eq!(
7229 formatted,
7230 "1year 1month 15days 7h 26m 24s 123ms 456us 789ns"
7231 );
7232 let expected = 1
7233 .year()
7234 .months(1)
7235 .days(15)
7236 .hours(7)
7237 .minutes(26)
7238 .seconds(24)
7239 .milliseconds(123)
7240 .microseconds(456)
7241 .nanoseconds(789);
7242 span_eq!(formatted.parse::<Span>().unwrap(), expected);
7243 }
7244
7245 /// This test ensures that we can print a `Span` that `humantime` can
7246 /// parse.
7247 ///
7248 /// Note that this isn't the default since `humantime`'s parser is
7249 /// pretty limited. e.g., It doesn't support things like `nsecs`
7250 /// despite supporting `secs`. And other reasons. See the docs on
7251 /// `Designator::HumanTime` for why we sadly provide a custom variant for
7252 /// it.
7253 #[test]
7254 fn humantime_compatibility_print() {
7255 static PRINTER: friendly::SpanPrinter = friendly::SpanPrinter::new()
7256 .designator(friendly::Designator::HumanTime);
7257
7258 let span = 1
7259 .year()
7260 .months(1)
7261 .days(15)
7262 .hours(7)
7263 .minutes(26)
7264 .seconds(24)
7265 .milliseconds(123)
7266 .microseconds(456)
7267 .nanoseconds(789);
7268 let formatted = PRINTER.span_to_string(&span);
7269 assert_eq!(formatted, "1y 1month 15d 7h 26m 24s 123ms 456us 789ns");
7270
7271 let dur = humantime::parse_duration(&formatted).unwrap();
7272 let expected =
7273 std::time::Duration::new(60 * 60 * 24 * 411, 123_456_789);
7274 assert_eq!(dur, expected);
7275 }
7276
7277 #[test]
7278 fn from_str() {
7279 let p = |s: &str| -> Result<Span, Error> { s.parse() };
7280
7281 insta::assert_snapshot!(
7282 p("1 day").unwrap(),
7283 @"P1D",
7284 );
7285 insta::assert_snapshot!(
7286 p("+1 day").unwrap(),
7287 @"P1D",
7288 );
7289 insta::assert_snapshot!(
7290 p("-1 day").unwrap(),
7291 @"-P1D",
7292 );
7293 insta::assert_snapshot!(
7294 p("P1d").unwrap(),
7295 @"P1D",
7296 );
7297 insta::assert_snapshot!(
7298 p("+P1d").unwrap(),
7299 @"P1D",
7300 );
7301 insta::assert_snapshot!(
7302 p("-P1d").unwrap(),
7303 @"-P1D",
7304 );
7305
7306 insta::assert_snapshot!(
7307 p("").unwrap_err(),
7308 @"an empty string is not a valid `Span`, expected either a ISO 8601 or Jiff's 'friendly' format",
7309 );
7310 insta::assert_snapshot!(
7311 p("+").unwrap_err(),
7312 @"found nothing after sign `+`, which is not a valid `Span`, expected either a ISO 8601 or Jiff's 'friendly' format",
7313 );
7314 insta::assert_snapshot!(
7315 p("-").unwrap_err(),
7316 @"found nothing after sign `-`, which is not a valid `Span`, expected either a ISO 8601 or Jiff's 'friendly' format",
7317 );
7318 }
7319
7320 #[test]
7321 fn serde_deserialize() {
7322 let p = |s: &str| -> Result<Span, serde_json::Error> {
7323 serde_json::from_str(&alloc::format!("\"{s}\""))
7324 };
7325
7326 insta::assert_snapshot!(
7327 p("1 day").unwrap(),
7328 @"P1D",
7329 );
7330 insta::assert_snapshot!(
7331 p("+1 day").unwrap(),
7332 @"P1D",
7333 );
7334 insta::assert_snapshot!(
7335 p("-1 day").unwrap(),
7336 @"-P1D",
7337 );
7338 insta::assert_snapshot!(
7339 p("P1d").unwrap(),
7340 @"P1D",
7341 );
7342 insta::assert_snapshot!(
7343 p("+P1d").unwrap(),
7344 @"P1D",
7345 );
7346 insta::assert_snapshot!(
7347 p("-P1d").unwrap(),
7348 @"-P1D",
7349 );
7350
7351 insta::assert_snapshot!(
7352 p("").unwrap_err(),
7353 @"an empty string is not a valid `Span`, expected either a ISO 8601 or Jiff's 'friendly' format at line 1 column 2",
7354 );
7355 insta::assert_snapshot!(
7356 p("+").unwrap_err(),
7357 @"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",
7358 );
7359 insta::assert_snapshot!(
7360 p("-").unwrap_err(),
7361 @"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",
7362 );
7363 }
7364}