jiff/signed_duration.rs
1use core::time::Duration;
2
3use jcore::bounds::Sign;
4
5use crate::{
6 Error, RoundMode, Timestamp, Unit, ZonedDateTime,
7 civil::{Date, DateTime, Time},
8 error::{ErrorContext, signed_duration::Error as E},
9 fmt::{friendly, temporal},
10 tz::Offset,
11 util::{
12 b::{self, SpecialBoundsError},
13 round::Increment,
14 },
15};
16
17// We define our own constants here instead of using `jcore` to try and make
18// things a little more self-contained here. These values are also just never
19// going to change and pretty easy to get right.
20const NANOS_PER_SEC: i32 = 1_000_000_000;
21const NANOS_PER_MILLI: i32 = 1_000_000;
22const NANOS_PER_MICRO: i32 = 1_000;
23const MILLIS_PER_SEC: i64 = 1_000;
24const MICROS_PER_SEC: i64 = 1_000_000;
25const SECS_PER_MINUTE: i64 = 60;
26const MINS_PER_HOUR: i64 = 60;
27const HOURS_PER_CIVIL_DAY: i64 = 24;
28const DAYS_PER_CIVIL_WEEK: i64 = 7;
29
30/// A signed duration of time represented as a 96-bit integer of nanoseconds.
31///
32/// Each duration is made up of a 64-bit integer of whole seconds and a
33/// 32-bit integer of fractional nanoseconds less than 1 whole second. Unlike
34/// [`std::time::Duration`], this duration is signed. The sign applies
35/// to the entire duration. That is, either _both_ the seconds and the
36/// fractional nanoseconds are negative or _neither_ are. Stated differently,
37/// it is guaranteed that the signs of [`SignedDuration::as_secs`] and
38/// [`SignedDuration::subsec_nanos`] are always the same, or one component is
39/// zero. (For example, `-1 seconds` and `0 nanoseconds`, or `0 seconds` and
40/// `-1 nanoseconds`.)
41///
42/// # Parsing and printing
43///
44/// Like the [`Span`](crate::Span) type, the `SignedDuration` type
45/// provides convenient trait implementations of [`std::str::FromStr`] and
46/// [`std::fmt::Display`]:
47///
48/// ```
49/// use jiff::SignedDuration;
50///
51/// let duration: SignedDuration = "PT2h30m".parse()?;
52/// assert_eq!(duration.to_string(), "PT2H30M");
53///
54/// // Or use the "friendly" format by invoking the alternate:
55/// assert_eq!(format!("{duration:#}"), "2h 30m");
56///
57/// // Parsing automatically supports both the ISO 8601 and "friendly" formats:
58/// let duration: SignedDuration = "2h 30m".parse()?;
59/// assert_eq!(duration, SignedDuration::new(2 * 60 * 60 + 30 * 60, 0));
60/// let duration: SignedDuration = "2 hours, 30 minutes".parse()?;
61/// assert_eq!(duration, SignedDuration::new(2 * 60 * 60 + 30 * 60, 0));
62///
63/// # Ok::<(), Box<dyn std::error::Error>>(())
64/// ```
65///
66/// Unlike the `Span` type, though, only uniform units are supported. This
67/// means that ISO 8601 durations with non-zero units of days or greater cannot
68/// be parsed directly into a `SignedDuration`:
69///
70/// ```
71/// use jiff::SignedDuration;
72///
73/// assert_eq!(
74/// "P1d".parse::<SignedDuration>().unwrap_err().to_string(),
75/// "parsing ISO 8601 duration in this context requires that \
76/// the duration contain a time component and no components of days or \
77/// greater",
78/// );
79///
80/// # Ok::<(), Box<dyn std::error::Error>>(())
81/// ```
82///
83/// To parse such durations, one should first parse them into a `Span` and
84/// then convert them to a `SignedDuration` by providing a relative date:
85///
86/// ```
87/// use jiff::{civil::date, Span};
88///
89/// let span: Span = "P1d".parse()?;
90/// let relative = date(2024, 11, 3).in_tz("America/New_York")?;
91/// let duration = span.to_duration(&relative)?;
92/// // This example also motivates *why* a relative date
93/// // is required. Not all days are the same length!
94/// assert_eq!(duration.to_string(), "PT25H");
95///
96/// # Ok::<(), Box<dyn std::error::Error>>(())
97/// ```
98///
99/// The format supported is a variation (nearly a subset) of the duration
100/// format specified in [ISO 8601] _and_ a Jiff-specific "friendly" format.
101/// Here are more examples:
102///
103/// ```
104/// use jiff::SignedDuration;
105///
106/// let durations = [
107/// // ISO 8601
108/// ("PT2H30M", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
109/// ("PT2.5h", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
110/// ("PT1m", SignedDuration::from_mins(1)),
111/// ("PT1.5m", SignedDuration::from_secs(90)),
112/// ("PT0.0021s", SignedDuration::new(0, 2_100_000)),
113/// ("PT0s", SignedDuration::ZERO),
114/// ("PT0.000000001s", SignedDuration::from_nanos(1)),
115/// // Jiff's "friendly" format
116/// ("2h30m", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
117/// ("2 hrs 30 mins", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
118/// ("2 hours 30 minutes", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
119/// ("2.5h", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
120/// ("1m", SignedDuration::from_mins(1)),
121/// ("1.5m", SignedDuration::from_secs(90)),
122/// ("0.0021s", SignedDuration::new(0, 2_100_000)),
123/// ("0s", SignedDuration::ZERO),
124/// ("0.000000001s", SignedDuration::from_nanos(1)),
125/// ];
126/// for (string, duration) in durations {
127/// let parsed: SignedDuration = string.parse()?;
128/// assert_eq!(duration, parsed, "result of parsing {string:?}");
129/// }
130///
131/// # Ok::<(), Box<dyn std::error::Error>>(())
132/// ```
133///
134/// For more details, see the [`fmt::temporal`](temporal) and
135/// [`fmt::friendly`](friendly) modules.
136///
137/// [ISO 8601]: https://www.iso.org/iso-8601-date-and-time-format.html
138///
139/// # API design
140///
141/// A `SignedDuration` is, as much as is possible, a replica of the
142/// `std::time::Duration` API. While there are probably some quirks in the API
143/// of `std::time::Duration` that could have been fixed here, it is probably
144/// more important that it behave "exactly like a `std::time::Duration` but
145/// with a sign." That is, this type mirrors the parallels between signed and
146/// unsigned integer types.
147///
148/// While the goal was to match the `std::time::Duration` API as much as
149/// possible, there are some differences worth highlighting:
150///
151/// * As stated, a `SignedDuration` has a sign. Therefore, it uses `i64` and
152/// `i32` instead of `u64` and `u32` to represent its 96-bit integer.
153/// * Because it's signed, the range of possible values is different. For
154/// example, a `SignedDuration::MAX` has a whole number of seconds equivalent
155/// to `i64::MAX`, which is less than `u64::MAX`.
156/// * There are some additional APIs that don't make sense on an unsigned
157/// duration, like [`SignedDuration::abs`] and [`SignedDuration::checked_neg`].
158/// * A [`SignedDuration::system_until`] routine is provided as a replacement
159/// for [`std::time::SystemTime::duration_since`], but with signed durations.
160/// * Fallible constructors are provided, where as the standard library lacks
161/// them.
162/// * Unlike the standard library, this type implements the `std::fmt::Display`
163/// and `std::str::FromStr` traits via the ISO 8601 duration format, just
164/// like the [`Span`](crate::Span) type does. Also like `Span`, the ISO
165/// 8601 duration format is used to implement the serde `Serialize` and
166/// `Deserialize` traits when the `serde` crate feature is enabled.
167/// Additionally, the Jiff-specific [`friendly`] format is supported when
168/// parsing (or deserializing) automatically. And is available as an alternate
169/// via the `std::fmt::Display` implementation, i.e.,
170/// `format!("{duration:#}")`.
171/// * The `std::fmt::Debug` trait implementation is a bit different. If you
172/// have a problem with it, please file an issue.
173/// * At present, there is no `SignedDuration::abs_diff` since there are some
174/// API design questions. If you want it, please file an issue.
175///
176/// # When should I use `SignedDuration` versus [`Span`](crate::Span)?
177///
178/// Jiff's primary duration type is `Span`. The key differences between it and
179/// `SignedDuration` are:
180///
181/// * A `Span` keeps track of each individual unit separately. That is, even
182/// though `1 hour 60 minutes` and `2 hours` are equivalent durations
183/// of time, representing each as a `Span` corresponds to two distinct values
184/// in memory. And serializing them to the ISO 8601 duration format will also
185/// preserve the units, for example, `PT1h60m` and `PT2h`.
186/// * A `Span` supports non-uniform units like days, weeks, months and years.
187/// Since not all days, weeks, months and years have the same length, they
188/// cannot be represented by a `SignedDuration`. In some cases, it may be
189/// appropriate, for example, to assume that all days are 24 hours long. But
190/// since Jiff sometimes assumes all days are 24 hours (for civil time) and
191/// sometimes doesn't (like for `ZonedDateTime` when respecting time zones), it
192/// would be inappropriate to bake one of those assumptions into a
193/// `SignedDuration`.
194/// * A `SignedDuration` is a much smaller type than a `Span`. Specifically,
195/// it's a 96-bit integer. In contrast, a `Span` is much larger since it needs
196/// to track each individual unit separately.
197///
198/// Those differences in turn motivate some approximate reasoning for when to
199/// use `Span` and when to use `SignedDuration`:
200///
201/// * If you don't care about keeping track of individual units separately or
202/// don't need the sophisticated rounding options available on a `Span`, it
203/// might be simpler and faster to use a `SignedDuration`.
204/// * If you specifically need performance on arithmetic operations involving
205/// datetimes and durations, even if it's not as convenient or correct, then it
206/// might make sense to use a `SignedDuration`.
207/// * If you need to perform arithmetic using a `std::time::Duration` and
208/// otherwise don't need the functionality of a `Span`, it might make sense
209/// to first convert the `std::time::Duration` to a `SignedDuration`, and then
210/// use one of the corresponding operations defined for `SignedDuration` on
211/// the datetime types. (They all support it.)
212///
213/// In general, a `Span` provides more functionality and is overall more
214/// flexible. A `Span` can also deserialize all forms of ISO 8601 durations
215/// (as long as they're within Jiff's limits), including durations with units
216/// of years, months, weeks and days. A `SignedDuration`, by contrast, only
217/// supports units up to and including hours.
218///
219/// # Integration with datetime types
220///
221/// All datetime types that support arithmetic using [`Span`](crate::Span) also
222/// support arithmetic using `SignedDuration` (and [`std::time::Duration`]).
223/// For example, here's how to add an absolute duration to a [`Timestamp`]:
224///
225/// ```
226/// use jiff::{SignedDuration, Timestamp};
227///
228/// let ts1 = Timestamp::from_second(1_123_456_789)?;
229/// assert_eq!(ts1.to_string(), "2005-08-07T23:19:49Z");
230///
231/// let duration = SignedDuration::new(59, 999_999_999);
232/// // Timestamp::checked_add is polymorphic! It can accept a
233/// // span or a duration.
234/// let ts2 = ts1.checked_add(duration)?;
235/// assert_eq!(ts2.to_string(), "2005-08-07T23:20:48.999999999Z");
236///
237/// # Ok::<(), Box<dyn std::error::Error>>(())
238/// ```
239///
240/// The same API pattern works with [`ZonedDateTime`], [`DateTime`], [`Date`]
241/// and [`Time`].
242///
243/// # Interaction with daylight saving time and time zone transitions
244///
245/// A `SignedDuration` always corresponds to a specific number of nanoseconds.
246/// Since a [`ZonedDateTime`] is always a precise instant in time, adding a
247/// `SignedDuration` to a `ZonedDateTime` always behaves by adding the
248/// nanoseconds from the duration to the timestamp inside of `ZonedDateTime`.
249/// Consider `2024-03-10` in `America/New_York`. At `02:00:00`, daylight saving
250/// time came into effect, switching the UTC offset for the region from `-05`
251/// to `-04`. This has the effect of skipping an hour on the clocks:
252///
253/// ```
254/// use jiff::{civil::date, SignedDuration};
255///
256/// let zdt = date(2024, 3, 10).at(1, 59, 0, 0).in_tz("America/New_York")?;
257/// assert_eq!(
258/// zdt.checked_add(SignedDuration::from_hours(1))?,
259/// // Time on the clock skipped an hour, but in this time
260/// // zone, 03:59 is actually precisely 1 hour later than
261/// // 01:59.
262/// date(2024, 3, 10).at(3, 59, 0, 0).in_tz("America/New_York")?,
263/// );
264/// // The same would apply if you used a `Span`:
265/// assert_eq!(
266/// zdt.checked_add(jiff::Span::new().hours(1))?,
267/// // Time on the clock skipped an hour, but in this time
268/// // zone, 03:59 is actually precisely 1 hour later than
269/// // 01:59.
270/// date(2024, 3, 10).at(3, 59, 0, 0).in_tz("America/New_York")?,
271/// );
272///
273/// # Ok::<(), Box<dyn std::error::Error>>(())
274/// ```
275///
276/// Where time zones might have a more interesting effect is in the definition
277/// of the "day" itself. If, for example, you encode the notion that a day is
278/// always 24 hours into your arithmetic, you might get unexpected results. For
279/// example, let's say you want to find the datetime precisely one week after
280/// `2024-03-08T17:00` in the `America/New_York` time zone. You might be
281/// tempted to just ask for the time that is `7 * 24` hours later:
282///
283/// ```
284/// use jiff::{civil::date, SignedDuration};
285///
286/// let zdt = date(2024, 3, 8).at(17, 0, 0, 0).in_tz("America/New_York")?;
287/// assert_eq!(
288/// zdt.checked_add(SignedDuration::from_hours(7 * 24))?,
289/// date(2024, 3, 15).at(18, 0, 0, 0).in_tz("America/New_York")?,
290/// );
291///
292/// # Ok::<(), Box<dyn std::error::Error>>(())
293/// ```
294///
295/// Notice that you get `18:00` and not `17:00`! That's because, as shown
296/// in the previous example, `2024-03-10` was only 23 hours long. That in turn
297/// implies that the week starting from `2024-03-08` is only `7 * 24 - 1` hours
298/// long. This can be tricky to get correct with absolute durations like
299/// `SignedDuration`, but a `Span` will handle this for you automatically:
300///
301/// ```
302/// use jiff::{civil::date, ToSpan};
303///
304/// let zdt = date(2024, 3, 8).at(17, 0, 0, 0).in_tz("America/New_York")?;
305/// assert_eq!(
306/// zdt.checked_add(1.week())?,
307/// // The expected time!
308/// date(2024, 3, 15).at(17, 0, 0, 0).in_tz("America/New_York")?,
309/// );
310///
311/// # Ok::<(), Box<dyn std::error::Error>>(())
312/// ```
313///
314/// A `Span` achieves this by keeping track of individual units. Unlike a
315/// `SignedDuration`, it is not just a simple count of nanoseconds. It is a
316/// "bag" of individual units, and the arithmetic operations defined on a
317/// `Span` for `ZonedDateTime` know how to interpret "day" in a particular time
318/// zone at a particular instant in time.
319///
320/// With that said, the above does not mean that using a `SignedDuration` is
321/// always wrong. For example, if you're dealing with units of hours or lower,
322/// then all such units are uniform and so you'll always get the same results
323/// as with a `Span`. And using a `SignedDuration` can sometimes be simpler
324/// or faster.
325#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
326pub struct SignedDuration {
327 secs: i64,
328 nanos: i32,
329}
330
331impl SignedDuration {
332 /// A duration of zero time.
333 ///
334 /// # Example
335 ///
336 /// ```
337 /// use jiff::SignedDuration;
338 ///
339 /// let duration = SignedDuration::ZERO;
340 /// assert!(duration.is_zero());
341 /// assert_eq!(duration.as_secs(), 0);
342 /// assert_eq!(duration.subsec_nanos(), 0);
343 /// ```
344 pub const ZERO: SignedDuration = SignedDuration { secs: 0, nanos: 0 };
345
346 /// The minimum possible duration. Or the "most negative" duration.
347 ///
348 /// # Example
349 ///
350 /// ```
351 /// use jiff::SignedDuration;
352 ///
353 /// let duration = SignedDuration::MIN;
354 /// assert_eq!(duration.as_secs(), i64::MIN);
355 /// assert_eq!(duration.subsec_nanos(), -999_999_999);
356 /// ```
357 pub const MIN: SignedDuration =
358 SignedDuration { secs: i64::MIN, nanos: -(NANOS_PER_SEC - 1) };
359
360 /// The maximum possible duration.
361 ///
362 /// # Example
363 ///
364 /// ```
365 /// use jiff::SignedDuration;
366 ///
367 /// let duration = SignedDuration::MAX;
368 /// assert_eq!(duration.as_secs(), i64::MAX);
369 /// assert_eq!(duration.subsec_nanos(), 999_999_999);
370 /// ```
371 pub const MAX: SignedDuration =
372 SignedDuration { secs: i64::MAX, nanos: NANOS_PER_SEC - 1 };
373
374 /// Creates a new `SignedDuration` from the given number of whole seconds
375 /// and additional nanoseconds.
376 ///
377 /// If the absolute value of the nanoseconds is greater than or equal to
378 /// 1 second, then the excess balances into the number of whole seconds.
379 ///
380 /// # Panics
381 ///
382 /// When the absolute value of the nanoseconds is greater than or equal
383 /// to 1 second and the excess that carries over to the number of whole
384 /// seconds overflows `i64`.
385 ///
386 /// This never panics when the absolute value of `nanos` is less than `1_000_000_000`.
387 ///
388 /// # Example
389 ///
390 /// ```
391 /// use jiff::SignedDuration;
392 ///
393 /// let duration = SignedDuration::new(12, 0);
394 /// assert_eq!(duration.as_secs(), 12);
395 /// assert_eq!(duration.subsec_nanos(), 0);
396 ///
397 /// let duration = SignedDuration::new(12, -1);
398 /// assert_eq!(duration.as_secs(), 11);
399 /// assert_eq!(duration.subsec_nanos(), 999_999_999);
400 ///
401 /// let duration = SignedDuration::new(12, 1_000_000_000);
402 /// assert_eq!(duration.as_secs(), 13);
403 /// assert_eq!(duration.subsec_nanos(), 0);
404 /// ```
405 #[inline]
406 pub const fn new(mut secs: i64, mut nanos: i32) -> SignedDuration {
407 // When |nanos| exceeds 1 second, we balance the excess up to seconds.
408 if !(-NANOS_PER_SEC < nanos && nanos < NANOS_PER_SEC) {
409 // Never wraps or panics because NANOS_PER_SEC!={0,-1}.
410 let addsecs = nanos / NANOS_PER_SEC;
411 secs = match secs.checked_add(addsecs as i64) {
412 Some(secs) => secs,
413 None => panic!(
414 "nanoseconds overflowed seconds in SignedDuration::new"
415 ),
416 };
417 // Never wraps or panics because NANOS_PER_SEC!={0,-1}.
418 nanos = nanos % NANOS_PER_SEC;
419 }
420 // At this point, we're done if either unit is zero or if they have the
421 // same sign.
422 if nanos == 0 || secs == 0 || secs.signum() == (nanos.signum() as i64)
423 {
424 return SignedDuration::new_unchecked(secs, nanos);
425 }
426 // Otherwise, the only work we have to do is to balance negative nanos
427 // into positive seconds, or positive nanos into negative seconds.
428 if secs < 0 {
429 debug_assert!(nanos > 0);
430 // Never wraps because adding +1 to a negative i64 never overflows.
431 //
432 // MSRV(1.79): Consider using `unchecked_add` here.
433 secs += 1;
434 // Never wraps because subtracting +1_000_000_000 from a positive
435 // i32 never overflows.
436 //
437 // MSRV(1.79): Consider using `unchecked_sub` here.
438 nanos -= NANOS_PER_SEC;
439 } else {
440 debug_assert!(secs > 0);
441 debug_assert!(nanos < 0);
442 // Never wraps because subtracting +1 from a positive i64 never
443 // overflows.
444 //
445 // MSRV(1.79): Consider using `unchecked_add` here.
446 secs -= 1;
447 // Never wraps because adding +1_000_000_000 to a negative i32
448 // never overflows.
449 //
450 // MSRV(1.79): Consider using `unchecked_add` here.
451 nanos += NANOS_PER_SEC;
452 }
453 SignedDuration::new_unchecked(secs, nanos)
454 }
455
456 /// Creates a new signed duration without handling nanosecond overflow or
457 /// sign differences.
458 ///
459 /// This might produce tighter code in some cases.
460 ///
461 /// Note that this should not be made public *and* safe.
462 ///
463 /// # Panics
464 ///
465 /// In debug mode only, when `|nanos|` is greater than or equal to 1
466 /// second. Or when both `secs` and `nanos` are non-zero and their signs
467 /// mismatch.
468 #[inline]
469 pub(crate) const fn new_unchecked(
470 secs: i64,
471 nanos: i32,
472 ) -> SignedDuration {
473 debug_assert!(nanos <= 999_999_999);
474 debug_assert!(nanos >= -999_999_999);
475 debug_assert!(
476 secs == 0
477 || nanos == 0
478 || secs.signum() == (nanos.signum() as i64)
479 );
480 SignedDuration { secs, nanos }
481 }
482
483 /// Creates a new `SignedDuration` from the given number of whole seconds.
484 ///
485 /// # Example
486 ///
487 /// ```
488 /// use jiff::SignedDuration;
489 ///
490 /// let duration = SignedDuration::from_secs(12);
491 /// assert_eq!(duration.as_secs(), 12);
492 /// assert_eq!(duration.subsec_nanos(), 0);
493 /// ```
494 #[inline]
495 pub const fn from_secs(secs: i64) -> SignedDuration {
496 SignedDuration::new_unchecked(secs, 0)
497 }
498
499 /// Creates a new `SignedDuration` from the given number of whole
500 /// milliseconds.
501 ///
502 /// Note that since this accepts an `i64`, this method cannot be used
503 /// to construct the full range of possible signed duration values. In
504 /// particular, [`SignedDuration::as_millis`] returns an `i128`, and this
505 /// may be a value that would otherwise overflow an `i64`.
506 ///
507 /// # Example
508 ///
509 /// ```
510 /// use jiff::SignedDuration;
511 ///
512 /// let duration = SignedDuration::from_millis(12_456);
513 /// assert_eq!(duration.as_secs(), 12);
514 /// assert_eq!(duration.subsec_nanos(), 456_000_000);
515 ///
516 /// let duration = SignedDuration::from_millis(-12_456);
517 /// assert_eq!(duration.as_secs(), -12);
518 /// assert_eq!(duration.subsec_nanos(), -456_000_000);
519 /// ```
520 #[inline]
521 pub const fn from_millis(millis: i64) -> SignedDuration {
522 // OK because MILLIS_PER_SEC!={-1,0}.
523 let secs = millis / MILLIS_PER_SEC;
524 // OK because MILLIS_PER_SEC!={-1,0} and because
525 // millis % MILLIS_PER_SEC can be at most 999, and 999 * 1_000_000
526 // never overflows i32.
527 let nanos = (millis % MILLIS_PER_SEC) as i32 * NANOS_PER_MILLI;
528 SignedDuration::new_unchecked(secs, nanos)
529 }
530
531 /// Creates a new `SignedDuration` from a given number of whole
532 /// milliseconds in 128 bits.
533 ///
534 /// # Panics
535 ///
536 /// When the given number of milliseconds is greater than the number of
537 /// nanoseconds represented by [`SignedDuration::MAX`] or smaller than
538 /// [`SignedDuration::MIN`].
539 ///
540 /// # Example
541 ///
542 /// ```
543 /// use jiff::SignedDuration;
544 ///
545 /// let duration = SignedDuration::from_millis_i128(12_456);
546 /// assert_eq!(duration.as_secs(), 12);
547 /// assert_eq!(duration.subsec_millis(), 456);
548 ///
549 /// let duration = SignedDuration::from_millis_i128(-12_456);
550 /// assert_eq!(duration.as_secs(), -12);
551 /// assert_eq!(duration.subsec_millis(), -456);
552 ///
553 /// // This input is bigger than what 64-bits can fit,
554 /// // and so demonstrates its utility in a case when
555 /// // `SignedDuration::from_nanos` cannot be used.
556 /// let duration = SignedDuration::from_millis_i128(
557 /// 1_208_925_819_614_629_174,
558 /// );
559 /// assert_eq!(duration.as_secs(), 1_208_925_819_614_629);
560 /// assert_eq!(duration.subsec_millis(), 174);
561 /// ```
562 #[inline]
563 pub const fn from_millis_i128(millis: i128) -> SignedDuration {
564 match SignedDuration::try_from_millis_i128(millis) {
565 Some(sdur) => sdur,
566 None => {
567 panic!(
568 "seconds overflows `i64` \
569 in `SignedDuration::from_millis_i128`",
570 )
571 }
572 }
573 }
574
575 /// Creates a new `SignedDuration` from the given number of whole
576 /// microseconds.
577 ///
578 /// Note that since this accepts an `i64`, this method cannot be used
579 /// to construct the full range of possible signed duration values. In
580 /// particular, [`SignedDuration::as_micros`] returns an `i128`, and this
581 /// may be a value that would otherwise overflow an `i64`.
582 ///
583 /// # Example
584 ///
585 /// ```
586 /// use jiff::SignedDuration;
587 ///
588 /// let duration = SignedDuration::from_micros(12_000_456);
589 /// assert_eq!(duration.as_secs(), 12);
590 /// assert_eq!(duration.subsec_nanos(), 456_000);
591 ///
592 /// let duration = SignedDuration::from_micros(-12_000_456);
593 /// assert_eq!(duration.as_secs(), -12);
594 /// assert_eq!(duration.subsec_nanos(), -456_000);
595 /// ```
596 #[inline]
597 pub const fn from_micros(micros: i64) -> SignedDuration {
598 // OK because MICROS_PER_SEC!={-1,0}.
599 let secs = micros / MICROS_PER_SEC;
600 // OK because MICROS_PER_SEC!={-1,0} and because
601 // micros % MICROS_PER_SEC can be at most 999_999, and 999_999 * 1_000
602 // never overflows i32.
603 let nanos = (micros % MICROS_PER_SEC) as i32 * NANOS_PER_MICRO;
604 SignedDuration::new_unchecked(secs, nanos)
605 }
606
607 /// Creates a new `SignedDuration` from a given number of whole
608 /// microseconds in 128 bits.
609 ///
610 /// # Panics
611 ///
612 /// When the given number of microseconds is greater than the number of
613 /// nanoseconds represented by [`SignedDuration::MAX`] or smaller than
614 /// [`SignedDuration::MIN`].
615 ///
616 /// # Example
617 ///
618 /// ```
619 /// use jiff::SignedDuration;
620 ///
621 /// let duration = SignedDuration::from_micros_i128(12_000_456);
622 /// assert_eq!(duration.as_secs(), 12);
623 /// assert_eq!(duration.subsec_micros(), 456);
624 ///
625 /// let duration = SignedDuration::from_micros_i128(-12_000_456);
626 /// assert_eq!(duration.as_secs(), -12);
627 /// assert_eq!(duration.subsec_micros(), -456);
628 ///
629 /// // This input is bigger than what 64-bits can fit,
630 /// // and so demonstrates its utility in a case when
631 /// // `SignedDuration::from_nanos` cannot be used.
632 /// let duration = SignedDuration::from_micros_i128(
633 /// 1_208_925_819_614_629_174_706,
634 /// );
635 /// assert_eq!(duration.as_secs(), 1_208_925_819_614_629);
636 /// assert_eq!(duration.subsec_micros(), 174_706);
637 /// ```
638 #[inline]
639 pub const fn from_micros_i128(micros: i128) -> SignedDuration {
640 match SignedDuration::try_from_micros_i128(micros) {
641 Some(sdur) => sdur,
642 None => {
643 panic!(
644 "seconds overflows `i64` \
645 in `SignedDuration::from_micros_i128`",
646 )
647 }
648 }
649 }
650
651 /// Creates a new `SignedDuration` from the given number of whole
652 /// nanoseconds.
653 ///
654 /// Note that since this accepts an `i64`, this method cannot be used
655 /// to construct the full range of possible signed duration values. In
656 /// particular, [`SignedDuration::as_nanos`] returns an `i128`, which may
657 /// be a value that would otherwise overflow an `i64`. To correctly
658 /// round-trip through an integer number of nanoseconds, use
659 /// [`SignedDuration::from_nanos_i128`].
660 ///
661 /// # Example
662 ///
663 /// ```
664 /// use jiff::SignedDuration;
665 ///
666 /// let duration = SignedDuration::from_nanos(12_000_000_456);
667 /// assert_eq!(duration.as_secs(), 12);
668 /// assert_eq!(duration.subsec_nanos(), 456);
669 ///
670 /// let duration = SignedDuration::from_nanos(-12_000_000_456);
671 /// assert_eq!(duration.as_secs(), -12);
672 /// assert_eq!(duration.subsec_nanos(), -456);
673 /// ```
674 #[inline]
675 pub const fn from_nanos(nanos: i64) -> SignedDuration {
676 const NANOS_PER_SEC: i64 = self::NANOS_PER_SEC as i64;
677 // OK because NANOS_PER_SEC!={-1,0}.
678 let secs = nanos / NANOS_PER_SEC;
679 // OK because NANOS_PER_SEC!={-1,0}.
680 let nanos = (nanos % NANOS_PER_SEC) as i32;
681 SignedDuration::new_unchecked(secs, nanos)
682 }
683
684 /// Creates a new `SignedDuration` from a given number of whole
685 /// nanoseconds in 128 bits.
686 ///
687 /// # Panics
688 ///
689 /// When the given number of nanoseconds is greater than the number of
690 /// nanoseconds represented by [`SignedDuration::MAX`] or smaller than
691 /// [`SignedDuration::MIN`].
692 ///
693 /// # Example
694 ///
695 /// ```
696 /// use jiff::SignedDuration;
697 ///
698 /// let duration = SignedDuration::from_nanos_i128(12_000_000_456);
699 /// assert_eq!(duration.as_secs(), 12);
700 /// assert_eq!(duration.subsec_nanos(), 456);
701 ///
702 /// let duration = SignedDuration::from_nanos_i128(-12_000_000_456);
703 /// assert_eq!(duration.as_secs(), -12);
704 /// assert_eq!(duration.subsec_nanos(), -456);
705 ///
706 /// // This input is bigger than what 64-bits can fit,
707 /// // and so demonstrates its utility in a case when
708 /// // `SignedDuration::from_nanos` cannot be used.
709 /// let duration = SignedDuration::from_nanos_i128(
710 /// 1_208_925_819_614_629_174_706_176,
711 /// );
712 /// assert_eq!(duration.as_secs(), 1_208_925_819_614_629);
713 /// assert_eq!(duration.subsec_nanos(), 174_706_176);
714 /// ```
715 #[inline]
716 pub const fn from_nanos_i128(nanos: i128) -> SignedDuration {
717 match SignedDuration::try_from_nanos_i128(nanos) {
718 Some(sdur) => sdur,
719 None => {
720 panic!(
721 "seconds overflows `i64` \
722 in `SignedDuration::from_nanos_i128`",
723 )
724 }
725 }
726 }
727
728 /// Creates a new `SignedDuration` from the given number of hours. Every
729 /// hour is exactly `3,600` seconds.
730 ///
731 /// # Panics
732 ///
733 /// Panics if the number of hours, after being converted to nanoseconds,
734 /// overflows the minimum or maximum `SignedDuration` values.
735 ///
736 /// # Example
737 ///
738 /// ```
739 /// use jiff::SignedDuration;
740 ///
741 /// let duration = SignedDuration::from_hours(24);
742 /// assert_eq!(duration.as_secs(), 86_400);
743 /// assert_eq!(duration.subsec_nanos(), 0);
744 ///
745 /// let duration = SignedDuration::from_hours(-24);
746 /// assert_eq!(duration.as_secs(), -86_400);
747 /// assert_eq!(duration.subsec_nanos(), 0);
748 /// ```
749 #[inline]
750 pub const fn from_hours(hours: i64) -> SignedDuration {
751 match SignedDuration::try_from_hours(hours) {
752 Some(sdur) => sdur,
753 None => {
754 panic!(
755 "hours overflowed an `i64` number of seconds \
756 in `SignedDuration::from_hours`",
757 )
758 }
759 }
760 }
761
762 /// Creates a new `SignedDuration` from the given number of minutes. Every
763 /// minute is exactly `60` seconds.
764 ///
765 /// # Panics
766 ///
767 /// Panics if the number of minutes, after being converted to nanoseconds,
768 /// overflows the minimum or maximum `SignedDuration` values.
769 ///
770 /// # Example
771 ///
772 /// ```
773 /// use jiff::SignedDuration;
774 ///
775 /// let duration = SignedDuration::from_mins(1_440);
776 /// assert_eq!(duration.as_secs(), 86_400);
777 /// assert_eq!(duration.subsec_nanos(), 0);
778 ///
779 /// let duration = SignedDuration::from_mins(-1_440);
780 /// assert_eq!(duration.as_secs(), -86_400);
781 /// assert_eq!(duration.subsec_nanos(), 0);
782 /// ```
783 #[inline]
784 pub const fn from_mins(mins: i64) -> SignedDuration {
785 match SignedDuration::try_from_mins(mins) {
786 Some(sdur) => sdur,
787 None => {
788 panic!(
789 "minutes overflowed an `i64` number of seconds \
790 in `SignedDuration::from_mins`",
791 )
792 }
793 }
794 }
795
796 /// Returns true if this duration spans no time.
797 ///
798 /// # Example
799 ///
800 /// ```
801 /// use jiff::SignedDuration;
802 ///
803 /// assert!(SignedDuration::ZERO.is_zero());
804 /// assert!(!SignedDuration::MIN.is_zero());
805 /// assert!(!SignedDuration::MAX.is_zero());
806 /// ```
807 #[inline]
808 pub const fn is_zero(&self) -> bool {
809 self.secs == 0 && self.nanos == 0
810 }
811
812 /// Returns the number of whole seconds in this duration.
813 ///
814 /// The value returned is negative when the duration is negative.
815 ///
816 /// This does not include any fractional component corresponding to units
817 /// less than a second. To access those, use one of the `subsec` methods
818 /// such as [`SignedDuration::subsec_nanos`].
819 ///
820 /// # Example
821 ///
822 /// ```
823 /// use jiff::SignedDuration;
824 ///
825 /// let duration = SignedDuration::new(12, 999_999_999);
826 /// assert_eq!(duration.as_secs(), 12);
827 ///
828 /// let duration = SignedDuration::new(-12, -999_999_999);
829 /// assert_eq!(duration.as_secs(), -12);
830 /// ```
831 #[inline]
832 pub const fn as_secs(&self) -> i64 {
833 self.secs
834 }
835
836 /// Returns the fractional part of this duration in whole milliseconds.
837 ///
838 /// The value returned is negative when the duration is negative. It is
839 /// guaranteed that the range of the value returned is in the inclusive
840 /// range `-999..=999`.
841 ///
842 /// To get the length of the total duration represented in milliseconds,
843 /// use [`SignedDuration::as_millis`].
844 ///
845 /// # Example
846 ///
847 /// ```
848 /// use jiff::SignedDuration;
849 ///
850 /// let duration = SignedDuration::new(12, 123_456_789);
851 /// assert_eq!(duration.subsec_millis(), 123);
852 ///
853 /// let duration = SignedDuration::new(-12, -123_456_789);
854 /// assert_eq!(duration.subsec_millis(), -123);
855 /// ```
856 #[inline]
857 pub const fn subsec_millis(&self) -> i32 {
858 // OK because NANOS_PER_MILLI!={-1,0}.
859 self.nanos / NANOS_PER_MILLI
860 }
861
862 /// Returns the fractional part of this duration in whole microseconds.
863 ///
864 /// The value returned is negative when the duration is negative. It is
865 /// guaranteed that the range of the value returned is in the inclusive
866 /// range `-999_999..=999_999`.
867 ///
868 /// To get the length of the total duration represented in microseconds,
869 /// use [`SignedDuration::as_micros`].
870 ///
871 /// # Example
872 ///
873 /// ```
874 /// use jiff::SignedDuration;
875 ///
876 /// let duration = SignedDuration::new(12, 123_456_789);
877 /// assert_eq!(duration.subsec_micros(), 123_456);
878 ///
879 /// let duration = SignedDuration::new(-12, -123_456_789);
880 /// assert_eq!(duration.subsec_micros(), -123_456);
881 /// ```
882 #[inline]
883 pub const fn subsec_micros(&self) -> i32 {
884 // OK because NANOS_PER_MICRO!={-1,0}.
885 self.nanos / NANOS_PER_MICRO
886 }
887
888 /// Returns the fractional part of this duration in whole nanoseconds.
889 ///
890 /// The value returned is negative when the duration is negative. It is
891 /// guaranteed that the range of the value returned is in the inclusive
892 /// range `-999_999_999..=999_999_999`.
893 ///
894 /// To get the length of the total duration represented in nanoseconds,
895 /// use [`SignedDuration::as_nanos`].
896 ///
897 /// # Example
898 ///
899 /// ```
900 /// use jiff::SignedDuration;
901 ///
902 /// let duration = SignedDuration::new(12, 123_456_789);
903 /// assert_eq!(duration.subsec_nanos(), 123_456_789);
904 ///
905 /// let duration = SignedDuration::new(-12, -123_456_789);
906 /// assert_eq!(duration.subsec_nanos(), -123_456_789);
907 /// ```
908 #[inline]
909 pub const fn subsec_nanos(&self) -> i32 {
910 self.nanos
911 }
912
913 /// Returns the total duration in units of whole milliseconds.
914 ///
915 /// The value returned is negative when the duration is negative.
916 ///
917 /// To get only the fractional component of this duration in units of
918 /// whole milliseconds, use [`SignedDuration::subsec_millis`].
919 ///
920 /// # Example
921 ///
922 /// ```
923 /// use jiff::SignedDuration;
924 ///
925 /// let duration = SignedDuration::new(12, 123_456_789);
926 /// assert_eq!(duration.as_millis(), 12_123);
927 ///
928 /// let duration = SignedDuration::new(-12, -123_456_789);
929 /// assert_eq!(duration.as_millis(), -12_123);
930 /// ```
931 #[inline]
932 pub const fn as_millis(&self) -> i128 {
933 // OK because 1_000 times any i64 will never overflow i128.
934 let millis = (self.secs as i128) * (MILLIS_PER_SEC as i128);
935 // OK because NANOS_PER_MILLI!={-1,0}.
936 let subsec_millis = (self.nanos / NANOS_PER_MILLI) as i128;
937 // OK because subsec_millis maxes out at 999, and adding that to
938 // i64::MAX*1_000 will never overflow a i128.
939 millis + subsec_millis
940 }
941
942 /// Returns the total duration in units of whole microseconds.
943 ///
944 /// The value returned is negative when the duration is negative.
945 ///
946 /// To get only the fractional component of this duration in units of
947 /// whole microseconds, use [`SignedDuration::subsec_micros`].
948 ///
949 /// # Example
950 ///
951 /// ```
952 /// use jiff::SignedDuration;
953 ///
954 /// let duration = SignedDuration::new(12, 123_456_789);
955 /// assert_eq!(duration.as_micros(), 12_123_456);
956 ///
957 /// let duration = SignedDuration::new(-12, -123_456_789);
958 /// assert_eq!(duration.as_micros(), -12_123_456);
959 /// ```
960 #[inline]
961 pub const fn as_micros(&self) -> i128 {
962 // OK because 1_000_000 times any i64 will never overflow i128.
963 let micros = (self.secs as i128) * (MICROS_PER_SEC as i128);
964 // OK because NANOS_PER_MICRO!={-1,0}.
965 let subsec_micros = (self.nanos / NANOS_PER_MICRO) as i128;
966 // OK because subsec_micros maxes out at 999_999, and adding that to
967 // i64::MAX*1_000_000 will never overflow a i128.
968 micros + subsec_micros
969 }
970
971 /// Returns the total duration in units of whole nanoseconds.
972 ///
973 /// The value returned is negative when the duration is negative.
974 ///
975 /// To get only the fractional component of this duration in units of
976 /// whole nanoseconds, use [`SignedDuration::subsec_nanos`].
977 ///
978 /// # Example
979 ///
980 /// ```
981 /// use jiff::SignedDuration;
982 ///
983 /// let duration = SignedDuration::new(12, 123_456_789);
984 /// assert_eq!(duration.as_nanos(), 12_123_456_789);
985 ///
986 /// let duration = SignedDuration::new(-12, -123_456_789);
987 /// assert_eq!(duration.as_nanos(), -12_123_456_789);
988 /// ```
989 #[inline]
990 pub const fn as_nanos(&self) -> i128 {
991 // OK because 1_000_000_000 times any i64 will never overflow i128.
992 let nanos = (self.secs as i128) * (NANOS_PER_SEC as i128);
993 // OK because subsec_nanos maxes out at 999_999_999, and adding that to
994 // i64::MAX*1_000_000_000 will never overflow a i128.
995 nanos + (self.nanos as i128)
996 }
997
998 /// Like `SignedDuration::as_nanos()`, but only returns a result when it
999 /// fits into a 64-bit integer.
1000 #[inline]
1001 pub(crate) fn as_nanos64(&self) -> Option<i64> {
1002 const MIN: SignedDuration = SignedDuration::from_nanos(i64::MIN);
1003 const MAX: SignedDuration = SignedDuration::from_nanos(i64::MAX);
1004 if MIN <= *self && *self <= MAX {
1005 let nanos = self.secs * (NANOS_PER_SEC as i64);
1006 Some(nanos + (self.nanos as i64))
1007 } else {
1008 None
1009 }
1010 }
1011
1012 // NOTE: We don't provide `abs_diff` here because we can't represent the
1013 // difference between all possible durations. For example,
1014 // `abs_diff(SignedDuration::MAX, SignedDuration::MIN)`. It therefore seems
1015 // like we should actually return a `std::time::Duration` here, but I'm
1016 // trying to be conservative when divering from std.
1017
1018 /// Add two signed durations together. If overflow occurs, then `None` is
1019 /// returned.
1020 ///
1021 /// # Example
1022 ///
1023 /// ```
1024 /// use jiff::SignedDuration;
1025 ///
1026 /// let duration1 = SignedDuration::new(12, 500_000_000);
1027 /// let duration2 = SignedDuration::new(0, 500_000_000);
1028 /// assert_eq!(
1029 /// duration1.checked_add(duration2),
1030 /// Some(SignedDuration::new(13, 0)),
1031 /// );
1032 ///
1033 /// let duration1 = SignedDuration::MAX;
1034 /// let duration2 = SignedDuration::new(0, 1);
1035 /// assert_eq!(duration1.checked_add(duration2), None);
1036 /// ```
1037 #[inline]
1038 pub const fn checked_add(
1039 self,
1040 rhs: SignedDuration,
1041 ) -> Option<SignedDuration> {
1042 let Some(mut secs) = self.secs.checked_add(rhs.secs) else {
1043 return None;
1044 };
1045 // OK because `-999_999_999 <= nanos <= 999_999_999`, and so adding
1046 // them together will never overflow an i32.
1047 let mut nanos = self.nanos + rhs.nanos;
1048 // The below is effectively SignedDuration::new, but with checked
1049 // arithmetic. My suspicion is that there is probably a better way
1050 // to do this. The main complexity here is that 1) `|nanos|` might
1051 // now exceed 1 second and 2) the signs of `secs` and `nanos` might
1052 // not be the same. The other difference from SignedDuration::new is
1053 // that we know that `-1_999_999_998 <= nanos <= 1_999_999_998` since
1054 // `|SignedDuration::nanos|` is guaranteed to be less than 1 second. So
1055 // we can skip the div and modulus operations.
1056
1057 // When |nanos| exceeds 1 second, we balance the excess up to seconds.
1058 if nanos != 0 {
1059 if nanos >= NANOS_PER_SEC {
1060 nanos -= NANOS_PER_SEC;
1061 secs = match secs.checked_add(1) {
1062 None => return None,
1063 Some(secs) => secs,
1064 };
1065 } else if nanos <= -NANOS_PER_SEC {
1066 nanos += NANOS_PER_SEC;
1067 secs = match secs.checked_sub(1) {
1068 None => return None,
1069 Some(secs) => secs,
1070 };
1071 }
1072 if secs != 0
1073 && nanos != 0
1074 && secs.signum() != (nanos.signum() as i64)
1075 {
1076 if secs < 0 {
1077 debug_assert!(nanos > 0);
1078 // OK because secs<0.
1079 secs += 1;
1080 // OK because nanos>0.
1081 nanos -= NANOS_PER_SEC;
1082 } else {
1083 debug_assert!(secs > 0);
1084 debug_assert!(nanos < 0);
1085 // OK because secs>0.
1086 secs -= 1;
1087 // OK because nanos<0.
1088 nanos += NANOS_PER_SEC;
1089 }
1090 }
1091 }
1092 Some(SignedDuration::new_unchecked(secs, nanos))
1093 }
1094
1095 /// Add two signed durations together. If overflow occurs, then arithmetic
1096 /// saturates.
1097 ///
1098 /// # Example
1099 ///
1100 /// ```
1101 /// use jiff::SignedDuration;
1102 ///
1103 /// let duration1 = SignedDuration::MAX;
1104 /// let duration2 = SignedDuration::new(0, 1);
1105 /// assert_eq!(duration1.saturating_add(duration2), SignedDuration::MAX);
1106 ///
1107 /// let duration1 = SignedDuration::MIN;
1108 /// let duration2 = SignedDuration::new(0, -1);
1109 /// assert_eq!(duration1.saturating_add(duration2), SignedDuration::MIN);
1110 /// ```
1111 #[inline]
1112 pub const fn saturating_add(self, rhs: SignedDuration) -> SignedDuration {
1113 let Some(sum) = self.checked_add(rhs) else {
1114 return if rhs.is_negative() {
1115 SignedDuration::MIN
1116 } else {
1117 SignedDuration::MAX
1118 };
1119 };
1120 sum
1121 }
1122
1123 /// Subtract one signed duration from another. If overflow occurs, then
1124 /// `None` is returned.
1125 ///
1126 /// # Example
1127 ///
1128 /// ```
1129 /// use jiff::SignedDuration;
1130 ///
1131 /// let duration1 = SignedDuration::new(12, 500_000_000);
1132 /// let duration2 = SignedDuration::new(0, 500_000_000);
1133 /// assert_eq!(
1134 /// duration1.checked_sub(duration2),
1135 /// Some(SignedDuration::new(12, 0)),
1136 /// );
1137 ///
1138 /// let duration1 = SignedDuration::MIN;
1139 /// let duration2 = SignedDuration::new(0, 1);
1140 /// assert_eq!(duration1.checked_sub(duration2), None);
1141 /// ```
1142 #[inline]
1143 pub const fn checked_sub(
1144 self,
1145 rhs: SignedDuration,
1146 ) -> Option<SignedDuration> {
1147 let Some(rhs) = rhs.checked_neg() else { return None };
1148 self.checked_add(rhs)
1149 }
1150
1151 /// Add two signed durations together. If overflow occurs, then arithmetic
1152 /// saturates.
1153 ///
1154 /// # Example
1155 ///
1156 /// ```
1157 /// use jiff::SignedDuration;
1158 ///
1159 /// let duration1 = SignedDuration::MAX;
1160 /// let duration2 = SignedDuration::new(0, -1);
1161 /// assert_eq!(duration1.saturating_sub(duration2), SignedDuration::MAX);
1162 ///
1163 /// let duration1 = SignedDuration::MIN;
1164 /// let duration2 = SignedDuration::new(0, 1);
1165 /// assert_eq!(duration1.saturating_sub(duration2), SignedDuration::MIN);
1166 /// ```
1167 #[inline]
1168 pub const fn saturating_sub(self, rhs: SignedDuration) -> SignedDuration {
1169 let Some(diff) = self.checked_sub(rhs) else {
1170 return if rhs.is_positive() {
1171 SignedDuration::MIN
1172 } else {
1173 SignedDuration::MAX
1174 };
1175 };
1176 diff
1177 }
1178
1179 /// Multiply this signed duration by an integer. If the multiplication
1180 /// overflows, then `None` is returned.
1181 ///
1182 /// # Example
1183 ///
1184 /// ```
1185 /// use jiff::SignedDuration;
1186 ///
1187 /// let duration = SignedDuration::new(12, 500_000_000);
1188 /// assert_eq!(
1189 /// duration.checked_mul(2),
1190 /// Some(SignedDuration::new(25, 0)),
1191 /// );
1192 /// ```
1193 #[inline]
1194 pub const fn checked_mul(self, rhs: i32) -> Option<SignedDuration> {
1195 let rhs = rhs as i64;
1196 // Multiplying any two i32 values never overflows an i64.
1197 let nanos = (self.nanos as i64) * rhs;
1198 // OK since NANOS_PER_SEC!={-1,0}.
1199 let addsecs = nanos / (NANOS_PER_SEC as i64);
1200 // OK since NANOS_PER_SEC!={-1,0}.
1201 let nanos = (nanos % (NANOS_PER_SEC as i64)) as i32;
1202 let Some(secs) = self.secs.checked_mul(rhs) else { return None };
1203 let Some(secs) = secs.checked_add(addsecs) else { return None };
1204 Some(SignedDuration::new_unchecked(secs, nanos))
1205 }
1206
1207 /// Multiply this signed duration by an integer. If the multiplication
1208 /// overflows, then the result saturates to either the minimum or maximum
1209 /// duration depending on the sign of the product.
1210 ///
1211 /// # Example
1212 ///
1213 /// ```
1214 /// use jiff::SignedDuration;
1215 ///
1216 /// let duration = SignedDuration::new(i64::MAX, 0);
1217 /// assert_eq!(duration.saturating_mul(2), SignedDuration::MAX);
1218 /// assert_eq!(duration.saturating_mul(-2), SignedDuration::MIN);
1219 ///
1220 /// let duration = SignedDuration::new(i64::MIN, 0);
1221 /// assert_eq!(duration.saturating_mul(2), SignedDuration::MIN);
1222 /// assert_eq!(duration.saturating_mul(-2), SignedDuration::MAX);
1223 /// ```
1224 #[inline]
1225 pub const fn saturating_mul(self, rhs: i32) -> SignedDuration {
1226 let Some(product) = self.checked_mul(rhs) else {
1227 let sign = (self.signum() as i64) * (rhs as i64).signum();
1228 return if sign.is_negative() {
1229 SignedDuration::MIN
1230 } else {
1231 SignedDuration::MAX
1232 };
1233 };
1234 product
1235 }
1236
1237 /// Divide this duration by an integer. If the division overflows, then
1238 /// `None` is returned.
1239 ///
1240 /// # Example
1241 ///
1242 /// ```
1243 /// use jiff::SignedDuration;
1244 ///
1245 /// let duration = SignedDuration::new(12, 500_000_000);
1246 /// assert_eq!(
1247 /// duration.checked_div(2),
1248 /// Some(SignedDuration::new(6, 250_000_000)),
1249 /// );
1250 /// assert_eq!(
1251 /// duration.checked_div(-2),
1252 /// Some(SignedDuration::new(-6, -250_000_000)),
1253 /// );
1254 ///
1255 /// let duration = SignedDuration::new(-12, -500_000_000);
1256 /// assert_eq!(
1257 /// duration.checked_div(2),
1258 /// Some(SignedDuration::new(-6, -250_000_000)),
1259 /// );
1260 /// assert_eq!(
1261 /// duration.checked_div(-2),
1262 /// Some(SignedDuration::new(6, 250_000_000)),
1263 /// );
1264 /// ```
1265 #[inline]
1266 pub const fn checked_div(self, rhs: i32) -> Option<SignedDuration> {
1267 if rhs == 0 || (self.secs == i64::MIN && rhs == -1) {
1268 return None;
1269 }
1270 // OK since rhs!={-1,0}.
1271 let secs = self.secs / (rhs as i64);
1272 // OK since rhs!={-1,0}.
1273 let addsecs = self.secs % (rhs as i64);
1274 // OK since rhs!=0 and self.nanos>i32::MIN.
1275 let mut nanos = self.nanos / rhs;
1276 // OK since rhs!=0 and self.nanos>i32::MIN.
1277 let addnanos = self.nanos % rhs;
1278 let leftover_nanos =
1279 (addsecs * (NANOS_PER_SEC as i64)) + (addnanos as i64);
1280 nanos += (leftover_nanos / (rhs as i64)) as i32;
1281 debug_assert!(nanos < NANOS_PER_SEC);
1282 Some(SignedDuration::new_unchecked(secs, nanos))
1283 }
1284
1285 /// Returns the number of seconds, with a possible fractional nanosecond
1286 /// component, represented by this signed duration as a 64-bit float.
1287 ///
1288 /// # Example
1289 ///
1290 /// ```
1291 /// use jiff::SignedDuration;
1292 ///
1293 /// let duration = SignedDuration::new(12, 123_456_789);
1294 /// assert_eq!(duration.as_secs_f64(), 12.123456789);
1295 ///
1296 /// let duration = SignedDuration::new(-12, -123_456_789);
1297 /// assert_eq!(duration.as_secs_f64(), -12.123456789);
1298 /// ```
1299 #[inline]
1300 pub fn as_secs_f64(&self) -> f64 {
1301 (self.secs as f64) + ((self.nanos as f64) / (NANOS_PER_SEC as f64))
1302 }
1303
1304 /// Returns the number of seconds, with a possible fractional nanosecond
1305 /// component, represented by this signed duration as a 32-bit float.
1306 ///
1307 /// # Example
1308 ///
1309 /// ```
1310 /// use jiff::SignedDuration;
1311 ///
1312 /// let duration = SignedDuration::new(12, 123_456_789);
1313 /// assert_eq!(duration.as_secs_f32(), 12.123456789);
1314 ///
1315 /// let duration = SignedDuration::new(-12, -123_456_789);
1316 /// assert_eq!(duration.as_secs_f32(), -12.123456789);
1317 /// ```
1318 #[inline]
1319 pub fn as_secs_f32(&self) -> f32 {
1320 (self.secs as f32) + ((self.nanos as f32) / (NANOS_PER_SEC as f32))
1321 }
1322
1323 /// Returns the number of milliseconds, with a possible fractional
1324 /// nanosecond component, represented by this signed duration as a 64-bit
1325 /// float.
1326 ///
1327 /// # Example
1328 ///
1329 /// ```
1330 /// use jiff::SignedDuration;
1331 ///
1332 /// let duration = SignedDuration::new(12, 123_456_789);
1333 /// assert_eq!(duration.as_millis_f64(), 12123.456789);
1334 ///
1335 /// let duration = SignedDuration::new(-12, -123_456_789);
1336 /// assert_eq!(duration.as_millis_f64(), -12123.456789);
1337 /// ```
1338 #[inline]
1339 pub fn as_millis_f64(&self) -> f64 {
1340 ((self.secs as f64) * (MILLIS_PER_SEC as f64))
1341 + ((self.nanos as f64) / (NANOS_PER_MILLI as f64))
1342 }
1343
1344 /// Returns the number of milliseconds, with a possible fractional
1345 /// nanosecond component, represented by this signed duration as a 32-bit
1346 /// float.
1347 ///
1348 /// # Example
1349 ///
1350 /// ```
1351 /// use jiff::SignedDuration;
1352 ///
1353 /// let duration = SignedDuration::new(12, 123_456_789);
1354 /// assert_eq!(duration.as_millis_f32(), 12123.456789);
1355 ///
1356 /// let duration = SignedDuration::new(-12, -123_456_789);
1357 /// assert_eq!(duration.as_millis_f32(), -12123.456789);
1358 /// ```
1359 #[inline]
1360 pub fn as_millis_f32(&self) -> f32 {
1361 ((self.secs as f32) * (MILLIS_PER_SEC as f32))
1362 + ((self.nanos as f32) / (NANOS_PER_MILLI as f32))
1363 }
1364
1365 /// Returns a signed duration corresponding to the number of seconds
1366 /// represented as a 64-bit float. The number given may have a fractional
1367 /// nanosecond component.
1368 ///
1369 /// # Panics
1370 ///
1371 /// If the given float overflows the minimum or maximum signed duration
1372 /// values, then this panics.
1373 ///
1374 /// # Example
1375 ///
1376 /// ```
1377 /// use jiff::SignedDuration;
1378 ///
1379 /// let duration = SignedDuration::from_secs_f64(12.123456789);
1380 /// assert_eq!(duration.as_secs(), 12);
1381 /// assert_eq!(duration.subsec_nanos(), 123_456_789);
1382 ///
1383 /// let duration = SignedDuration::from_secs_f64(-12.123456789);
1384 /// assert_eq!(duration.as_secs(), -12);
1385 /// assert_eq!(duration.subsec_nanos(), -123_456_789);
1386 ///
1387 /// # Ok::<(), Box<dyn std::error::Error>>(())
1388 /// ```
1389 #[inline]
1390 pub fn from_secs_f64(secs: f64) -> SignedDuration {
1391 SignedDuration::try_from_secs_f64(secs)
1392 .expect("finite and in-bounds f64")
1393 }
1394
1395 /// Returns a signed duration corresponding to the number of seconds
1396 /// represented as a 32-bit float. The number given may have a fractional
1397 /// nanosecond component.
1398 ///
1399 /// # Panics
1400 ///
1401 /// If the given float overflows the minimum or maximum signed duration
1402 /// values, then this panics.
1403 ///
1404 /// # Example
1405 ///
1406 /// ```
1407 /// use jiff::SignedDuration;
1408 ///
1409 /// let duration = SignedDuration::from_secs_f32(12.123456789);
1410 /// assert_eq!(duration.as_secs(), 12);
1411 /// // loss of precision!
1412 /// assert_eq!(duration.subsec_nanos(), 123_456_952);
1413 ///
1414 /// let duration = SignedDuration::from_secs_f32(-12.123456789);
1415 /// assert_eq!(duration.as_secs(), -12);
1416 /// // loss of precision!
1417 /// assert_eq!(duration.subsec_nanos(), -123_456_952);
1418 ///
1419 /// # Ok::<(), Box<dyn std::error::Error>>(())
1420 /// ```
1421 #[inline]
1422 pub fn from_secs_f32(secs: f32) -> SignedDuration {
1423 SignedDuration::try_from_secs_f32(secs)
1424 .expect("finite and in-bounds f32")
1425 }
1426
1427 /// Returns a signed duration corresponding to the number of seconds
1428 /// represented as a 64-bit float. The number given may have a fractional
1429 /// nanosecond component.
1430 ///
1431 /// If the given float overflows the minimum or maximum signed duration
1432 /// values, then an error is returned.
1433 ///
1434 /// # Example
1435 ///
1436 /// ```
1437 /// use jiff::SignedDuration;
1438 ///
1439 /// let duration = SignedDuration::try_from_secs_f64(12.123456789)?;
1440 /// assert_eq!(duration.as_secs(), 12);
1441 /// assert_eq!(duration.subsec_nanos(), 123_456_789);
1442 ///
1443 /// let duration = SignedDuration::try_from_secs_f64(-12.123456789)?;
1444 /// assert_eq!(duration.as_secs(), -12);
1445 /// assert_eq!(duration.subsec_nanos(), -123_456_789);
1446 ///
1447 /// assert!(SignedDuration::try_from_secs_f64(f64::NAN).is_err());
1448 /// assert!(SignedDuration::try_from_secs_f64(f64::INFINITY).is_err());
1449 /// assert!(SignedDuration::try_from_secs_f64(f64::NEG_INFINITY).is_err());
1450 /// assert!(SignedDuration::try_from_secs_f64(f64::MIN).is_err());
1451 /// assert!(SignedDuration::try_from_secs_f64(f64::MAX).is_err());
1452 ///
1453 /// # Ok::<(), Box<dyn std::error::Error>>(())
1454 /// ```
1455 #[inline]
1456 pub fn try_from_secs_f64(secs: f64) -> Result<SignedDuration, Error> {
1457 #[cfg(not(feature = "std"))]
1458 use crate::util::libm::Float;
1459
1460 if !secs.is_finite() {
1461 return Err(Error::from(E::ConvertNonFinite));
1462 }
1463 if !((i64::MIN as f64) <= secs && secs <= (i64::MAX as f64)) {
1464 return Err(
1465 SpecialBoundsError::SignedDurationFloatOutOfRangeF64.into()
1466 );
1467 }
1468
1469 let mut int_secs = secs.trunc() as i64;
1470 let mut int_nanos =
1471 (secs.fract() * (NANOS_PER_SEC as f64)).round() as i32;
1472 if int_nanos.unsigned_abs() == 1_000_000_000 {
1473 let increment = i64::from(int_nanos.signum());
1474 int_secs = int_secs
1475 .checked_add(increment)
1476 .ok_or_else(b::SignedDurationSeconds::error)?;
1477 int_nanos = 0;
1478 }
1479 Ok(SignedDuration::new_unchecked(int_secs, int_nanos))
1480 }
1481
1482 /// Returns a signed duration corresponding to the number of seconds
1483 /// represented as a 32-bit float. The number given may have a fractional
1484 /// nanosecond component.
1485 ///
1486 /// If the given float overflows the minimum or maximum signed duration
1487 /// values, then an error is returned.
1488 ///
1489 /// # Example
1490 ///
1491 /// ```
1492 /// use jiff::SignedDuration;
1493 ///
1494 /// let duration = SignedDuration::try_from_secs_f32(12.123456789)?;
1495 /// assert_eq!(duration.as_secs(), 12);
1496 /// // loss of precision!
1497 /// assert_eq!(duration.subsec_nanos(), 123_456_952);
1498 ///
1499 /// let duration = SignedDuration::try_from_secs_f32(-12.123456789)?;
1500 /// assert_eq!(duration.as_secs(), -12);
1501 /// // loss of precision!
1502 /// assert_eq!(duration.subsec_nanos(), -123_456_952);
1503 ///
1504 /// assert!(SignedDuration::try_from_secs_f32(f32::NAN).is_err());
1505 /// assert!(SignedDuration::try_from_secs_f32(f32::INFINITY).is_err());
1506 /// assert!(SignedDuration::try_from_secs_f32(f32::NEG_INFINITY).is_err());
1507 /// assert!(SignedDuration::try_from_secs_f32(f32::MIN).is_err());
1508 /// assert!(SignedDuration::try_from_secs_f32(f32::MAX).is_err());
1509 ///
1510 /// # Ok::<(), Box<dyn std::error::Error>>(())
1511 /// ```
1512 #[inline]
1513 pub fn try_from_secs_f32(secs: f32) -> Result<SignedDuration, Error> {
1514 #[cfg(not(feature = "std"))]
1515 use crate::util::libm::Float;
1516
1517 if !secs.is_finite() {
1518 return Err(Error::from(E::ConvertNonFinite));
1519 }
1520 if !((i64::MIN as f32) <= secs && secs <= (i64::MAX as f32)) {
1521 return Err(
1522 SpecialBoundsError::SignedDurationFloatOutOfRangeF32.into()
1523 );
1524 }
1525
1526 let mut int_nanos =
1527 (secs.fract() * (NANOS_PER_SEC as f32)).round() as i32;
1528 let mut int_secs = secs.trunc() as i64;
1529 if int_nanos.unsigned_abs() == 1_000_000_000 {
1530 let increment = i64::from(int_nanos.signum());
1531 // N.B. I haven't found a way to trigger this error path in tests.
1532 int_secs = int_secs
1533 .checked_add(increment)
1534 .ok_or_else(b::SignedDurationSeconds::error)?;
1535 int_nanos = 0;
1536 }
1537 Ok(SignedDuration::new_unchecked(int_secs, int_nanos))
1538 }
1539
1540 /// Returns the result of multiplying this duration by the given 64-bit
1541 /// float.
1542 ///
1543 /// # Panics
1544 ///
1545 /// This panics if the result is not finite or overflows a
1546 /// `SignedDuration`.
1547 ///
1548 /// # Example
1549 ///
1550 /// ```
1551 /// use jiff::SignedDuration;
1552 ///
1553 /// let duration = SignedDuration::new(12, 300_000_000);
1554 /// assert_eq!(
1555 /// duration.mul_f64(2.0),
1556 /// SignedDuration::new(24, 600_000_000),
1557 /// );
1558 /// assert_eq!(
1559 /// duration.mul_f64(-2.0),
1560 /// SignedDuration::new(-24, -600_000_000),
1561 /// );
1562 /// ```
1563 #[inline]
1564 pub fn mul_f64(self, rhs: f64) -> SignedDuration {
1565 SignedDuration::from_secs_f64(rhs * self.as_secs_f64())
1566 }
1567
1568 /// Returns the result of multiplying this duration by the given 32-bit
1569 /// float.
1570 ///
1571 /// # Panics
1572 ///
1573 /// This panics if the result is not finite or overflows a
1574 /// `SignedDuration`.
1575 ///
1576 /// # Example
1577 ///
1578 /// ```
1579 /// use jiff::SignedDuration;
1580 ///
1581 /// let duration = SignedDuration::new(12, 300_000_000);
1582 /// assert_eq!(
1583 /// duration.mul_f32(2.0),
1584 /// // loss of precision!
1585 /// SignedDuration::new(24, 600_000_384),
1586 /// );
1587 /// assert_eq!(
1588 /// duration.mul_f32(-2.0),
1589 /// // loss of precision!
1590 /// SignedDuration::new(-24, -600_000_384),
1591 /// );
1592 /// ```
1593 #[inline]
1594 pub fn mul_f32(self, rhs: f32) -> SignedDuration {
1595 SignedDuration::from_secs_f32(rhs * self.as_secs_f32())
1596 }
1597
1598 /// Returns the result of dividing this duration by the given 64-bit
1599 /// float.
1600 ///
1601 /// # Panics
1602 ///
1603 /// This panics if the result is not finite or overflows a
1604 /// `SignedDuration`.
1605 ///
1606 /// # Example
1607 ///
1608 /// ```
1609 /// use jiff::SignedDuration;
1610 ///
1611 /// let duration = SignedDuration::new(12, 300_000_000);
1612 /// assert_eq!(
1613 /// duration.div_f64(2.0),
1614 /// SignedDuration::new(6, 150_000_000),
1615 /// );
1616 /// assert_eq!(
1617 /// duration.div_f64(-2.0),
1618 /// SignedDuration::new(-6, -150_000_000),
1619 /// );
1620 /// ```
1621 #[inline]
1622 pub fn div_f64(self, rhs: f64) -> SignedDuration {
1623 SignedDuration::from_secs_f64(self.as_secs_f64() / rhs)
1624 }
1625
1626 /// Returns the result of dividing this duration by the given 32-bit
1627 /// float.
1628 ///
1629 /// # Panics
1630 ///
1631 /// This panics if the result is not finite or overflows a
1632 /// `SignedDuration`.
1633 ///
1634 /// # Example
1635 ///
1636 /// ```
1637 /// use jiff::SignedDuration;
1638 ///
1639 /// let duration = SignedDuration::new(12, 300_000_000);
1640 /// assert_eq!(
1641 /// duration.div_f32(2.0),
1642 /// // loss of precision!
1643 /// SignedDuration::new(6, 150_000_096),
1644 /// );
1645 /// assert_eq!(
1646 /// duration.div_f32(-2.0),
1647 /// // loss of precision!
1648 /// SignedDuration::new(-6, -150_000_096),
1649 /// );
1650 /// ```
1651 #[inline]
1652 pub fn div_f32(self, rhs: f32) -> SignedDuration {
1653 SignedDuration::from_secs_f32(self.as_secs_f32() / rhs)
1654 }
1655
1656 /// Divides this signed duration by another signed duration and returns the
1657 /// corresponding 64-bit float result.
1658 ///
1659 /// # Example
1660 ///
1661 /// ```
1662 /// use jiff::SignedDuration;
1663 ///
1664 /// let duration1 = SignedDuration::new(12, 600_000_000);
1665 /// let duration2 = SignedDuration::new(6, 300_000_000);
1666 /// assert_eq!(duration1.div_duration_f64(duration2), 2.0);
1667 ///
1668 /// let duration1 = SignedDuration::new(-12, -600_000_000);
1669 /// let duration2 = SignedDuration::new(6, 300_000_000);
1670 /// assert_eq!(duration1.div_duration_f64(duration2), -2.0);
1671 ///
1672 /// let duration1 = SignedDuration::new(-12, -600_000_000);
1673 /// let duration2 = SignedDuration::new(-6, -300_000_000);
1674 /// assert_eq!(duration1.div_duration_f64(duration2), 2.0);
1675 /// ```
1676 #[inline]
1677 pub fn div_duration_f64(self, rhs: SignedDuration) -> f64 {
1678 let lhs_nanos =
1679 (self.secs as f64) * (NANOS_PER_SEC as f64) + (self.nanos as f64);
1680 let rhs_nanos =
1681 (rhs.secs as f64) * (NANOS_PER_SEC as f64) + (rhs.nanos as f64);
1682 lhs_nanos / rhs_nanos
1683 }
1684
1685 /// Divides this signed duration by another signed duration and returns the
1686 /// corresponding 32-bit float result.
1687 ///
1688 /// # Example
1689 ///
1690 /// ```
1691 /// use jiff::SignedDuration;
1692 ///
1693 /// let duration1 = SignedDuration::new(12, 600_000_000);
1694 /// let duration2 = SignedDuration::new(6, 300_000_000);
1695 /// assert_eq!(duration1.div_duration_f32(duration2), 2.0);
1696 ///
1697 /// let duration1 = SignedDuration::new(-12, -600_000_000);
1698 /// let duration2 = SignedDuration::new(6, 300_000_000);
1699 /// assert_eq!(duration1.div_duration_f32(duration2), -2.0);
1700 ///
1701 /// let duration1 = SignedDuration::new(-12, -600_000_000);
1702 /// let duration2 = SignedDuration::new(-6, -300_000_000);
1703 /// assert_eq!(duration1.div_duration_f32(duration2), 2.0);
1704 /// ```
1705 #[inline]
1706 pub fn div_duration_f32(self, rhs: SignedDuration) -> f32 {
1707 let lhs_nanos =
1708 (self.secs as f32) * (NANOS_PER_SEC as f32) + (self.nanos as f32);
1709 let rhs_nanos =
1710 (rhs.secs as f32) * (NANOS_PER_SEC as f32) + (rhs.nanos as f32);
1711 lhs_nanos / rhs_nanos
1712 }
1713}
1714
1715/// Additional APIs not found in the standard library.
1716///
1717/// In some cases, these APIs exist as a result of the fact that this duration
1718/// is signed.
1719impl SignedDuration {
1720 /// Fallibly creates a new `SignedDuration` from a 64-bit integer number
1721 /// of hours.
1722 ///
1723 /// If the number of hours is less than [`SignedDuration::MIN`] or
1724 /// more than [`SignedDuration::MAX`], then this returns `None`.
1725 ///
1726 /// # Example
1727 ///
1728 /// ```
1729 /// use jiff::SignedDuration;
1730 ///
1731 /// assert_eq!(SignedDuration::try_from_hours(i64::MAX), None);
1732 /// ```
1733 #[inline]
1734 pub const fn try_from_hours(hours: i64) -> Option<SignedDuration> {
1735 // OK because (SECS_PER_MINUTE*MINS_PER_HOUR)!={-1,0}.
1736 const MIN_HOUR: i64 = i64::MIN / (SECS_PER_MINUTE * MINS_PER_HOUR);
1737 // OK because (SECS_PER_MINUTE*MINS_PER_HOUR)!={-1,0}.
1738 const MAX_HOUR: i64 = i64::MAX / (SECS_PER_MINUTE * MINS_PER_HOUR);
1739 if !(MIN_HOUR <= hours && hours <= MAX_HOUR) {
1740 return None;
1741 }
1742 Some(SignedDuration::from_secs(
1743 hours * MINS_PER_HOUR * SECS_PER_MINUTE,
1744 ))
1745 }
1746
1747 /// Fallibly creates a new `SignedDuration` from a 64-bit integer number
1748 /// of minutes.
1749 ///
1750 /// If the number of minutes is less than [`SignedDuration::MIN`] or
1751 /// more than [`SignedDuration::MAX`], then this returns `None`.
1752 ///
1753 /// # Example
1754 ///
1755 /// ```
1756 /// use jiff::SignedDuration;
1757 ///
1758 /// assert_eq!(SignedDuration::try_from_mins(i64::MAX), None);
1759 /// ```
1760 #[inline]
1761 pub const fn try_from_mins(mins: i64) -> Option<SignedDuration> {
1762 // OK because SECS_PER_MINUTE!={-1,0}.
1763 const MIN_MINUTE: i64 = i64::MIN / SECS_PER_MINUTE;
1764 // OK because SECS_PER_MINUTE!={-1,0}.
1765 const MAX_MINUTE: i64 = i64::MAX / SECS_PER_MINUTE;
1766 if !(MIN_MINUTE <= mins && mins <= MAX_MINUTE) {
1767 return None;
1768 }
1769 Some(SignedDuration::from_secs(mins * SECS_PER_MINUTE))
1770 }
1771
1772 /// Fallibly creates a new `SignedDuration` from a 128-bit integer number
1773 /// of milliseconds.
1774 ///
1775 /// If the number of milliseconds is less than [`SignedDuration::MIN`] or
1776 /// more than [`SignedDuration::MAX`], then this returns `None`.
1777 ///
1778 /// # Example
1779 ///
1780 /// ```
1781 /// use jiff::SignedDuration;
1782 ///
1783 /// assert_eq!(SignedDuration::try_from_millis_i128(i128::MAX), None);
1784 /// ```
1785 #[inline]
1786 pub const fn try_from_millis_i128(millis: i128) -> Option<SignedDuration> {
1787 const MILLIS_PER_SEC: i128 = self::MILLIS_PER_SEC as i128;
1788 // OK because MILLIS_PER_SEC!={-1,0}.
1789 let secs = millis / MILLIS_PER_SEC;
1790 // RUST: Use `i64::try_from` when available in `const`.
1791 if !(i64::MIN as i128 <= secs && secs <= i64::MAX as i128) {
1792 return None;
1793 }
1794 let secs64 = secs as i64;
1795 // OK because NANOS_PER_SEC!={-1,0} and because
1796 // micros % MILLIS_PER_SEC can be at most 999, and 999 * 1_000_000
1797 // never overflows i32.
1798 let nanos = (millis % MILLIS_PER_SEC) as i32 * NANOS_PER_MILLI;
1799 Some(SignedDuration::new_unchecked(secs64, nanos))
1800 }
1801
1802 /// Fallibly creates a new `SignedDuration` from a 128-bit integer number
1803 /// of microseconds.
1804 ///
1805 /// If the number of microseconds is less than [`SignedDuration::MIN`] or
1806 /// more than [`SignedDuration::MAX`], then this returns `None`.
1807 ///
1808 /// # Example
1809 ///
1810 /// ```
1811 /// use jiff::SignedDuration;
1812 ///
1813 /// assert_eq!(SignedDuration::try_from_micros_i128(i128::MAX), None);
1814 /// ```
1815 #[inline]
1816 pub const fn try_from_micros_i128(micros: i128) -> Option<SignedDuration> {
1817 const MICROS_PER_SEC: i128 = self::MICROS_PER_SEC as i128;
1818 // OK because MICROS_PER_SEC!={-1,0}.
1819 let secs = micros / MICROS_PER_SEC;
1820 // RUST: Use `i64::try_from` when available in `const`.
1821 if !(i64::MIN as i128 <= secs && secs <= i64::MAX as i128) {
1822 return None;
1823 }
1824 let secs64 = secs as i64;
1825 // OK because NANOS_PER_SEC!={-1,0} and because
1826 // micros % MICROS_PER_SEC can be at most 999_999, and 999_999 * 1_000
1827 // never overflows i32.
1828 let nanos = (micros % MICROS_PER_SEC) as i32 * NANOS_PER_MICRO;
1829 Some(SignedDuration::new_unchecked(secs64, nanos))
1830 }
1831
1832 /// Fallibly creates a new `SignedDuration` from a 128-bit integer number
1833 /// of nanoseconds.
1834 ///
1835 /// If the number of nanoseconds is less than [`SignedDuration::MIN`] or
1836 /// more than [`SignedDuration::MAX`], then this returns `None`.
1837 ///
1838 /// # Example
1839 ///
1840 /// ```
1841 /// use jiff::SignedDuration;
1842 ///
1843 /// assert_eq!(SignedDuration::try_from_nanos_i128(i128::MAX), None);
1844 /// ```
1845 #[inline]
1846 pub const fn try_from_nanos_i128(nanos: i128) -> Option<SignedDuration> {
1847 const NANOS_PER_SEC: i128 = self::NANOS_PER_SEC as i128;
1848 // OK because NANOS_PER_SEC!={-1,0}.
1849 let secs = nanos / NANOS_PER_SEC;
1850 // RUST: Use `i64::try_from` when available in `const`.
1851 if !(i64::MIN as i128 <= secs && secs <= i64::MAX as i128) {
1852 return None;
1853 }
1854 let secs64 = secs as i64;
1855 // OK because NANOS_PER_SEC!={-1,0}.
1856 let nanos = (nanos % NANOS_PER_SEC) as i32;
1857 Some(SignedDuration::new_unchecked(secs64, nanos))
1858 }
1859
1860 /// Returns the number of whole hours in this duration.
1861 ///
1862 /// The value returned is negative when the duration is negative.
1863 ///
1864 /// This does not include any fractional component corresponding to units
1865 /// less than an hour.
1866 ///
1867 /// # Example
1868 ///
1869 /// ```
1870 /// use jiff::SignedDuration;
1871 ///
1872 /// let duration = SignedDuration::new(86_400, 999_999_999);
1873 /// assert_eq!(duration.as_hours(), 24);
1874 ///
1875 /// let duration = SignedDuration::new(-86_400, -999_999_999);
1876 /// assert_eq!(duration.as_hours(), -24);
1877 /// ```
1878 #[inline]
1879 pub const fn as_hours(&self) -> i64 {
1880 self.as_secs() / (MINS_PER_HOUR * SECS_PER_MINUTE)
1881 }
1882
1883 /// Returns the number of whole minutes in this duration.
1884 ///
1885 /// The value returned is negative when the duration is negative.
1886 ///
1887 /// This does not include any fractional component corresponding to units
1888 /// less than a minute.
1889 ///
1890 /// # Example
1891 ///
1892 /// ```
1893 /// use jiff::SignedDuration;
1894 ///
1895 /// let duration = SignedDuration::new(3_600, 999_999_999);
1896 /// assert_eq!(duration.as_mins(), 60);
1897 ///
1898 /// let duration = SignedDuration::new(-3_600, -999_999_999);
1899 /// assert_eq!(duration.as_mins(), -60);
1900 /// ```
1901 #[inline]
1902 pub const fn as_mins(&self) -> i64 {
1903 self.as_secs() / SECS_PER_MINUTE
1904 }
1905
1906 /// Returns the absolute value of this signed duration.
1907 ///
1908 /// If this duration isn't negative, then this returns the original
1909 /// duration unchanged.
1910 ///
1911 /// # Panics
1912 ///
1913 /// This panics when the seconds component of this signed duration is
1914 /// equal to `i64::MIN`.
1915 ///
1916 /// # Example
1917 ///
1918 /// ```
1919 /// use jiff::SignedDuration;
1920 ///
1921 /// let duration = SignedDuration::new(1, -1_999_999_999);
1922 /// assert_eq!(duration.abs(), SignedDuration::new(0, 999_999_999));
1923 /// ```
1924 #[inline]
1925 pub const fn abs(self) -> SignedDuration {
1926 SignedDuration::new_unchecked(self.secs.abs(), self.nanos.abs())
1927 }
1928
1929 /// Returns the absolute value of this signed duration as a
1930 /// [`std::time::Duration`]. More specifically, this routine cannot
1931 /// panic because the absolute value of `SignedDuration::MIN` is
1932 /// representable in a `std::time::Duration`.
1933 ///
1934 /// # Example
1935 ///
1936 /// ```
1937 /// use std::time::Duration;
1938 ///
1939 /// use jiff::SignedDuration;
1940 ///
1941 /// let duration = SignedDuration::MIN;
1942 /// assert_eq!(
1943 /// duration.unsigned_abs(),
1944 /// Duration::new(i64::MIN.unsigned_abs(), 999_999_999),
1945 /// );
1946 /// ```
1947 #[inline]
1948 pub const fn unsigned_abs(self) -> Duration {
1949 Duration::new(self.secs.unsigned_abs(), self.nanos.unsigned_abs())
1950 }
1951
1952 /// Returns this duration with its sign flipped.
1953 ///
1954 /// If this duration is zero, then this returns the duration unchanged.
1955 ///
1956 /// This returns none if the negation does not exist. This occurs in
1957 /// precisely the cases when [`SignedDuration::as_secs`] is equal to
1958 /// `i64::MIN`.
1959 ///
1960 /// # Example
1961 ///
1962 /// ```
1963 /// use jiff::SignedDuration;
1964 ///
1965 /// let duration = SignedDuration::new(12, 123_456_789);
1966 /// assert_eq!(
1967 /// duration.checked_neg(),
1968 /// Some(SignedDuration::new(-12, -123_456_789)),
1969 /// );
1970 ///
1971 /// let duration = SignedDuration::new(-12, -123_456_789);
1972 /// assert_eq!(
1973 /// duration.checked_neg(),
1974 /// Some(SignedDuration::new(12, 123_456_789)),
1975 /// );
1976 ///
1977 /// // Negating the minimum seconds isn't possible.
1978 /// assert_eq!(SignedDuration::MIN.checked_neg(), None);
1979 /// ```
1980 #[inline]
1981 pub const fn checked_neg(self) -> Option<SignedDuration> {
1982 let Some(secs) = self.secs.checked_neg() else { return None };
1983 Some(SignedDuration::new_unchecked(
1984 secs,
1985 // Always OK because `-999_999_999 <= self.nanos <= 999_999_999`.
1986 -self.nanos,
1987 ))
1988 }
1989
1990 /// Returns a number that represents the sign of this duration.
1991 ///
1992 /// * When [`SignedDuration::is_zero`] is true, this returns `0`.
1993 /// * When [`SignedDuration::is_positive`] is true, this returns `1`.
1994 /// * When [`SignedDuration::is_negative`] is true, this returns `-1`.
1995 ///
1996 /// The above cases are mutually exclusive.
1997 ///
1998 /// # Example
1999 ///
2000 /// ```
2001 /// use jiff::SignedDuration;
2002 ///
2003 /// assert_eq!(0, SignedDuration::ZERO.signum());
2004 /// ```
2005 #[inline]
2006 pub const fn signum(self) -> i8 {
2007 if self.is_zero() {
2008 0
2009 } else if self.is_positive() {
2010 1
2011 } else {
2012 debug_assert!(self.is_negative());
2013 -1
2014 }
2015 }
2016
2017 /// For internal use with Jiff.
2018 ///
2019 /// This returns a `jcore` type, so this can never be exported! Otherwise
2020 /// it would create a public dependency on `jcore`.
2021 #[inline]
2022 pub(crate) const fn sign(self) -> Sign {
2023 if self.is_zero() {
2024 Sign::Zero
2025 } else if self.is_positive() {
2026 Sign::Positive
2027 } else {
2028 debug_assert!(self.is_negative());
2029 Sign::Negative
2030 }
2031 }
2032
2033 /// Returns true when this duration is positive. That is, greater than
2034 /// [`SignedDuration::ZERO`].
2035 ///
2036 /// # Example
2037 ///
2038 /// ```
2039 /// use jiff::SignedDuration;
2040 ///
2041 /// let duration = SignedDuration::new(0, 1);
2042 /// assert!(duration.is_positive());
2043 /// ```
2044 #[inline]
2045 pub const fn is_positive(&self) -> bool {
2046 self.secs.is_positive() || self.nanos.is_positive()
2047 }
2048
2049 /// Returns true when this duration is negative. That is, less than
2050 /// [`SignedDuration::ZERO`].
2051 ///
2052 /// # Example
2053 ///
2054 /// ```
2055 /// use jiff::SignedDuration;
2056 ///
2057 /// let duration = SignedDuration::new(0, -1);
2058 /// assert!(duration.is_negative());
2059 /// ```
2060 #[inline]
2061 pub const fn is_negative(&self) -> bool {
2062 self.secs.is_negative() || self.nanos.is_negative()
2063 }
2064}
2065
2066/// Additional APIs for computing the duration between date and time values.
2067impl SignedDuration {
2068 pub(crate) fn zoned_datetime_until(
2069 zoned1: &ZonedDateTime,
2070 zoned2: &ZonedDateTime,
2071 ) -> SignedDuration {
2072 SignedDuration::timestamp_until(zoned1.timestamp(), zoned2.timestamp())
2073 }
2074
2075 pub(crate) fn timestamp_until(
2076 timestamp1: Timestamp,
2077 timestamp2: Timestamp,
2078 ) -> SignedDuration {
2079 // OK because all the difference between any two timestamp values can
2080 // fit into a signed duration.
2081 timestamp2.as_duration() - timestamp1.as_duration()
2082 }
2083
2084 pub(crate) fn datetime_until(
2085 datetime1: DateTime,
2086 datetime2: DateTime,
2087 ) -> SignedDuration {
2088 let date_until =
2089 SignedDuration::date_until(datetime1.date(), datetime2.date());
2090 let time_until =
2091 SignedDuration::time_until(datetime1.time(), datetime2.time());
2092 // OK because the difference between any two datetimes can bit into a
2093 // 96-bit integer of nanoseconds.
2094 date_until + time_until
2095 }
2096
2097 pub(crate) fn date_until(date1: Date, date2: Date) -> SignedDuration {
2098 let days = date1.until_days(date2);
2099 // OK because difference in days fits in an i32, and multiplying an
2100 // i32 by 24 will never overflow an i64.
2101 let hours = 24 * i64::from(days);
2102 SignedDuration::from_hours(hours)
2103 }
2104
2105 pub(crate) fn time_until(time1: Time, time2: Time) -> SignedDuration {
2106 SignedDuration::from_nanos(time1.until_nanoseconds(time2))
2107 }
2108
2109 pub(crate) fn offset_until(
2110 offset1: Offset,
2111 offset2: Offset,
2112 ) -> SignedDuration {
2113 let secs1 = i64::from(offset1.seconds());
2114 let secs2 = i64::from(offset2.seconds());
2115 // OK because subtracting any two i32 values will
2116 // never overflow an i64.
2117 let diff = secs2 - secs1;
2118 SignedDuration::from_secs(diff)
2119 }
2120
2121 /// Returns the duration from `time1` until `time2` where the times are
2122 /// [`std::time::SystemTime`] values from the standard library.
2123 ///
2124 /// # Errors
2125 ///
2126 /// This returns an error if the difference between the two time values
2127 /// overflows the signed duration limits.
2128 ///
2129 /// # Example
2130 ///
2131 /// ```
2132 /// use std::time::{Duration, SystemTime};
2133 /// use jiff::SignedDuration;
2134 ///
2135 /// let time1 = SystemTime::UNIX_EPOCH;
2136 /// let time2 = time1.checked_add(Duration::from_secs(86_400)).unwrap();
2137 /// assert_eq!(
2138 /// SignedDuration::system_until(time1, time2)?,
2139 /// SignedDuration::from_hours(24),
2140 /// );
2141 ///
2142 /// # Ok::<(), Box<dyn std::error::Error>>(())
2143 /// ```
2144 #[cfg(feature = "std")]
2145 #[inline]
2146 pub fn system_until(
2147 time1: std::time::SystemTime,
2148 time2: std::time::SystemTime,
2149 ) -> Result<SignedDuration, Error> {
2150 match time2.duration_since(time1) {
2151 Ok(dur) => {
2152 SignedDuration::try_from(dur).context(E::ConvertSystemTime)
2153 }
2154 Err(err) => {
2155 let dur = err.duration();
2156 let dur = SignedDuration::try_from(dur)
2157 .context(E::ConvertSystemTime)?;
2158 dur.checked_neg()
2159 .ok_or_else(b::SignedDurationSeconds::error)
2160 .context(E::ConvertSystemTime)
2161 }
2162 }
2163 }
2164}
2165
2166/// Jiff specific APIs.
2167impl SignedDuration {
2168 /// Returns a new signed duration that is rounded according to the given
2169 /// configuration.
2170 ///
2171 /// Rounding a duration has a number of parameters, all of which are
2172 /// optional. When no parameters are given, then no rounding is done, and
2173 /// the duration as given is returned. That is, it's a no-op.
2174 ///
2175 /// As is consistent with `SignedDuration` itself, rounding only supports
2176 /// time units, i.e., units of hours or smaller. If a calendar `Unit` is
2177 /// provided, then an error is returned. In order to round a duration with
2178 /// calendar units, you must use [`Span::round`](crate::Span::round) and
2179 /// provide a relative datetime.
2180 ///
2181 /// The parameters are, in brief:
2182 ///
2183 /// * [`SignedDurationRound::smallest`] sets the smallest [`Unit`] that
2184 /// is allowed to be non-zero in the duration returned. By default, it
2185 /// is set to [`Unit::Nanosecond`], i.e., no rounding occurs. When the
2186 /// smallest unit is set to something bigger than nanoseconds, then the
2187 /// non-zero units in the duration smaller than the smallest unit are used
2188 /// to determine how the duration should be rounded. For example, rounding
2189 /// `1 hour 59 minutes` to the nearest hour using the default rounding mode
2190 /// would produce `2 hours`.
2191 /// * [`SignedDurationRound::mode`] determines how to handle the remainder
2192 /// when rounding. The default is [`RoundMode::HalfExpand`], which
2193 /// corresponds to how you were likely taught to round in school.
2194 /// Alternative modes, like [`RoundMode::Trunc`], exist too. For example,
2195 /// a truncating rounding of `1 hour 59 minutes` to the nearest hour would
2196 /// produce `1 hour`.
2197 /// * [`SignedDurationRound::increment`] sets the rounding granularity to
2198 /// use for the configured smallest unit. For example, if the smallest unit
2199 /// is minutes and the increment is 5, then the duration returned will
2200 /// always have its minute units set to a multiple of `5`.
2201 ///
2202 /// # Errors
2203 ///
2204 /// In general, there are two main ways for rounding to fail: an improper
2205 /// configuration like trying to round a duration to the nearest calendar
2206 /// unit, or when overflow occurs. Overflow can occur when the duration
2207 /// would exceed the minimum or maximum `SignedDuration` values. Typically,
2208 /// this can only realistically happen if the duration before rounding is
2209 /// already close to its minimum or maximum value.
2210 ///
2211 /// # Example: round to the nearest second
2212 ///
2213 /// This shows how to round a duration to the nearest second. This might
2214 /// be useful when you want to chop off any sub-second component in a way
2215 /// that depends on how close it is (or not) to the next second.
2216 ///
2217 /// ```
2218 /// use jiff::{SignedDuration, Unit};
2219 ///
2220 /// // rounds up
2221 /// let dur = SignedDuration::new(4 * 60 * 60 + 50 * 60 + 32, 500_000_000);
2222 /// assert_eq!(
2223 /// dur.round(Unit::Second)?,
2224 /// SignedDuration::new(4 * 60 * 60 + 50 * 60 + 33, 0),
2225 /// );
2226 /// // rounds down
2227 /// let dur = SignedDuration::new(4 * 60 * 60 + 50 * 60 + 32, 499_999_999);
2228 /// assert_eq!(
2229 /// dur.round(Unit::Second)?,
2230 /// SignedDuration::new(4 * 60 * 60 + 50 * 60 + 32, 0),
2231 /// );
2232 ///
2233 /// # Ok::<(), Box<dyn std::error::Error>>(())
2234 /// ```
2235 ///
2236 /// # Example: round to the nearest half minute
2237 ///
2238 /// One can use [`SignedDurationRound::increment`] to set the rounding
2239 /// increment:
2240 ///
2241 /// ```
2242 /// use jiff::{SignedDuration, SignedDurationRound, Unit};
2243 ///
2244 /// let options = SignedDurationRound::new()
2245 /// .smallest(Unit::Second)
2246 /// .increment(30);
2247 ///
2248 /// // rounds up
2249 /// let dur = SignedDuration::from_secs(4 * 60 * 60 + 50 * 60 + 15);
2250 /// assert_eq!(
2251 /// dur.round(options)?,
2252 /// SignedDuration::from_secs(4 * 60 * 60 + 50 * 60 + 30),
2253 /// );
2254 /// // rounds down
2255 /// let dur = SignedDuration::from_secs(4 * 60 * 60 + 50 * 60 + 14);
2256 /// assert_eq!(
2257 /// dur.round(options)?,
2258 /// SignedDuration::from_secs(4 * 60 * 60 + 50 * 60),
2259 /// );
2260 ///
2261 /// # Ok::<(), Box<dyn std::error::Error>>(())
2262 /// ```
2263 ///
2264 /// # Example: overflow results in an error
2265 ///
2266 /// If rounding would result in a value that exceeds a `SignedDuration`'s
2267 /// minimum or maximum values, then an error occurs:
2268 ///
2269 /// ```
2270 /// use jiff::{SignedDuration, Unit};
2271 ///
2272 /// assert_eq!(
2273 /// SignedDuration::MAX.round(Unit::Hour).unwrap_err().to_string(),
2274 /// "rounding signed duration to nearest hour resulted in a value \
2275 /// outside the supported range of a `jiff::SignedDuration`: \
2276 /// parameter 'signed duration seconds' is not in the \
2277 /// required range of -9223372036854775808..=9223372036854775807",
2278 /// );
2279 /// assert_eq!(
2280 /// SignedDuration::MIN.round(Unit::Hour).unwrap_err().to_string(),
2281 /// "rounding signed duration to nearest hour resulted in a value \
2282 /// outside the supported range of a `jiff::SignedDuration`: \
2283 /// parameter 'signed duration seconds' is not in the \
2284 /// required range of -9223372036854775808..=9223372036854775807",
2285 /// );
2286 /// ```
2287 ///
2288 /// # Example: rounding with a calendar unit results in an error
2289 ///
2290 /// ```
2291 /// use jiff::{SignedDuration, Unit};
2292 ///
2293 /// assert_eq!(
2294 /// SignedDuration::ZERO.round(Unit::Day).unwrap_err().to_string(),
2295 /// "rounding `jiff::SignedDuration` failed \
2296 /// because the smallest unit provided, 'days', \
2297 /// is a calendar unit \
2298 /// (to round by calendar units, you must use a `jiff::Span`)",
2299 /// );
2300 /// ```
2301 #[inline]
2302 pub fn round<R: Into<SignedDurationRound>>(
2303 self,
2304 options: R,
2305 ) -> Result<SignedDuration, Error> {
2306 let options: SignedDurationRound = options.into();
2307 options.round(self)
2308 }
2309}
2310
2311/// Internal helpers used by Jiff.
2312///
2313/// NOTE: It is sad that some of these helpers can't really be implemented
2314/// as efficiently outside of Jiff. If we exposed a `new_unchecked`
2315/// constructor, then I believe that would be sufficient.
2316impl SignedDuration {
2317 /// Creates a signed duration from a 32-bit number of civil weeks. (That
2318 /// is, every day is exactly 24 hours long and every week is 7 such days.)
2319 ///
2320 /// This is infallible. It can never panic.
2321 #[inline]
2322 pub(crate) const fn from_civil_weeks32(weeks: i32) -> SignedDuration {
2323 SignedDuration::from_secs(
2324 (weeks as i64)
2325 * DAYS_PER_CIVIL_WEEK
2326 * HOURS_PER_CIVIL_DAY
2327 * MINS_PER_HOUR
2328 * SECS_PER_MINUTE,
2329 )
2330 }
2331
2332 /// Creates a signed duration from a 32-bit number of civil days. (That is,
2333 /// every day is exactly 24 hours long.)
2334 ///
2335 /// This is infallible. It can never panic.
2336 #[inline]
2337 pub(crate) const fn from_civil_days32(days: i32) -> SignedDuration {
2338 SignedDuration::from_secs(
2339 (days as i64)
2340 * HOURS_PER_CIVIL_DAY
2341 * MINS_PER_HOUR
2342 * SECS_PER_MINUTE,
2343 )
2344 }
2345
2346 /// Like `SignedDuration::from_hours`, but for 32-bit integers
2347 /// and thus infallible (including never panicking).
2348 #[inline]
2349 pub(crate) const fn from_hours32(hours: i32) -> SignedDuration {
2350 SignedDuration::from_secs(
2351 (hours as i64) * MINS_PER_HOUR * SECS_PER_MINUTE,
2352 )
2353 }
2354
2355 /// Like `SignedDuration::from_mins`, but for 32-bit integers
2356 /// and thus infallible (including never panicking).
2357 #[allow(dead_code)]
2358 #[inline]
2359 pub(crate) const fn from_mins32(mins: i32) -> SignedDuration {
2360 SignedDuration::from_secs((mins as i64) * SECS_PER_MINUTE)
2361 }
2362
2363 /// Returns the number of whole civil weeks in this duration.
2364 #[inline]
2365 pub(crate) const fn as_civil_weeks(&self) -> i64 {
2366 self.as_secs()
2367 / (DAYS_PER_CIVIL_WEEK
2368 * HOURS_PER_CIVIL_DAY
2369 * MINS_PER_HOUR
2370 * SECS_PER_MINUTE)
2371 }
2372
2373 /// Returns the number of whole civil days in this duration.
2374 #[inline]
2375 pub(crate) const fn as_civil_days(&self) -> i64 {
2376 self.as_secs()
2377 / (HOURS_PER_CIVIL_DAY * MINS_PER_HOUR * SECS_PER_MINUTE)
2378 }
2379
2380 /// Returns the number of whole civil weeks in this duration (equivalent to
2381 /// `SignedDuration::as_civil_weeks`) along with a duration equivalent to
2382 /// the fractional remainder.
2383 #[inline]
2384 pub(crate) fn as_civil_weeks_with_remainder(
2385 &self,
2386 ) -> (i64, SignedDuration) {
2387 let weeks = self.as_civil_weeks();
2388 let secs = self.as_secs()
2389 % (DAYS_PER_CIVIL_WEEK
2390 * HOURS_PER_CIVIL_DAY
2391 * MINS_PER_HOUR
2392 * SECS_PER_MINUTE);
2393 let rem = SignedDuration::new_unchecked(secs, self.subsec_nanos());
2394 (weeks, rem)
2395 }
2396
2397 /// Returns the number of whole civil days in this duration (equivalent to
2398 /// `SignedDuration::as_civil_days`) along with a duration equivalent to
2399 /// the fractional remainder.
2400 #[inline]
2401 pub(crate) fn as_civil_days_with_remainder(
2402 &self,
2403 ) -> (i64, SignedDuration) {
2404 let days = self.as_civil_days();
2405 let secs = self.as_secs()
2406 % (HOURS_PER_CIVIL_DAY * MINS_PER_HOUR * SECS_PER_MINUTE);
2407 let rem = SignedDuration::new_unchecked(secs, self.subsec_nanos());
2408 (days, rem)
2409 }
2410
2411 /// Returns the number of whole hours in this duration (equivalent to
2412 /// `SignedDuration::as_hours`) along with a duration equivalent to the
2413 /// fractional remainder.
2414 #[inline]
2415 pub(crate) fn as_hours_with_remainder(&self) -> (i64, SignedDuration) {
2416 let hours = self.as_hours();
2417 let secs = self.as_secs() % (MINS_PER_HOUR * SECS_PER_MINUTE);
2418 let rem = SignedDuration::new_unchecked(secs, self.subsec_nanos());
2419 (hours, rem)
2420 }
2421
2422 /// Returns the number of whole minutes in this duration (equivalent to
2423 /// `SignedDuration::as_mins`) along with a duration equivalent to the
2424 /// fractional remainder.
2425 #[inline]
2426 pub(crate) fn as_mins_with_remainder(&self) -> (i64, SignedDuration) {
2427 let mins = self.as_mins();
2428 let secs = self.as_secs() % SECS_PER_MINUTE;
2429 let rem = SignedDuration::new_unchecked(secs, self.subsec_nanos());
2430 (mins, rem)
2431 }
2432
2433 /// Returns the number of whole seconds in this duration (equivalent to
2434 /// `SignedDuration::as_secs`) along with a duration equivalent to the
2435 /// fractional remainder.
2436 #[inline]
2437 pub(crate) fn as_secs_with_remainder(&self) -> (i64, SignedDuration) {
2438 let secs = self.as_secs();
2439 let rem = SignedDuration::new_unchecked(0, self.subsec_nanos());
2440 (secs, rem)
2441 }
2442
2443 /// Returns the number of whole milliseconds in this duration (equivalent
2444 /// to `SignedDuration::as_millis`) along with a duration equivalent to the
2445 /// fractional remainder.
2446 #[inline]
2447 pub(crate) fn as_millis_with_remainder(&self) -> (i128, SignedDuration) {
2448 let millis = self.as_millis();
2449 let nanos = self.subsec_nanos() % NANOS_PER_MILLI;
2450 let rem = SignedDuration::new_unchecked(0, nanos);
2451 (millis, rem)
2452 }
2453
2454 /// Returns the number of whole microseconds in this duration (equivalent
2455 /// to `SignedDuration::as_micros`) along with a duration equivalent to the
2456 /// fractional remainder.
2457 #[inline]
2458 pub(crate) fn as_micros_with_remainder(&self) -> (i128, SignedDuration) {
2459 let micros = self.as_micros();
2460 let nanos = self.subsec_nanos() % NANOS_PER_MICRO;
2461 let rem = SignedDuration::new_unchecked(0, nanos);
2462 (micros, rem)
2463 }
2464}
2465
2466impl core::fmt::Display for SignedDuration {
2467 #[inline]
2468 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2469 use crate::fmt::StdFmtWrite;
2470
2471 if f.alternate() {
2472 friendly::DEFAULT_SPAN_PRINTER
2473 .print_duration(self, StdFmtWrite(f))
2474 .map_err(|_| core::fmt::Error)
2475 } else {
2476 temporal::DEFAULT_SPAN_PRINTER
2477 .print_duration(self, StdFmtWrite(f))
2478 .map_err(|_| core::fmt::Error)
2479 }
2480 }
2481}
2482
2483impl core::fmt::Debug for SignedDuration {
2484 #[inline]
2485 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2486 use crate::fmt::StdFmtWrite;
2487
2488 if f.alternate() {
2489 if self.subsec_nanos() == 0 {
2490 core::fmt::Display::fmt(&self.as_secs(), f)?;
2491 f.write_str("s")
2492 } else if self.as_secs() == 0 {
2493 core::fmt::Display::fmt(&self.subsec_nanos(), f)?;
2494 f.write_str("ns")
2495 } else {
2496 core::fmt::Display::fmt(&self.as_secs(), f)?;
2497 f.write_str("s ")?;
2498 core::fmt::Display::fmt(
2499 &self.subsec_nanos().unsigned_abs(),
2500 f,
2501 )?;
2502 f.write_str("ns")
2503 }
2504 } else {
2505 friendly::DEFAULT_SPAN_PRINTER
2506 .print_duration(self, StdFmtWrite(f))
2507 .map_err(|_| core::fmt::Error)
2508 }
2509 }
2510}
2511
2512/// Fallibly converts a [`std::time::Duration`] to a `SignedDuration`.
2513///
2514/// # Errors
2515///
2516/// This fails when the duration's second component exceeds `i64::MAX`.
2517///
2518/// # Examples
2519///
2520/// ```
2521/// use std::time::Duration;
2522///
2523/// use jiff::SignedDuration;
2524///
2525/// let dur = Duration::new(5, 123_000_000);
2526/// let sdur = SignedDuration::try_from(dur)?;
2527/// assert_eq!(sdur, SignedDuration::new(5, 123_000_000));
2528///
2529/// let dur = Duration::new(i64::MAX as u64, 999_999_999);
2530/// let sdur = SignedDuration::try_from(dur)?;
2531/// assert_eq!(sdur, SignedDuration::new(i64::MAX, 999_999_999));
2532///
2533/// // Some failure cases:
2534/// assert!(SignedDuration::try_from(Duration::new(i64::MAX as u64 + 1, 0)).is_err());
2535/// assert!(SignedDuration::try_from(Duration::new(u64::MAX, 0)).is_err());
2536///
2537/// # Ok::<(), Box<dyn std::error::Error>>(())
2538/// ```
2539impl TryFrom<Duration> for SignedDuration {
2540 type Error = Error;
2541
2542 fn try_from(d: Duration) -> Result<SignedDuration, Error> {
2543 let secs = i64::try_from(d.as_secs())
2544 .map_err(|_| b::SignedDurationSeconds::error())?;
2545 // Guaranteed to succeed since 0<=nanos<=999,999,999.
2546 let nanos = i32::try_from(d.subsec_nanos()).unwrap();
2547 Ok(SignedDuration::new_unchecked(secs, nanos))
2548 }
2549}
2550
2551/// Fallibly converts a `SignedDuration` to a [`std::time::Duration`].
2552///
2553/// # Errors
2554///
2555/// This fails when the signed duration is negative.
2556///
2557/// # Examples
2558///
2559/// ```
2560/// use std::time::Duration;
2561///
2562/// use jiff::SignedDuration;
2563///
2564/// let sdur = SignedDuration::new(5, 123_000_000);
2565/// let dur = Duration::try_from(sdur)?;
2566/// assert_eq!(dur, Duration::new(5, 123_000_000));
2567///
2568/// // Some failure cases:
2569/// assert!(Duration::try_from(SignedDuration::new(-5, 0)).is_err());
2570/// assert!(Duration::try_from(SignedDuration::new(-5, -1)).is_err());
2571/// assert!(Duration::try_from(SignedDuration::new(0, -1)).is_err());
2572///
2573/// # Ok::<(), Box<dyn std::error::Error>>(())
2574/// ```
2575impl TryFrom<SignedDuration> for Duration {
2576 type Error = Error;
2577
2578 fn try_from(sd: SignedDuration) -> Result<Duration, Error> {
2579 let secs = u64::try_from(sd.as_secs())
2580 .map_err(|_| SpecialBoundsError::SignedToUnsignedDuration)?;
2581 // This could still be negative in the case where
2582 // `sd.as_secs()` is zero.
2583 let nanos = u32::try_from(sd.subsec_nanos())
2584 .map_err(|_| SpecialBoundsError::SignedToUnsignedDuration)?;
2585 Ok(Duration::new(secs, nanos))
2586 }
2587}
2588
2589impl From<Offset> for SignedDuration {
2590 fn from(offset: Offset) -> SignedDuration {
2591 SignedDuration::from_secs(i64::from(offset.seconds()))
2592 }
2593}
2594
2595impl core::str::FromStr for SignedDuration {
2596 type Err = Error;
2597
2598 #[inline]
2599 fn from_str(string: &str) -> Result<SignedDuration, Error> {
2600 parse_iso_or_friendly(string.as_bytes())
2601 }
2602}
2603
2604impl core::ops::Neg for SignedDuration {
2605 type Output = SignedDuration;
2606
2607 #[inline]
2608 fn neg(self) -> SignedDuration {
2609 self.checked_neg().expect("overflow when negating signed duration")
2610 }
2611}
2612
2613impl core::ops::Add for SignedDuration {
2614 type Output = SignedDuration;
2615
2616 #[inline]
2617 fn add(self, rhs: SignedDuration) -> SignedDuration {
2618 self.checked_add(rhs).expect("overflow when adding signed durations")
2619 }
2620}
2621
2622impl core::ops::AddAssign for SignedDuration {
2623 #[inline]
2624 fn add_assign(&mut self, rhs: SignedDuration) {
2625 *self = *self + rhs;
2626 }
2627}
2628
2629impl core::ops::Sub for SignedDuration {
2630 type Output = SignedDuration;
2631
2632 #[inline]
2633 fn sub(self, rhs: SignedDuration) -> SignedDuration {
2634 self.checked_sub(rhs)
2635 .expect("overflow when subtracting signed durations")
2636 }
2637}
2638
2639impl core::ops::SubAssign for SignedDuration {
2640 #[inline]
2641 fn sub_assign(&mut self, rhs: SignedDuration) {
2642 *self = *self - rhs;
2643 }
2644}
2645
2646impl core::ops::Mul<i32> for SignedDuration {
2647 type Output = SignedDuration;
2648
2649 #[inline]
2650 fn mul(self, rhs: i32) -> SignedDuration {
2651 self.checked_mul(rhs)
2652 .expect("overflow when multiplying signed duration by scalar")
2653 }
2654}
2655
2656impl core::iter::Sum for SignedDuration {
2657 fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
2658 iter.fold(Self::new(0, 0), |acc, d| acc + d)
2659 }
2660}
2661
2662impl<'a> core::iter::Sum<&'a Self> for SignedDuration {
2663 fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
2664 iter.fold(Self::new(0, 0), |acc, d| acc + *d)
2665 }
2666}
2667
2668impl core::ops::Mul<SignedDuration> for i32 {
2669 type Output = SignedDuration;
2670
2671 #[inline]
2672 fn mul(self, rhs: SignedDuration) -> SignedDuration {
2673 rhs * self
2674 }
2675}
2676
2677impl core::ops::MulAssign<i32> for SignedDuration {
2678 #[inline]
2679 fn mul_assign(&mut self, rhs: i32) {
2680 *self = *self * rhs;
2681 }
2682}
2683
2684impl core::ops::Div<i32> for SignedDuration {
2685 type Output = SignedDuration;
2686
2687 #[inline]
2688 fn div(self, rhs: i32) -> SignedDuration {
2689 self.checked_div(rhs)
2690 .expect("overflow when dividing signed duration by scalar")
2691 }
2692}
2693
2694impl core::ops::DivAssign<i32> for SignedDuration {
2695 #[inline]
2696 fn div_assign(&mut self, rhs: i32) {
2697 *self = *self / rhs;
2698 }
2699}
2700
2701#[cfg(feature = "defmt")]
2702impl defmt::Format for SignedDuration {
2703 fn format(&self, f: defmt::Formatter) {
2704 use crate::fmt::DefmtWrite;
2705
2706 defmt::unwrap!(
2707 friendly::DEFAULT_SPAN_PRINTER.print_duration(self, DefmtWrite(f))
2708 );
2709 }
2710}
2711
2712#[cfg(feature = "serde")]
2713impl serde_core::Serialize for SignedDuration {
2714 #[inline]
2715 fn serialize<S: serde_core::Serializer>(
2716 &self,
2717 serializer: S,
2718 ) -> Result<S::Ok, S::Error> {
2719 serializer.collect_str(self)
2720 }
2721}
2722
2723#[cfg(feature = "serde")]
2724impl<'de> serde_core::Deserialize<'de> for SignedDuration {
2725 #[inline]
2726 fn deserialize<D: serde_core::Deserializer<'de>>(
2727 deserializer: D,
2728 ) -> Result<SignedDuration, D::Error> {
2729 use serde_core::de;
2730
2731 struct SignedDurationVisitor;
2732
2733 impl<'de> de::Visitor<'de> for SignedDurationVisitor {
2734 type Value = SignedDuration;
2735
2736 fn expecting(
2737 &self,
2738 f: &mut core::fmt::Formatter,
2739 ) -> core::fmt::Result {
2740 f.write_str("a signed duration string")
2741 }
2742
2743 #[inline]
2744 fn visit_bytes<E: de::Error>(
2745 self,
2746 value: &[u8],
2747 ) -> Result<SignedDuration, E> {
2748 parse_iso_or_friendly(value).map_err(de::Error::custom)
2749 }
2750
2751 #[inline]
2752 fn visit_str<E: de::Error>(
2753 self,
2754 value: &str,
2755 ) -> Result<SignedDuration, E> {
2756 self.visit_bytes(value.as_bytes())
2757 }
2758 }
2759
2760 deserializer.deserialize_str(SignedDurationVisitor)
2761 }
2762}
2763
2764/// Options for [`SignedDuration::round`].
2765///
2766/// This type provides a way to configure the rounding of a duration. This
2767/// includes setting the smallest unit (i.e., the unit to round), the rounding
2768/// increment and the rounding mode (e.g., "ceil" or "truncate").
2769///
2770/// `SignedDuration::round` accepts anything that implements
2771/// `Into<SignedDurationRound>`. There are a few key trait implementations that
2772/// make this convenient:
2773///
2774/// * `From<Unit> for SignedDurationRound` will construct a rounding
2775/// configuration where the smallest unit is set to the one given.
2776/// * `From<(Unit, i64)> for SignedDurationRound` will construct a rounding
2777/// configuration where the smallest unit and the rounding increment are set to
2778/// the ones given.
2779///
2780/// In order to set other options (like the rounding mode), one must explicitly
2781/// create a `SignedDurationRound` and pass it to `SignedDuration::round`.
2782///
2783/// # Example
2784///
2785/// This example shows how to always round up to the nearest half-minute:
2786///
2787/// ```
2788/// use jiff::{RoundMode, SignedDuration, SignedDurationRound, Unit};
2789///
2790/// let dur = SignedDuration::new(4 * 60 * 60 + 17 * 60 + 1, 123_456_789);
2791/// let rounded = dur.round(
2792/// SignedDurationRound::new()
2793/// .smallest(Unit::Second)
2794/// .increment(30)
2795/// .mode(RoundMode::Expand),
2796/// )?;
2797/// assert_eq!(rounded, SignedDuration::from_secs(4 * 60 * 60 + 17 * 60 + 30));
2798///
2799/// # Ok::<(), Box<dyn std::error::Error>>(())
2800/// ```
2801#[derive(Clone, Copy, Debug)]
2802pub struct SignedDurationRound {
2803 smallest: Unit,
2804 mode: RoundMode,
2805 increment: i64,
2806}
2807
2808impl SignedDurationRound {
2809 /// Create a new default configuration for rounding a signed duration via
2810 /// [`SignedDuration::round`].
2811 ///
2812 /// The default configuration does no rounding.
2813 #[inline]
2814 pub fn new() -> SignedDurationRound {
2815 SignedDurationRound {
2816 smallest: Unit::Nanosecond,
2817 mode: RoundMode::HalfExpand,
2818 increment: 1,
2819 }
2820 }
2821
2822 /// Set the smallest units allowed in the duration returned. These are the
2823 /// units that the duration is rounded to.
2824 ///
2825 /// # Errors
2826 ///
2827 /// The unit must be [`Unit::Hour`] or smaller.
2828 ///
2829 /// # Example
2830 ///
2831 /// A basic example that rounds to the nearest minute:
2832 ///
2833 /// ```
2834 /// use jiff::{SignedDuration, Unit};
2835 ///
2836 /// let duration = SignedDuration::new(15 * 60 + 46, 0);
2837 /// assert_eq!(duration.round(Unit::Minute)?, SignedDuration::from_mins(16));
2838 ///
2839 /// # Ok::<(), Box<dyn std::error::Error>>(())
2840 /// ```
2841 #[inline]
2842 pub fn smallest(self, unit: Unit) -> SignedDurationRound {
2843 SignedDurationRound { smallest: unit, ..self }
2844 }
2845
2846 /// Set the rounding mode.
2847 ///
2848 /// This defaults to [`RoundMode::HalfExpand`], which makes rounding work
2849 /// like how you were taught in school.
2850 ///
2851 /// # Example
2852 ///
2853 /// A basic example that rounds to the nearest minute, but changing its
2854 /// rounding mode to truncation:
2855 ///
2856 /// ```
2857 /// use jiff::{RoundMode, SignedDuration, SignedDurationRound, Unit};
2858 ///
2859 /// let duration = SignedDuration::new(15 * 60 + 46, 0);
2860 /// assert_eq!(
2861 /// duration.round(SignedDurationRound::new()
2862 /// .smallest(Unit::Minute)
2863 /// .mode(RoundMode::Trunc),
2864 /// )?,
2865 /// // The default round mode does rounding like
2866 /// // how you probably learned in school, and would
2867 /// // result in rounding up to 16 minutes. But we
2868 /// // change it to truncation here, which makes it
2869 /// // round down.
2870 /// SignedDuration::from_mins(15),
2871 /// );
2872 ///
2873 /// # Ok::<(), Box<dyn std::error::Error>>(())
2874 /// ```
2875 #[inline]
2876 pub fn mode(self, mode: RoundMode) -> SignedDurationRound {
2877 SignedDurationRound { mode, ..self }
2878 }
2879
2880 /// Set the rounding increment for the smallest unit.
2881 ///
2882 /// The default value is `1`. Other values permit rounding the smallest
2883 /// unit to the nearest integer increment specified. For example, if the
2884 /// smallest unit is set to [`Unit::Minute`], then a rounding increment of
2885 /// `30` would result in rounding in increments of a half hour. That is,
2886 /// the only minute value that could result would be `0` or `30`.
2887 ///
2888 /// # Errors
2889 ///
2890 /// Unlike rounding a [`Span`](crate::Span), the increment does not need
2891 /// to divide evenly into the next largest unit. Callers can round a
2892 /// signed duration to any increment value so long as it is greater than
2893 /// zero and less than or equal to `1_000_000_000`.
2894 ///
2895 /// # Example
2896 ///
2897 /// This shows how to round a duration to the nearest 5 minute increment:
2898 ///
2899 /// ```
2900 /// use jiff::{SignedDuration, Unit};
2901 ///
2902 /// let duration = SignedDuration::new(4 * 60 * 60 + 2 * 60 + 30, 0);
2903 /// assert_eq!(
2904 /// duration.round((Unit::Minute, 5))?,
2905 /// SignedDuration::new(4 * 60 * 60 + 5 * 60, 0),
2906 /// );
2907 ///
2908 /// # Ok::<(), Box<dyn std::error::Error>>(())
2909 /// ```
2910 #[inline]
2911 pub fn increment(self, increment: i64) -> SignedDurationRound {
2912 SignedDurationRound { increment, ..self }
2913 }
2914
2915 /// Does the actual duration rounding.
2916 fn round(&self, dur: SignedDuration) -> Result<SignedDuration, Error> {
2917 let increment =
2918 Increment::for_signed_duration(self.smallest, self.increment)?;
2919 increment
2920 .round(self.mode, dur)
2921 .with_context(|| E::RoundOverflowed { unit: self.smallest })
2922 }
2923}
2924
2925impl Default for SignedDurationRound {
2926 fn default() -> SignedDurationRound {
2927 SignedDurationRound::new()
2928 }
2929}
2930
2931impl From<Unit> for SignedDurationRound {
2932 fn from(unit: Unit) -> SignedDurationRound {
2933 SignedDurationRound::default().smallest(unit)
2934 }
2935}
2936
2937impl From<(Unit, i64)> for SignedDurationRound {
2938 fn from((unit, increment): (Unit, i64)) -> SignedDurationRound {
2939 SignedDurationRound::default().smallest(unit).increment(increment)
2940 }
2941}
2942
2943/// A common parsing function that works in bytes.
2944///
2945/// Specifically, this parses either an ISO 8601 duration into a
2946/// `SignedDuration` or a "friendly" duration into a `SignedDuration`. It also
2947/// tries to give decent error messages.
2948///
2949/// This works because the friendly and ISO 8601 formats have non-overlapping
2950/// prefixes. Both can start with a `+` or `-`, but aside from that, an ISO
2951/// 8601 duration _always_ has to start with a `P` or `p`. We can utilize this
2952/// property to very quickly determine how to parse the input. We just need to
2953/// handle the possibly ambiguous case with a leading sign a little carefully
2954/// in order to ensure good error messages.
2955///
2956/// (We do the same thing for `Span`.)
2957#[cfg_attr(feature = "perf-inline", inline(always))]
2958fn parse_iso_or_friendly(bytes: &[u8]) -> Result<SignedDuration, Error> {
2959 let Some((&byte, tail)) = bytes.split_first() else {
2960 return Err(crate::Error::from(
2961 crate::error::fmt::Error::HybridDurationEmpty,
2962 ));
2963 };
2964 let mut first = byte;
2965 // N.B. Unsigned durations don't support negative durations (of
2966 // course), but we still check for it here so that we can defer to
2967 // the dedicated parsers. They will provide their own error messages.
2968 if first == b'+' || first == b'-' {
2969 let Some(&byte) = tail.first() else {
2970 return Err(crate::Error::from(
2971 crate::error::fmt::Error::HybridDurationPrefix { sign: first },
2972 ));
2973 };
2974 first = byte;
2975 }
2976 if first == b'P' || first == b'p' {
2977 temporal::DEFAULT_SPAN_PARSER.parse_duration(bytes)
2978 } else {
2979 friendly::DEFAULT_SPAN_PARSER.parse_duration(bytes)
2980 }
2981}
2982
2983#[cfg(feature = "arbitrary")]
2984impl<'a> arbitrary::Arbitrary<'a> for SignedDuration {
2985 fn arbitrary(
2986 u: &mut arbitrary::Unstructured<'a>,
2987 ) -> arbitrary::Result<SignedDuration> {
2988 let secs = i64::arbitrary(u)?;
2989 let nanos =
2990 u.int_in_range(-(NANOS_PER_SEC - 1)..=(NANOS_PER_SEC - 1))?;
2991 Ok(SignedDuration::new(secs, nanos))
2992 }
2993
2994 fn size_hint(depth: usize) -> (usize, Option<usize>) {
2995 arbitrary::size_hint::and(
2996 <i64 as arbitrary::Arbitrary>::size_hint(depth),
2997 <i32 as arbitrary::Arbitrary>::size_hint(depth),
2998 )
2999 }
3000}
3001
3002#[cfg(test)]
3003mod tests {
3004 use std::io::Cursor;
3005
3006 use alloc::string::ToString;
3007
3008 use super::*;
3009
3010 #[test]
3011 fn new() {
3012 let d = SignedDuration::new(12, i32::MAX);
3013 assert_eq!(d.as_secs(), 14);
3014 assert_eq!(d.subsec_nanos(), 147_483_647);
3015
3016 let d = SignedDuration::new(-12, i32::MIN);
3017 assert_eq!(d.as_secs(), -14);
3018 assert_eq!(d.subsec_nanos(), -147_483_648);
3019
3020 let d = SignedDuration::new(i64::MAX, i32::MIN);
3021 assert_eq!(d.as_secs(), i64::MAX - 3);
3022 assert_eq!(d.subsec_nanos(), 852_516_352);
3023
3024 let d = SignedDuration::new(i64::MIN, i32::MAX);
3025 assert_eq!(d.as_secs(), i64::MIN + 3);
3026 assert_eq!(d.subsec_nanos(), -852_516_353);
3027 }
3028
3029 #[test]
3030 #[should_panic]
3031 fn new_fail_positive() {
3032 SignedDuration::new(i64::MAX, 1_000_000_000);
3033 }
3034
3035 #[test]
3036 #[should_panic]
3037 fn new_fail_negative() {
3038 SignedDuration::new(i64::MIN, -1_000_000_000);
3039 }
3040
3041 #[test]
3042 fn from_hours_limits() {
3043 let d = SignedDuration::from_hours(2_562_047_788_015_215);
3044 assert_eq!(d.as_secs(), 9223372036854774000);
3045
3046 let d = SignedDuration::from_hours(-2_562_047_788_015_215);
3047 assert_eq!(d.as_secs(), -9223372036854774000);
3048 }
3049
3050 #[test]
3051 #[should_panic]
3052 fn from_hours_fail_positive() {
3053 SignedDuration::from_hours(2_562_047_788_015_216);
3054 }
3055
3056 #[test]
3057 #[should_panic]
3058 fn from_hours_fail_negative() {
3059 SignedDuration::from_hours(-2_562_047_788_015_216);
3060 }
3061
3062 #[test]
3063 fn from_minutes_limits() {
3064 let d = SignedDuration::from_mins(153_722_867_280_912_930);
3065 assert_eq!(d.as_secs(), 9223372036854775800);
3066
3067 let d = SignedDuration::from_mins(-153_722_867_280_912_930);
3068 assert_eq!(d.as_secs(), -9223372036854775800);
3069 }
3070
3071 #[test]
3072 #[should_panic]
3073 fn from_minutes_fail_positive() {
3074 SignedDuration::from_mins(153_722_867_280_912_931);
3075 }
3076
3077 #[test]
3078 #[should_panic]
3079 fn from_minutes_fail_negative() {
3080 SignedDuration::from_mins(-153_722_867_280_912_931);
3081 }
3082
3083 #[test]
3084 fn add() {
3085 let add = |(secs1, nanos1): (i64, i32),
3086 (secs2, nanos2): (i64, i32)|
3087 -> (i64, i32) {
3088 let d1 = SignedDuration::new(secs1, nanos1);
3089 let d2 = SignedDuration::new(secs2, nanos2);
3090 let sum = d1.checked_add(d2).unwrap();
3091 (sum.as_secs(), sum.subsec_nanos())
3092 };
3093
3094 assert_eq!(add((1, 1), (1, 1)), (2, 2));
3095 assert_eq!(add((1, 1), (-1, -1)), (0, 0));
3096 assert_eq!(add((-1, -1), (1, 1)), (0, 0));
3097 assert_eq!(add((-1, -1), (-1, -1)), (-2, -2));
3098
3099 assert_eq!(add((1, 500_000_000), (1, 500_000_000)), (3, 0));
3100 assert_eq!(add((-1, -500_000_000), (-1, -500_000_000)), (-3, 0));
3101 assert_eq!(
3102 add((5, 200_000_000), (-1, -500_000_000)),
3103 (3, 700_000_000)
3104 );
3105 assert_eq!(
3106 add((-5, -200_000_000), (1, 500_000_000)),
3107 (-3, -700_000_000)
3108 );
3109 }
3110
3111 #[test]
3112 fn add_overflow() {
3113 let add = |(secs1, nanos1): (i64, i32),
3114 (secs2, nanos2): (i64, i32)|
3115 -> Option<(i64, i32)> {
3116 let d1 = SignedDuration::new(secs1, nanos1);
3117 let d2 = SignedDuration::new(secs2, nanos2);
3118 d1.checked_add(d2).map(|d| (d.as_secs(), d.subsec_nanos()))
3119 };
3120 assert_eq!(None, add((i64::MAX, 0), (1, 0)));
3121 assert_eq!(None, add((i64::MIN, 0), (-1, 0)));
3122 assert_eq!(None, add((i64::MAX, 1), (0, 999_999_999)));
3123 assert_eq!(None, add((i64::MIN, -1), (0, -999_999_999)));
3124 }
3125
3126 /// # `serde` deserializer compatibility test
3127 ///
3128 /// Serde YAML used to be unable to deserialize `jiff` types,
3129 /// as deserializing from bytes is not supported by the deserializer.
3130 ///
3131 /// - <https://github.com/BurntSushi/jiff/issues/138>
3132 /// - <https://github.com/BurntSushi/jiff/discussions/148>
3133 #[test]
3134 fn signed_duration_deserialize_yaml() {
3135 let expected = SignedDuration::from_secs(123456789);
3136
3137 let deserialized: SignedDuration =
3138 serde_yaml::from_str("PT34293h33m9s").unwrap();
3139
3140 assert_eq!(deserialized, expected);
3141
3142 let deserialized: SignedDuration =
3143 serde_yaml::from_slice("PT34293h33m9s".as_bytes()).unwrap();
3144
3145 assert_eq!(deserialized, expected);
3146
3147 let cursor = Cursor::new(b"PT34293h33m9s");
3148 let deserialized: SignedDuration =
3149 serde_yaml::from_reader(cursor).unwrap();
3150
3151 assert_eq!(deserialized, expected);
3152 }
3153
3154 #[test]
3155 fn from_str() {
3156 let p = |s: &str| -> Result<SignedDuration, Error> { s.parse() };
3157
3158 insta::assert_snapshot!(
3159 p("1 hour").unwrap(),
3160 @"PT1H",
3161 );
3162 insta::assert_snapshot!(
3163 p("+1 hour").unwrap(),
3164 @"PT1H",
3165 );
3166 insta::assert_snapshot!(
3167 p("-1 hour").unwrap(),
3168 @"-PT1H",
3169 );
3170 insta::assert_snapshot!(
3171 p("PT1h").unwrap(),
3172 @"PT1H",
3173 );
3174 insta::assert_snapshot!(
3175 p("+PT1h").unwrap(),
3176 @"PT1H",
3177 );
3178 insta::assert_snapshot!(
3179 p("-PT1h").unwrap(),
3180 @"-PT1H",
3181 );
3182
3183 insta::assert_snapshot!(
3184 p("").unwrap_err(),
3185 @r#"an empty string is not a valid duration in either the ISO 8601 format or Jiff's "friendly" format"#,
3186 );
3187 insta::assert_snapshot!(
3188 p("+").unwrap_err(),
3189 @r#"found nothing after sign `+`, which is not a valid duration in either the ISO 8601 format or Jiff's "friendly" format"#,
3190 );
3191 insta::assert_snapshot!(
3192 p("-").unwrap_err(),
3193 @r#"found nothing after sign `-`, which is not a valid duration in either the ISO 8601 format or Jiff's "friendly" format"#,
3194 );
3195 }
3196
3197 #[test]
3198 fn serde_deserialize() {
3199 let p = |s: &str| -> Result<SignedDuration, serde_json::Error> {
3200 serde_json::from_str(&alloc::format!("\"{s}\""))
3201 };
3202
3203 insta::assert_snapshot!(
3204 p("1 hour").unwrap(),
3205 @"PT1H",
3206 );
3207 insta::assert_snapshot!(
3208 p("+1 hour").unwrap(),
3209 @"PT1H",
3210 );
3211 insta::assert_snapshot!(
3212 p("-1 hour").unwrap(),
3213 @"-PT1H",
3214 );
3215 insta::assert_snapshot!(
3216 p("PT1h").unwrap(),
3217 @"PT1H",
3218 );
3219 insta::assert_snapshot!(
3220 p("+PT1h").unwrap(),
3221 @"PT1H",
3222 );
3223 insta::assert_snapshot!(
3224 p("-PT1h").unwrap(),
3225 @"-PT1H",
3226 );
3227
3228 insta::assert_snapshot!(
3229 p("").unwrap_err(),
3230 @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"#,
3231 );
3232 insta::assert_snapshot!(
3233 p("+").unwrap_err(),
3234 @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"#,
3235 );
3236 insta::assert_snapshot!(
3237 p("-").unwrap_err(),
3238 @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"#,
3239 );
3240 }
3241
3242 /// This test ensures that we can parse `humantime` formatted durations.
3243 #[test]
3244 fn humantime_compatibility_parse() {
3245 let dur = std::time::Duration::new(26_784, 123_456_789);
3246 let formatted = humantime::format_duration(dur).to_string();
3247 assert_eq!(formatted, "7h 26m 24s 123ms 456us 789ns");
3248
3249 let expected = SignedDuration::try_from(dur).unwrap();
3250 assert_eq!(formatted.parse::<SignedDuration>().unwrap(), expected);
3251 }
3252
3253 /// This test ensures that we can print a `SignedDuration` that `humantime`
3254 /// can parse.
3255 ///
3256 /// Note that this isn't the default since `humantime`'s parser is
3257 /// pretty limited. e.g., It doesn't support things like `nsecs`
3258 /// despite supporting `secs`. And other reasons. See the docs on
3259 /// `Designator::HumanTime` for why we sadly provide a custom variant for
3260 /// it.
3261 #[test]
3262 fn humantime_compatibility_print() {
3263 static PRINTER: friendly::SpanPrinter = friendly::SpanPrinter::new()
3264 .designator(friendly::Designator::HumanTime);
3265
3266 let sdur = SignedDuration::new(26_784, 123_456_789);
3267 let formatted = PRINTER.duration_to_string(&sdur);
3268 assert_eq!(formatted, "7h 26m 24s 123ms 456us 789ns");
3269
3270 let dur = humantime::parse_duration(&formatted).unwrap();
3271 let expected = std::time::Duration::try_from(sdur).unwrap();
3272 assert_eq!(dur, expected);
3273 }
3274
3275 #[test]
3276 fn using_sum() {
3277 let signed_durations = [
3278 SignedDuration::new(12, 600_000_000),
3279 SignedDuration::new(13, 400_000_000),
3280 ];
3281 let sum1: SignedDuration = signed_durations.iter().sum();
3282 let sum2: SignedDuration = signed_durations.into_iter().sum();
3283
3284 assert_eq!(sum1, SignedDuration::new(26, 0));
3285 assert_eq!(sum2, SignedDuration::new(26, 0));
3286 }
3287
3288 #[test]
3289 #[should_panic]
3290 fn using_sum_when_max_exceeds() {
3291 [
3292 SignedDuration::new(i64::MAX, 0),
3293 SignedDuration::new(0, 1_000_000_000),
3294 ]
3295 .iter()
3296 .sum::<SignedDuration>();
3297 }
3298
3299 /// Regression test for a case where this routine could panic, even though
3300 /// it is fallible and should never panic.
3301 ///
3302 /// This occurred when rounding the fractional part of f64 could result in
3303 /// a number of nanoseconds equivalent to 1 second. This was then fed to
3304 /// a `SignedDuration` constructor that expected no nanosecond overflow.
3305 /// And this triggered a panic in debug mode (and an incorrect result in
3306 /// release mode).
3307 ///
3308 /// See: https://github.com/BurntSushi/jiff/issues/324
3309 #[test]
3310 fn panic_try_from_secs_f64() {
3311 let sdur = SignedDuration::try_from_secs_f64(0.999999999999).unwrap();
3312 assert_eq!(sdur, SignedDuration::from_secs(1));
3313
3314 let sdur = SignedDuration::try_from_secs_f64(-0.999999999999).unwrap();
3315 assert_eq!(sdur, SignedDuration::from_secs(-1));
3316
3317 let max = 9223372036854775807.999999999f64;
3318 let sdur = SignedDuration::try_from_secs_f64(max).unwrap();
3319 assert_eq!(sdur, SignedDuration::new(9223372036854775807, 0));
3320
3321 let min = -9223372036854775808.999999999f64;
3322 let sdur = SignedDuration::try_from_secs_f64(min).unwrap();
3323 assert_eq!(sdur, SignedDuration::new(-9223372036854775808, 0));
3324 }
3325
3326 /// See `panic_try_from_secs_f64`.
3327 ///
3328 /// Although note that I could never get this to panic. Perhaps the
3329 /// particulars of f32 prevent the fractional part from rounding up to
3330 /// 1_000_000_000?
3331 #[test]
3332 fn panic_try_from_secs_f32() {
3333 let sdur = SignedDuration::try_from_secs_f32(0.999999999).unwrap();
3334 assert_eq!(sdur, SignedDuration::from_secs(1));
3335
3336 let sdur = SignedDuration::try_from_secs_f32(-0.999999999).unwrap();
3337 assert_eq!(sdur, SignedDuration::from_secs(-1));
3338
3339 // Indeed, this is why the above never panicked.
3340 let x: f32 = 1.0;
3341 let y: f32 = 0.999999999;
3342 assert_eq!(x, y);
3343 assert_eq!(y.fract(), 0.0f32);
3344 }
3345
3346 #[test]
3347 fn as_hours_with_remainder() {
3348 let sdur = SignedDuration::new(4 * 60 * 60 + 30 * 60, 123_000_000);
3349 let (hours, rem) = sdur.as_hours_with_remainder();
3350 assert_eq!(hours, 4);
3351 assert_eq!(rem, SignedDuration::new(30 * 60, 123_000_000));
3352
3353 let sdur = SignedDuration::new(-(4 * 60 * 60 + 30 * 60), -123_000_000);
3354 let (hours, rem) = sdur.as_hours_with_remainder();
3355 assert_eq!(hours, -4);
3356 assert_eq!(rem, SignedDuration::new(-30 * 60, -123_000_000));
3357 }
3358
3359 #[test]
3360 fn as_mins_with_remainder() {
3361 let sdur = SignedDuration::new(4 * 60 + 30, 123_000_000);
3362 let (mins, rem) = sdur.as_mins_with_remainder();
3363 assert_eq!(mins, 4);
3364 assert_eq!(rem, SignedDuration::new(30, 123_000_000));
3365
3366 let sdur = SignedDuration::new(-(4 * 60 + 30), -123_000_000);
3367 let (mins, rem) = sdur.as_mins_with_remainder();
3368 assert_eq!(mins, -4);
3369 assert_eq!(rem, SignedDuration::new(-30, -123_000_000));
3370 }
3371
3372 #[test]
3373 fn as_secs_with_remainder() {
3374 let sdur = SignedDuration::new(4, 123_456_789);
3375 let (secs, rem) = sdur.as_secs_with_remainder();
3376 assert_eq!(secs, 4);
3377 assert_eq!(rem, SignedDuration::new(0, 123_456_789));
3378
3379 let sdur = SignedDuration::new(-4, -123_456_789);
3380 let (secs, rem) = sdur.as_secs_with_remainder();
3381 assert_eq!(secs, -4);
3382 assert_eq!(rem, SignedDuration::new(0, -123_456_789));
3383 }
3384
3385 #[test]
3386 fn as_millis_with_remainder() {
3387 let sdur = SignedDuration::new(4, 123_456_789);
3388 let (millis, rem) = sdur.as_millis_with_remainder();
3389 assert_eq!(millis, 4_123);
3390 assert_eq!(rem, SignedDuration::new(0, 000_456_789));
3391
3392 let sdur = SignedDuration::new(-4, -123_456_789);
3393 let (millis, rem) = sdur.as_millis_with_remainder();
3394 assert_eq!(millis, -4_123);
3395 assert_eq!(rem, SignedDuration::new(0, -000_456_789));
3396 }
3397
3398 #[test]
3399 fn as_micros_with_remainder() {
3400 let sdur = SignedDuration::new(4, 123_456_789);
3401 let (micros, rem) = sdur.as_micros_with_remainder();
3402 assert_eq!(micros, 4_123_456);
3403 assert_eq!(rem, SignedDuration::new(0, 000_000_789));
3404
3405 let sdur = SignedDuration::new(-4, -123_456_789);
3406 let (micros, rem) = sdur.as_micros_with_remainder();
3407 assert_eq!(micros, -4_123_456);
3408 assert_eq!(rem, SignedDuration::new(0, -000_000_789));
3409 }
3410}