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