jiff/civil/time.rs
1use core::time::Duration as UnsignedDuration;
2
3use jcore::{
4 civil::{
5 Time as JTime, TimeNanosecond as JTimeNanosecond,
6 TimeSecond as JTimeSecond,
7 },
8 constants as c,
9};
10
11use crate::{
12 RoundMode, SignedDuration, Span, SpanRound, Unit, ZonedDateTime,
13 civil::{Date, DateTime},
14 duration::{Duration, SDuration},
15 error::{Error, civil::Error as E, unit::UnitConfigError},
16 fmt::{
17 self,
18 temporal::{self, DEFAULT_DATETIME_PARSER},
19 },
20 util::{b, constant, round::Increment},
21};
22
23/// A representation of civil "wall clock" time.
24///
25/// Conceptually, a `Time` value corresponds to the typical hours and minutes
26/// that you might see on a clock. This type also contains the second and
27/// fractional subsecond (to nanosecond precision) associated with a time.
28///
29/// # Civil time
30///
31/// A `Time` value behaves as if it corresponds precisely to a single
32/// nanosecond within a day, where all days have `86,400` seconds. That is,
33/// any given `Time` value corresponds to a nanosecond in the inclusive range
34/// `[0, 86399999999999]`, where `0` corresponds to `00:00:00.000000000`
35/// ([`Time::MIN`]) and `86399999999999` corresponds to `23:59:59.999999999`
36/// ([`Time::MAX`]). Moreover, in civil time, all hours have the same number of
37/// minutes, all minutes have the same number of seconds and all seconds have
38/// the same number of nanoseconds.
39///
40/// # Parsing and printing
41///
42/// The `Time` type provides convenient trait implementations of
43/// [`std::str::FromStr`] and [`std::fmt::Display`]:
44///
45/// ```
46/// use jiff::civil::Time;
47///
48/// let t: Time = "15:22:45".parse()?;
49/// assert_eq!(t.to_string(), "15:22:45");
50///
51/// # Ok::<(), Box<dyn std::error::Error>>(())
52/// ```
53///
54/// A civil `Time` can also be parsed from something that _contains_ a
55/// time, but with perhaps other data (such as an offset or time zone):
56///
57/// ```
58/// use jiff::civil::Time;
59///
60/// let t: Time = "2024-06-19T15:22:45-04[America/New_York]".parse()?;
61/// assert_eq!(t.to_string(), "15:22:45");
62///
63/// # Ok::<(), Box<dyn std::error::Error>>(())
64/// ```
65///
66/// For more information on the specific format supported, see the
67/// [`fmt::temporal`](crate::fmt::temporal) module documentation.
68///
69/// # Default value
70///
71/// For convenience, this type implements the `Default` trait. Its default
72/// value is midnight. i.e., `00:00:00.000000000`.
73///
74/// # Leap seconds
75///
76/// Jiff does not support leap seconds. Jiff behaves as if they don't exist.
77/// The only exception is that if one parses a time with a second component
78/// of `60`, then it is automatically constrained to `59`:
79///
80/// ```
81/// use jiff::civil::{Time, time};
82///
83/// let t: Time = "23:59:60".parse()?;
84/// assert_eq!(t, time(23, 59, 59, 0));
85///
86/// # Ok::<(), Box<dyn std::error::Error>>(())
87/// ```
88///
89/// # Comparisons
90///
91/// The `Time` type provides both `Eq` and `Ord` trait implementations to
92/// facilitate easy comparisons. When a time `t1` occurs before a time `t2`,
93/// then `t1 < t2`. For example:
94///
95/// ```
96/// use jiff::civil::time;
97///
98/// let t1 = time(7, 30, 1, 0);
99/// let t2 = time(8, 10, 0, 0);
100/// assert!(t1 < t2);
101/// ```
102///
103/// As mentioned above, `Time` values are not associated with timezones, and
104/// thus transitions such as DST are not taken into account when comparing
105/// `Time` values.
106///
107/// # Arithmetic
108///
109/// This type provides routines for adding and subtracting spans of time, as
110/// well as computing the span of time between two `Time` values.
111///
112/// For adding or subtracting spans of time, one can use any of the following
113/// routines:
114///
115/// * [`Time::wrapping_add`] or [`Time::wrapping_sub`] for wrapping arithmetic.
116/// * [`Time::checked_add`] or [`Time::checked_sub`] for checked arithmetic.
117/// * [`Time::saturating_add`] or [`Time::saturating_sub`] for saturating
118/// arithmetic.
119///
120/// Additionally, wrapping arithmetic is available via the `Add` and `Sub`
121/// trait implementations:
122///
123/// ```
124/// use jiff::{civil::time, ToSpan};
125///
126/// let t = time(20, 10, 1, 0);
127/// let span = 1.hours().minutes(49).seconds(59);
128/// assert_eq!(t + span, time(22, 0, 0, 0));
129///
130/// // Overflow will result in wrap-around unless using checked
131/// // arithmetic explicitly.
132/// let t = time(23, 59, 59, 999_999_999);
133/// assert_eq!(time(0, 0, 0, 0), t + 1.nanoseconds());
134/// ```
135///
136/// Wrapping arithmetic is used by default because it corresponds to how clocks
137/// showing the time of day behave in practice.
138///
139/// One can compute the span of time between two times using either
140/// [`Time::until`] or [`Time::since`]. It's also possible to subtract two
141/// `Time` values directly via a `Sub` trait implementation:
142///
143/// ```
144/// use jiff::{civil::time, ToSpan};
145///
146/// let time1 = time(22, 0, 0, 0);
147/// let time2 = time(20, 10, 1, 0);
148/// assert_eq!(
149/// time1 - time2,
150/// 1.hours().minutes(49).seconds(59).fieldwise(),
151/// );
152/// ```
153///
154/// The `until` and `since` APIs are polymorphic and allow re-balancing and
155/// rounding the span returned. For example, the default largest unit is hours
156/// (as exemplified above), but we can ask for smaller units:
157///
158/// ```
159/// use jiff::{civil::time, ToSpan, Unit};
160///
161/// let time1 = time(23, 30, 0, 0);
162/// let time2 = time(7, 0, 0, 0);
163/// assert_eq!(
164/// time1.since((Unit::Minute, time2))?,
165/// 990.minutes().fieldwise(),
166/// );
167///
168/// # Ok::<(), Box<dyn std::error::Error>>(())
169/// ```
170///
171/// Or even round the span returned:
172///
173/// ```
174/// use jiff::{civil::{TimeDifference, time}, RoundMode, ToSpan, Unit};
175///
176/// let time1 = time(23, 30, 0, 0);
177/// let time2 = time(23, 35, 59, 0);
178/// assert_eq!(
179/// time1.until(
180/// TimeDifference::new(time2).smallest(Unit::Minute),
181/// )?,
182/// 5.minutes().fieldwise(),
183/// );
184/// // `TimeDifference` uses truncation as a rounding mode by default,
185/// // but you can set the rounding mode to break ties away from zero:
186/// assert_eq!(
187/// time1.until(
188/// TimeDifference::new(time2)
189/// .smallest(Unit::Minute)
190/// .mode(RoundMode::HalfExpand),
191/// )?,
192/// // Rounds up to 6 minutes.
193/// 6.minutes().fieldwise(),
194/// );
195///
196/// # Ok::<(), Box<dyn std::error::Error>>(())
197/// ```
198///
199/// # Rounding
200///
201/// A `Time` can be rounded based on a [`TimeRound`] configuration of smallest
202/// units, rounding increment and rounding mode. Here's an example showing how
203/// to round to the nearest third hour:
204///
205/// ```
206/// use jiff::{civil::{TimeRound, time}, Unit};
207///
208/// let t = time(16, 27, 29, 999_999_999);
209/// assert_eq!(
210/// t.round(TimeRound::new().smallest(Unit::Hour).increment(3))?,
211/// time(15, 0, 0, 0),
212/// );
213/// // Or alternatively, make use of the `From<(Unit, i64)> for TimeRound`
214/// // trait implementation:
215/// assert_eq!(t.round((Unit::Hour, 3))?, time(15, 0, 0, 0));
216///
217/// # Ok::<(), Box<dyn std::error::Error>>(())
218/// ```
219///
220/// See [`Time::round`] for more details.
221#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
222#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
223pub struct Time {
224 inner: JTime,
225}
226
227impl Time {
228 /// The minimum representable time value.
229 ///
230 /// This corresponds to `00:00:00.000000000`.
231 pub const MIN: Time = Time::midnight();
232
233 /// The maximum representable time value.
234 ///
235 /// This corresponds to `23:59:59.999999999`.
236 pub const MAX: Time = Time::constant(23, 59, 59, 999_999_999);
237
238 /// Creates a new `Time` value from its component hour, minute, second and
239 /// fractional subsecond (up to nanosecond precision) values.
240 ///
241 /// To set the component values of a time after creating it, use
242 /// [`TimeWith`] via [`Time::with`] to build a new [`Time`] from the fields
243 /// of an existing time.
244 ///
245 /// # Errors
246 ///
247 /// This returns an error unless *all* of the following conditions are
248 /// true:
249 ///
250 /// * `0 <= hour <= 23`
251 /// * `0 <= minute <= 59`
252 /// * `0 <= second <= 59`
253 /// * `0 <= subsec_nanosecond <= 999,999,999`
254 ///
255 /// # Example
256 ///
257 /// This shows an example of a valid time:
258 ///
259 /// ```
260 /// use jiff::civil::Time;
261 ///
262 /// let t = Time::new(21, 30, 5, 123_456_789).unwrap();
263 /// assert_eq!(t.hour(), 21);
264 /// assert_eq!(t.minute(), 30);
265 /// assert_eq!(t.second(), 5);
266 /// assert_eq!(t.millisecond(), 123);
267 /// assert_eq!(t.microsecond(), 456);
268 /// assert_eq!(t.nanosecond(), 789);
269 /// ```
270 ///
271 /// This shows an example of an invalid time:
272 ///
273 /// ```
274 /// use jiff::civil::Time;
275 ///
276 /// assert!(Time::new(21, 30, 60, 0).is_err());
277 /// ```
278 #[inline]
279 pub fn new(
280 hour: i8,
281 minute: i8,
282 second: i8,
283 subsec_nanosecond: i32,
284 ) -> Result<Time, Error> {
285 JTime::new(hour, minute, second, subsec_nanosecond)
286 .map(Time::from_jcore)
287 .map_err(Error::jcore_range)
288 }
289
290 /// Creates a new `Time` value in a `const` context.
291 ///
292 /// # Panics
293 ///
294 /// This panics if the given values do not correspond to a valid `Time`.
295 /// All of the following conditions must be true:
296 ///
297 /// * `0 <= hour <= 23`
298 /// * `0 <= minute <= 59`
299 /// * `0 <= second <= 59`
300 /// * `0 <= subsec_nanosecond <= 999,999,999`
301 ///
302 /// Similarly, when used in a const context, invalid parameters will
303 /// prevent your Rust program from compiling.
304 ///
305 /// # Example
306 ///
307 /// This shows an example of a valid time in a `const` context:
308 ///
309 /// ```
310 /// use jiff::civil::Time;
311 ///
312 /// const BEDTIME: Time = Time::constant(21, 30, 5, 123_456_789);
313 /// assert_eq!(BEDTIME.hour(), 21);
314 /// assert_eq!(BEDTIME.minute(), 30);
315 /// assert_eq!(BEDTIME.second(), 5);
316 /// assert_eq!(BEDTIME.millisecond(), 123);
317 /// assert_eq!(BEDTIME.microsecond(), 456);
318 /// assert_eq!(BEDTIME.nanosecond(), 789);
319 /// assert_eq!(BEDTIME.subsec_nanosecond(), 123_456_789);
320 /// ```
321 #[inline]
322 pub const fn constant(
323 hour: i8,
324 minute: i8,
325 second: i8,
326 subsec_nanosecond: i32,
327 ) -> Time {
328 Time::from_jcore(constant::unwrapr!(
329 JTime::new(hour, minute, second, subsec_nanosecond),
330 "invalid time"
331 ))
332 }
333
334 /// Returns the first moment of time in a day.
335 ///
336 /// Specifically, this has the `hour`, `minute`, `second`, `millisecond`,
337 /// `microsecond` and `nanosecond` fields all set to `0`.
338 ///
339 /// # Example
340 ///
341 /// ```
342 /// use jiff::civil::Time;
343 ///
344 /// let t = Time::midnight();
345 /// assert_eq!(t.hour(), 0);
346 /// assert_eq!(t.minute(), 0);
347 /// assert_eq!(t.second(), 0);
348 /// assert_eq!(t.millisecond(), 0);
349 /// assert_eq!(t.microsecond(), 0);
350 /// assert_eq!(t.nanosecond(), 0);
351 /// ```
352 #[inline]
353 pub const fn midnight() -> Time {
354 Time::constant(0, 0, 0, 0)
355 }
356
357 /// Create a builder for constructing a `Time` from the fields of this
358 /// time.
359 ///
360 /// See the methods on [`TimeWith`] for the different ways one can set the
361 /// fields of a new `Time`.
362 ///
363 /// # Example
364 ///
365 /// Unlike [`Date`], a [`Time`] is valid for all possible valid values
366 /// of its fields. That is, there is no way for two valid field values
367 /// to combine into an invalid `Time`. So, for `Time`, this builder does
368 /// have as much of a benefit versus an API design with methods like
369 /// `Time::with_hour` and `Time::with_minute`. Nevertheless, this builder
370 /// permits settings multiple fields at the same time and performing only
371 /// one validity check. Moreover, this provides a consistent API with other
372 /// date and time types in this crate.
373 ///
374 /// ```
375 /// use jiff::civil::time;
376 ///
377 /// let t1 = time(0, 0, 24, 0);
378 /// let t2 = t1.with().hour(15).minute(30).millisecond(10).build()?;
379 /// assert_eq!(t2, time(15, 30, 24, 10_000_000));
380 ///
381 /// # Ok::<(), Box<dyn std::error::Error>>(())
382 /// ```
383 #[inline]
384 pub fn with(self) -> TimeWith {
385 TimeWith::new(self)
386 }
387
388 /// Returns the "hour" component of this time.
389 ///
390 /// The value returned is guaranteed to be in the range `0..=23`.
391 ///
392 /// # Example
393 ///
394 /// ```
395 /// use jiff::civil::time;
396 ///
397 /// let t = time(13, 35, 56, 123_456_789);
398 /// assert_eq!(t.hour(), 13);
399 /// ```
400 #[inline]
401 pub fn hour(self) -> i8 {
402 self.inner.hour()
403 }
404
405 /// Returns the "minute" component of this time.
406 ///
407 /// The value returned is guaranteed to be in the range `0..=59`.
408 ///
409 /// # Example
410 ///
411 /// ```
412 /// use jiff::civil::time;
413 ///
414 /// let t = time(13, 35, 56, 123_456_789);
415 /// assert_eq!(t.minute(), 35);
416 /// ```
417 #[inline]
418 pub fn minute(self) -> i8 {
419 self.inner.minute()
420 }
421
422 /// Returns the "second" component of this time.
423 ///
424 /// The value returned is guaranteed to be in the range `0..=59`.
425 ///
426 /// # Example
427 ///
428 /// ```
429 /// use jiff::civil::time;
430 ///
431 /// let t = time(13, 35, 56, 123_456_789);
432 /// assert_eq!(t.second(), 56);
433 /// ```
434 #[inline]
435 pub fn second(self) -> i8 {
436 self.inner.second()
437 }
438
439 /// Returns the "millisecond" component of this time.
440 ///
441 /// The value returned is guaranteed to be in the range `0..=999`.
442 ///
443 /// # Example
444 ///
445 /// ```
446 /// use jiff::civil::time;
447 ///
448 /// let t = time(13, 35, 56, 123_456_789);
449 /// assert_eq!(t.millisecond(), 123);
450 /// ```
451 #[inline]
452 pub fn millisecond(self) -> i16 {
453 self.inner.millisecond()
454 }
455
456 /// Returns the "microsecond" component of this time.
457 ///
458 /// The value returned is guaranteed to be in the range `0..=999`.
459 ///
460 /// # Example
461 ///
462 /// ```
463 /// use jiff::civil::time;
464 ///
465 /// let t = time(13, 35, 56, 123_456_789);
466 /// assert_eq!(t.microsecond(), 456);
467 /// ```
468 #[inline]
469 pub fn microsecond(self) -> i16 {
470 self.inner.microsecond()
471 }
472
473 /// Returns the "nanosecond" component of this time.
474 ///
475 /// The value returned is guaranteed to be in the range `0..=999`.
476 ///
477 /// # Example
478 ///
479 /// ```
480 /// use jiff::civil::time;
481 ///
482 /// let t = time(13, 35, 56, 123_456_789);
483 /// assert_eq!(t.nanosecond(), 789);
484 /// ```
485 #[inline]
486 pub fn nanosecond(self) -> i16 {
487 self.inner.nanosecond()
488 }
489
490 /// Returns the fractional nanosecond for this `Time` value.
491 ///
492 /// If you want to set this value on `Time`, then use
493 /// [`TimeWith::subsec_nanosecond`] via [`Time::with`].
494 ///
495 /// The value returned is guaranteed to be in the range `0..=999_999_999`.
496 ///
497 /// # Example
498 ///
499 /// This shows the relationship between constructing a `Time` value
500 /// with routines like `with().millisecond()` and accessing the entire
501 /// fractional part as a nanosecond:
502 ///
503 /// ```
504 /// use jiff::civil::time;
505 ///
506 /// let t = time(15, 21, 35, 0).with().millisecond(987).build()?;
507 /// assert_eq!(t.subsec_nanosecond(), 987_000_000);
508 ///
509 /// # Ok::<(), Box<dyn std::error::Error>>(())
510 /// ```
511 ///
512 /// # Example: nanoseconds from a timestamp
513 ///
514 /// This shows how the fractional nanosecond part of a `Time` value
515 /// manifests from a specific timestamp.
516 ///
517 /// ```
518 /// use jiff::Timestamp;
519 ///
520 /// // 1,234 nanoseconds after the Unix epoch.
521 /// let zdt = Timestamp::new(0, 1_234)?.in_tz("UTC")?;
522 /// let time = zdt.datetime().time();
523 /// assert_eq!(time.subsec_nanosecond(), 1_234);
524 ///
525 /// // 1,234 nanoseconds before the Unix epoch.
526 /// let zdt = Timestamp::new(0, -1_234)?.in_tz("UTC")?;
527 /// let time = zdt.datetime().time();
528 /// // The nanosecond is equal to `1_000_000_000 - 1_234`.
529 /// assert_eq!(time.subsec_nanosecond(), 999998766);
530 /// // Looking at the other components of the time value might help.
531 /// assert_eq!(time.hour(), 23);
532 /// assert_eq!(time.minute(), 59);
533 /// assert_eq!(time.second(), 59);
534 ///
535 /// # Ok::<(), Box<dyn std::error::Error>>(())
536 /// ```
537 #[inline]
538 pub fn subsec_nanosecond(self) -> i32 {
539 self.inner.subsec_nanosecond()
540 }
541
542 /// Given a [`Date`], this constructs a [`DateTime`] value with its time
543 /// component equal to this time.
544 ///
545 /// This is a convenience function for [`DateTime::from_parts`].
546 ///
547 /// # Example
548 ///
549 /// ```
550 /// use jiff::civil::{DateTime, date, time};
551 ///
552 /// let d = date(2010, 3, 14);
553 /// let t = time(2, 30, 0, 0);
554 /// assert_eq!(DateTime::from_parts(d, t), t.to_datetime(d));
555 /// ```
556 #[inline]
557 pub const fn to_datetime(self, date: Date) -> DateTime {
558 DateTime::from_parts(date, self)
559 }
560
561 /// A convenience function for constructing a [`DateTime`] from this time
562 /// on the date given by its components.
563 ///
564 /// # Panics
565 ///
566 /// This routine panics when [`Date::new`] with the given inputs would
567 /// return an error. That is, when the given year-month-day does not
568 /// correspond to a valid date. Namely, all of the following must be true:
569 ///
570 /// * The year must be in the range `-9999..=9999`.
571 /// * The month must be in the range `1..=12`.
572 /// * The day must be at least `1` and must be at most the number of days
573 /// in the corresponding month. So for example, `2024-02-29` is valid but
574 /// `2023-02-29` is not.
575 ///
576 /// Similarly, when used in a const context, invalid parameters will
577 /// prevent your Rust program from compiling.
578 ///
579 /// # Example
580 ///
581 /// ```
582 /// use jiff::civil::time;
583 ///
584 /// assert_eq!(
585 /// time(2, 30, 0, 0).on(2010, 3, 14).to_string(),
586 /// "2010-03-14T02:30:00",
587 /// );
588 /// ```
589 ///
590 /// One can also flip the order by making use of [`Date::at`]:
591 ///
592 /// ```
593 /// use jiff::civil::date;
594 ///
595 /// assert_eq!(
596 /// date(2010, 3, 14).at(2, 30, 0, 0).to_string(),
597 /// "2010-03-14T02:30:00",
598 /// );
599 /// ```
600 #[inline]
601 pub const fn on(self, year: i16, month: i8, day: i8) -> DateTime {
602 DateTime::from_parts(Date::constant(year, month, day), self)
603 }
604
605 /// Add the given span to this time and wrap around on overflow.
606 ///
607 /// This operation accepts three different duration types: [`Span`],
608 /// [`SignedDuration`] or [`std::time::Duration`]. This is achieved via
609 /// `From` trait implementations for the [`TimeArithmetic`] type.
610 ///
611 /// # Properties
612 ///
613 /// Given times `t1` and `t2`, and a span `s`, with `t2 = t1 + s`, it
614 /// follows then that `t1 = t2 - s` for all values of `t1` and `s` that sum
615 /// to `t2`.
616 ///
617 /// In short, subtracting the given span from the sum returned by this
618 /// function is guaranteed to result in precisely the original time.
619 ///
620 /// # Example: available via addition operator
621 ///
622 /// This routine can be used via the `+` operator.
623 ///
624 /// ```
625 /// use jiff::{civil::time, ToSpan};
626 ///
627 /// let t = time(20, 10, 1, 0);
628 /// assert_eq!(
629 /// t + 1.hours().minutes(49).seconds(59),
630 /// time(22, 0, 0, 0),
631 /// );
632 /// ```
633 ///
634 /// # Example: add nanoseconds to a `Time`
635 ///
636 /// ```
637 /// use jiff::{civil::time, ToSpan};
638 ///
639 /// let t = time(22, 35, 1, 0);
640 /// assert_eq!(
641 /// time(22, 35, 3, 500_000_000),
642 /// t.wrapping_add(2_500_000_000i64.nanoseconds()),
643 /// );
644 /// ```
645 ///
646 /// # Example: add span with multiple units
647 ///
648 /// ```
649 /// use jiff::{civil::time, ToSpan};
650 ///
651 /// let t = time(20, 10, 1, 0);
652 /// assert_eq!(
653 /// time(22, 0, 0, 0),
654 /// t.wrapping_add(1.hours().minutes(49).seconds(59)),
655 /// );
656 /// ```
657 ///
658 /// # Example: adding an empty span is a no-op
659 ///
660 /// ```
661 /// use jiff::{civil::time, Span};
662 ///
663 /// let t = time(20, 10, 1, 0);
664 /// assert_eq!(t, t.wrapping_add(Span::new()));
665 /// ```
666 ///
667 /// # Example: addition wraps on overflow
668 ///
669 /// ```
670 /// use jiff::{civil::time, SignedDuration, ToSpan};
671 ///
672 /// let t = time(23, 59, 59, 999_999_999);
673 /// assert_eq!(
674 /// t.wrapping_add(1.nanoseconds()),
675 /// time(0, 0, 0, 0),
676 /// );
677 /// assert_eq!(
678 /// t.wrapping_add(SignedDuration::from_nanos(1)),
679 /// time(0, 0, 0, 0),
680 /// );
681 /// assert_eq!(
682 /// t.wrapping_add(std::time::Duration::from_nanos(1)),
683 /// time(0, 0, 0, 0),
684 /// );
685 /// ```
686 ///
687 /// Similarly, if there are any non-zero units greater than hours in the
688 /// given span, then they also result in wrapping behavior (i.e., they are
689 /// ignored):
690 ///
691 /// ```
692 /// use jiff::{civil::time, ToSpan};
693 ///
694 /// // doesn't matter what our time value is in this example
695 /// let t = time(0, 0, 0, 0);
696 /// assert_eq!(t, t.wrapping_add(1.days()));
697 /// ```
698 #[inline]
699 pub fn wrapping_add<A: Into<TimeArithmetic>>(self, duration: A) -> Time {
700 let duration: TimeArithmetic = duration.into();
701 duration.wrapping_add(self)
702 }
703
704 #[inline]
705 fn wrapping_add_span(self, span: Span) -> Time {
706 let sum = self
707 .to_nanosecond()
708 .wrapping_add(
709 i64::from(span.get_hours()).wrapping_mul(c::NANOS_PER_HOUR),
710 )
711 .wrapping_add(span.get_minutes().wrapping_mul(c::NANOS_PER_MIN))
712 .wrapping_add(span.get_seconds().wrapping_mul(c::NANOS_PER_SEC))
713 .wrapping_add(
714 span.get_milliseconds().wrapping_mul(c::NANOS_PER_MILLI),
715 )
716 .wrapping_add(
717 span.get_microseconds().wrapping_mul(c::NANOS_PER_MICRO),
718 )
719 .wrapping_add(span.get_nanoseconds());
720 let civil_day_nanosecond = sum.rem_euclid(c::NANOS_PER_CIVIL_DAY);
721 // OK because of the modulus by `NANOS_PER_CIVIL_DAY`.
722 Time::from_nanosecond(civil_day_nanosecond).unwrap()
723 }
724
725 #[inline]
726 fn wrapping_add_signed_duration(self, duration: SignedDuration) -> Time {
727 let start = i128::from(self.to_nanosecond());
728 let duration = duration.as_nanos();
729 let end = start
730 .wrapping_add(duration)
731 .rem_euclid(c::NANOS_PER_CIVIL_DAY as i128)
732 as i64;
733 // OK because of the modulus by `NANOS_PER_CIVIL_DAY`.
734 Time::from_nanosecond(end).unwrap()
735 }
736
737 #[inline]
738 fn wrapping_add_unsigned_duration(
739 self,
740 duration: UnsignedDuration,
741 ) -> Time {
742 let start = self.to_nanosecond() as u128;
743 let duration = duration.as_nanos();
744 let end = (start.wrapping_add(duration)
745 % (c::NANOS_PER_CIVIL_DAY as u128)) as i64;
746 // OK because of the modulus by `NANOS_PER_CIVIL_DAY`.
747 Time::from_nanosecond(end).unwrap()
748 }
749
750 /// This routine is identical to [`Time::wrapping_add`] with the duration
751 /// negated.
752 ///
753 /// # Example
754 ///
755 /// ```
756 /// use jiff::{civil::time, SignedDuration, ToSpan};
757 ///
758 /// let t = time(0, 0, 0, 0);
759 /// assert_eq!(
760 /// t.wrapping_sub(1.nanoseconds()),
761 /// time(23, 59, 59, 999_999_999),
762 /// );
763 /// assert_eq!(
764 /// t.wrapping_sub(SignedDuration::from_nanos(1)),
765 /// time(23, 59, 59, 999_999_999),
766 /// );
767 /// assert_eq!(
768 /// t.wrapping_sub(std::time::Duration::from_nanos(1)),
769 /// time(23, 59, 59, 999_999_999),
770 /// );
771 ///
772 /// assert_eq!(
773 /// t.wrapping_sub(SignedDuration::MIN),
774 /// time(15, 30, 8, 999_999_999),
775 /// );
776 /// assert_eq!(
777 /// t.wrapping_sub(SignedDuration::MAX),
778 /// time(8, 29, 52, 1),
779 /// );
780 /// assert_eq!(
781 /// t.wrapping_sub(std::time::Duration::MAX),
782 /// time(16, 59, 44, 1),
783 /// );
784 /// ```
785 #[inline]
786 pub fn wrapping_sub<A: Into<TimeArithmetic>>(self, duration: A) -> Time {
787 let duration: TimeArithmetic = duration.into();
788 duration.wrapping_sub(self)
789 }
790
791 #[inline]
792 fn wrapping_sub_unsigned_duration(
793 self,
794 duration: UnsignedDuration,
795 ) -> Time {
796 let start = self.to_nanosecond();
797 let duration = duration.as_nanos();
798 let duration = (duration % c::NANOS_PER_CIVIL_DAY as u128) as i64;
799 let end =
800 start.wrapping_sub(duration).rem_euclid(c::NANOS_PER_CIVIL_DAY);
801 // OK because of the modulus by `NANOS_PER_CIVIL_DAY`.
802 Time::from_nanosecond(end).unwrap()
803 }
804
805 /// Add the given span to this time and return an error if the result would
806 /// otherwise overflow.
807 ///
808 /// This operation accepts three different duration types: [`Span`],
809 /// [`SignedDuration`] or [`std::time::Duration`]. This is achieved via
810 /// `From` trait implementations for the [`TimeArithmetic`] type.
811 ///
812 /// # Properties
813 ///
814 /// Given a time `t1` and a span `s`, and assuming `t2 = t1 + s` exists, it
815 /// follows then that `t1 = t2 - s` for all values of `t1` and `s` that sum
816 /// to a valid `t2`.
817 ///
818 /// In short, subtracting the given span from the sum returned by this
819 /// function is guaranteed to result in precisely the original time.
820 ///
821 /// # Errors
822 ///
823 /// If the sum would overflow the minimum or maximum timestamp values, then
824 /// an error is returned.
825 ///
826 /// If the given span has any non-zero units greater than hours, then an
827 /// error is returned.
828 ///
829 /// # Example: add nanoseconds to a `Time`
830 ///
831 /// ```
832 /// use jiff::{civil::time, ToSpan};
833 ///
834 /// let t = time(22, 35, 1, 0);
835 /// assert_eq!(
836 /// time(22, 35, 3, 500_000_000),
837 /// t.checked_add(2_500_000_000i64.nanoseconds())?,
838 /// );
839 /// # Ok::<(), Box<dyn std::error::Error>>(())
840 /// ```
841 ///
842 /// # Example: add span with multiple units
843 ///
844 /// ```
845 /// use jiff::{civil::time, ToSpan};
846 ///
847 /// let t = time(20, 10, 1, 0);
848 /// assert_eq!(
849 /// time(22, 0, 0, 0),
850 /// t.checked_add(1.hours().minutes(49).seconds(59))?,
851 /// );
852 /// # Ok::<(), Box<dyn std::error::Error>>(())
853 /// ```
854 ///
855 /// # Example: adding an empty span is a no-op
856 ///
857 /// ```
858 /// use jiff::{civil::time, Span};
859 ///
860 /// let t = time(20, 10, 1, 0);
861 /// assert_eq!(t, t.checked_add(Span::new())?);
862 ///
863 /// # Ok::<(), Box<dyn std::error::Error>>(())
864 /// ```
865 ///
866 /// # Example: error on overflow
867 ///
868 /// ```
869 /// use jiff::{civil::time, ToSpan};
870 ///
871 /// // okay
872 /// let t = time(23, 59, 59, 999_999_998);
873 /// assert_eq!(
874 /// t.with().nanosecond(999).build()?,
875 /// t.checked_add(1.nanoseconds())?,
876 /// );
877 ///
878 /// // not okay
879 /// let t = time(23, 59, 59, 999_999_999);
880 /// assert!(t.checked_add(1.nanoseconds()).is_err());
881 ///
882 /// # Ok::<(), Box<dyn std::error::Error>>(())
883 /// ```
884 ///
885 /// Similarly, if there are any non-zero units greater than hours in the
886 /// given span, then they also result in overflow (and thus an error):
887 ///
888 /// ```
889 /// use jiff::{civil::time, ToSpan};
890 ///
891 /// // doesn't matter what our time value is in this example
892 /// let t = time(0, 0, 0, 0);
893 /// assert!(t.checked_add(1.days()).is_err());
894 /// ```
895 ///
896 /// # Example: adding absolute durations
897 ///
898 /// This shows how to add signed and unsigned absolute durations to a
899 /// `Time`. As with adding a `Span`, any overflow that occurs results in
900 /// an error.
901 ///
902 /// ```
903 /// use std::time::Duration;
904 ///
905 /// use jiff::{civil::time, SignedDuration};
906 ///
907 /// let t = time(23, 0, 0, 0);
908 ///
909 /// let dur = SignedDuration::from_mins(30);
910 /// assert_eq!(t.checked_add(dur)?, time(23, 30, 0, 0));
911 /// assert_eq!(t.checked_add(-dur)?, time(22, 30, 0, 0));
912 ///
913 /// let dur = Duration::new(0, 1);
914 /// assert_eq!(t.checked_add(dur)?, time(23, 0, 0, 1));
915 ///
916 /// # Ok::<(), Box<dyn std::error::Error>>(())
917 /// ```
918 #[inline]
919 pub fn checked_add<A: Into<TimeArithmetic>>(
920 self,
921 duration: A,
922 ) -> Result<Time, Error> {
923 let duration: TimeArithmetic = duration.into();
924 duration.checked_add(self)
925 }
926
927 #[inline]
928 fn checked_add_span(self, span: &Span) -> Result<Time, Error> {
929 let (time, span) = self.overflowing_add(span)?;
930 if span.smallest_non_time_non_zero_unit_error().is_some() {
931 return Err(Error::from(E::OverflowTimeNanoseconds));
932 }
933 Ok(time)
934 }
935
936 #[inline]
937 fn checked_add_duration(
938 self,
939 duration: SignedDuration,
940 ) -> Result<Time, Error> {
941 // NOTE: Every approach here just seems so circuitous...
942 // Checking when we convert to the same primitive representation.
943 // Checking when we add.
944 // Checking that the result is in bounds.
945 // Just seems very wateful and annoying.
946 let start = self.to_nanosecond();
947 let duration =
948 duration.as_nanos64().ok_or(E::OverflowTimeNanoseconds)?;
949 let end =
950 start.checked_add(duration).ok_or(E::OverflowTimeNanoseconds)?;
951 Time::from_nanosecond(end)
952 }
953
954 /// This routine is identical to [`Time::checked_add`] with the duration
955 /// negated.
956 ///
957 /// # Errors
958 ///
959 /// This has the same error conditions as [`Time::checked_add`].
960 ///
961 /// # Example
962 ///
963 /// ```
964 /// use std::time::Duration;
965 ///
966 /// use jiff::{civil::time, SignedDuration, ToSpan};
967 ///
968 /// let t = time(22, 0, 0, 0);
969 /// assert_eq!(
970 /// t.checked_sub(1.hours().minutes(49).seconds(59))?,
971 /// time(20, 10, 1, 0),
972 /// );
973 /// assert_eq!(
974 /// t.checked_sub(SignedDuration::from_hours(1))?,
975 /// time(21, 0, 0, 0),
976 /// );
977 /// assert_eq!(
978 /// t.checked_sub(Duration::from_secs(60 * 60))?,
979 /// time(21, 0, 0, 0),
980 /// );
981 /// # Ok::<(), Box<dyn std::error::Error>>(())
982 /// ```
983 #[inline]
984 pub fn checked_sub<A: Into<TimeArithmetic>>(
985 self,
986 duration: A,
987 ) -> Result<Time, Error> {
988 let duration: TimeArithmetic = duration.into();
989 duration.checked_neg().and_then(|ta| ta.checked_add(self))
990 }
991
992 /// This routine is identical to [`Time::checked_add`], except the
993 /// result saturates on overflow. That is, instead of overflow, either
994 /// [`Time::MIN`] or [`Time::MAX`] is returned.
995 ///
996 /// # Example
997 ///
998 /// ```
999 /// use jiff::{civil::{Time, time}, SignedDuration, ToSpan};
1000 ///
1001 /// // no saturation
1002 /// let t = time(23, 59, 59, 999_999_998);
1003 /// assert_eq!(
1004 /// t.with().nanosecond(999).build()?,
1005 /// t.saturating_add(1.nanoseconds()),
1006 /// );
1007 ///
1008 /// // saturates
1009 /// let t = time(23, 59, 59, 999_999_999);
1010 /// assert_eq!(Time::MAX, t.saturating_add(1.nanoseconds()));
1011 /// assert_eq!(Time::MAX, t.saturating_add(SignedDuration::MAX));
1012 /// assert_eq!(Time::MIN, t.saturating_add(SignedDuration::MIN));
1013 /// assert_eq!(Time::MAX, t.saturating_add(std::time::Duration::MAX));
1014 ///
1015 /// # Ok::<(), Box<dyn std::error::Error>>(())
1016 /// ```
1017 ///
1018 /// Similarly, if there are any non-zero units greater than hours in the
1019 /// given span, then they also result in overflow (and thus saturation):
1020 ///
1021 /// ```
1022 /// use jiff::{civil::{Time, time}, ToSpan};
1023 ///
1024 /// // doesn't matter what our time value is in this example
1025 /// let t = time(0, 0, 0, 0);
1026 /// assert_eq!(Time::MAX, t.saturating_add(1.days()));
1027 /// ```
1028 #[inline]
1029 pub fn saturating_add<A: Into<TimeArithmetic>>(self, duration: A) -> Time {
1030 let duration: TimeArithmetic = duration.into();
1031 self.checked_add(duration).unwrap_or_else(|_| {
1032 if duration.is_negative() { Time::MIN } else { Time::MAX }
1033 })
1034 }
1035
1036 /// This routine is identical to [`Time::saturating_add`] with the duration
1037 /// negated.
1038 ///
1039 /// # Example
1040 ///
1041 /// ```
1042 /// use jiff::{civil::{Time, time}, SignedDuration, ToSpan};
1043 ///
1044 /// // no saturation
1045 /// let t = time(0, 0, 0, 1);
1046 /// assert_eq!(
1047 /// t.with().nanosecond(0).build()?,
1048 /// t.saturating_sub(1.nanoseconds()),
1049 /// );
1050 ///
1051 /// // saturates
1052 /// let t = time(0, 0, 0, 0);
1053 /// assert_eq!(Time::MIN, t.saturating_sub(1.nanoseconds()));
1054 /// assert_eq!(Time::MIN, t.saturating_sub(SignedDuration::MAX));
1055 /// assert_eq!(Time::MAX, t.saturating_sub(SignedDuration::MIN));
1056 /// assert_eq!(Time::MIN, t.saturating_sub(std::time::Duration::MAX));
1057 ///
1058 /// # Ok::<(), Box<dyn std::error::Error>>(())
1059 /// ```
1060 #[inline]
1061 pub fn saturating_sub<A: Into<TimeArithmetic>>(self, duration: A) -> Time {
1062 let duration: TimeArithmetic = duration.into();
1063 let Ok(duration) = duration.checked_neg() else { return Time::MIN };
1064 self.saturating_add(duration)
1065 }
1066
1067 /// Adds the given span to the this time value, and returns the resulting
1068 /// time with any overflowing amount in the span returned.
1069 ///
1070 /// This isn't part of the public API because it seems a little odd, and
1071 /// I'm unsure of its use case. Overall this routine is a bit specialized
1072 /// and I'm not sure how generally useful it is. But it is used in crucial
1073 /// points in other parts of this crate.
1074 ///
1075 /// If you want this public, please file an issue and discuss your use
1076 /// case: https://github.com/BurntSushi/jiff/issues/new
1077 #[inline]
1078 pub(crate) fn overflowing_add(
1079 self,
1080 span: &Span,
1081 ) -> Result<(Time, Span), Error> {
1082 if let Some(err) = span.smallest_non_time_non_zero_unit_error() {
1083 return Err(err);
1084 }
1085
1086 let span = span.to_invariant_duration().as_nanos();
1087 let time = i128::from(self.to_nanosecond());
1088 let sum = span + time;
1089 let days = sum.div_euclid(i128::from(c::NANOS_PER_CIVIL_DAY)) as i64;
1090 let rem = sum.rem_euclid(i128::from(c::NANOS_PER_CIVIL_DAY)) as i64;
1091 let span = Span::new().try_days(days)?;
1092 // OK because of the modulus by `NANOS_PER_CIVIL_DAY`.
1093 Ok((Time::from_nanosecond(rem).unwrap(), span))
1094 }
1095
1096 /// Like `overflowing_add`, but with `SignedDuration`.
1097 ///
1098 /// This is used for datetime arithmetic, when adding to the time
1099 /// component overflows into days (always 24 hours).
1100 #[inline]
1101 pub(crate) fn overflowing_add_duration(
1102 self,
1103 duration: SignedDuration,
1104 ) -> Result<(Time, SignedDuration), Error> {
1105 if self.subsec_nanosecond() != 0 || duration.subsec_nanos() != 0 {
1106 return self.overflowing_add_duration_general(duration);
1107 }
1108 let start = i64::from(self.to_second());
1109 let duration_secs = duration.as_secs();
1110 // This can fail if the duration is near its min or max values, and
1111 // thus we fall back to the more general (but slower) implementation
1112 // that uses 128-bit integers.
1113 let Some(sum) = start.checked_add(duration_secs) else {
1114 return self.overflowing_add_duration_general(duration);
1115 };
1116
1117 let days = b::SpanDays::check(sum.div_euclid(c::SECS_PER_CIVIL_DAY))?;
1118 let rem = sum.rem_euclid(c::SECS_PER_CIVIL_DAY) as i32;
1119 // OK because of the modulus by `SECS_PER_CIVIL_DAY`.
1120 let time = Time::from_second(rem).unwrap();
1121 Ok((time, SignedDuration::from_civil_days32(days)))
1122 }
1123
1124 /// Like `overflowing_add`, but with `SignedDuration`.
1125 ///
1126 /// This is used for datetime arithmetic, when adding to the time
1127 /// component overflows into days (always 24 hours).
1128 #[inline(never)]
1129 #[cold]
1130 fn overflowing_add_duration_general(
1131 self,
1132 duration: SignedDuration,
1133 ) -> Result<(Time, SignedDuration), Error> {
1134 let start = i128::from(self.to_nanosecond());
1135 let duration = duration.as_nanos();
1136 // This can never fail because the maximum duration fits into a
1137 // 96-bit integer, and adding any 96-bit integer to any 64-bit
1138 // integer can never overflow a 128-bit integer.
1139 let sum = start + duration;
1140 let days =
1141 i64::try_from(sum.div_euclid(i128::from(c::NANOS_PER_CIVIL_DAY)))
1142 .map_err(|_| b::SpanDays::error())?;
1143 let days = b::SpanDays::check(days)?;
1144 let rem = sum.rem_euclid(i128::from(c::NANOS_PER_CIVIL_DAY)) as i64;
1145 // OK because of the modulus by `NANOS_PER_CIVIL_DAY`.
1146 let time = Time::from_nanosecond(rem).unwrap();
1147 Ok((time, SignedDuration::from_civil_days32(days)))
1148 }
1149
1150 /// Returns a span representing the elapsed time from this time until
1151 /// the given `other` time.
1152 ///
1153 /// When `other` is earlier than this time, the span returned will be
1154 /// negative.
1155 ///
1156 /// Depending on the input provided, the span returned is rounded. It may
1157 /// also be balanced down to smaller units than the default. By default,
1158 /// the span returned is balanced such that the biggest possible unit is
1159 /// hours.
1160 ///
1161 /// This operation is configured by providing a [`TimeDifference`]
1162 /// value. Since this routine accepts anything that implements
1163 /// `Into<TimeDifference>`, once can pass a `Time` directly. One
1164 /// can also pass a `(Unit, Time)`, where `Unit` is treated as
1165 /// [`TimeDifference::largest`].
1166 ///
1167 /// # Properties
1168 ///
1169 /// As long as no rounding is requested, it is guaranteed that adding the
1170 /// span returned to this time will always equal the `other` time.
1171 ///
1172 /// # Errors
1173 ///
1174 /// An error can occur if `TimeDifference` is misconfigured. For example,
1175 /// if the smallest unit provided is bigger than the largest unit, or if
1176 /// the largest unit is bigger than [`Unit::Hour`].
1177 ///
1178 /// It is guaranteed that if one provides a time with the default
1179 /// [`TimeDifference`] configuration, then this routine will never fail.
1180 ///
1181 /// # Examples
1182 ///
1183 /// ```
1184 /// use jiff::{civil::time, ToSpan};
1185 ///
1186 /// let t1 = time(22, 35, 1, 0);
1187 /// let t2 = time(22, 35, 3, 500_000_000);
1188 /// assert_eq!(t1.until(t2)?, 2.seconds().milliseconds(500).fieldwise());
1189 /// // Flipping the dates is fine, but you'll get a negative span.
1190 /// assert_eq!(t2.until(t1)?, -2.seconds().milliseconds(500).fieldwise());
1191 ///
1192 /// # Ok::<(), Box<dyn std::error::Error>>(())
1193 /// ```
1194 ///
1195 /// # Example: using smaller units
1196 ///
1197 /// This example shows how to contract the span returned to smaller units.
1198 /// This makes use of a `From<(Unit, Time)> for TimeDifference`
1199 /// trait implementation.
1200 ///
1201 /// ```
1202 /// use jiff::{civil::time, Unit, ToSpan};
1203 ///
1204 /// let t1 = time(3, 24, 30, 3500);
1205 /// let t2 = time(15, 30, 0, 0);
1206 ///
1207 /// // The default limits spans to using "hours" as the biggest unit.
1208 /// let span = t1.until(t2)?;
1209 /// assert_eq!(span.to_string(), "PT12H5M29.9999965S");
1210 ///
1211 /// // But we can ask for smaller units, like capping the biggest unit
1212 /// // to minutes instead of hours.
1213 /// let span = t1.until((Unit::Minute, t2))?;
1214 /// assert_eq!(span.to_string(), "PT725M29.9999965S");
1215 ///
1216 /// # Ok::<(), Box<dyn std::error::Error>>(())
1217 /// ```
1218 #[inline]
1219 pub fn until<A: Into<TimeDifference>>(
1220 self,
1221 other: A,
1222 ) -> Result<Span, Error> {
1223 let args: TimeDifference = other.into();
1224 let span = args.until_with_largest_unit(self)?;
1225 if args.rounding_may_change_span() {
1226 span.round(args.round)
1227 } else {
1228 Ok(span)
1229 }
1230 }
1231
1232 /// This routine is identical to [`Time::until`], but the order of the
1233 /// parameters is flipped.
1234 ///
1235 /// # Errors
1236 ///
1237 /// This has the same error conditions as [`Time::until`].
1238 ///
1239 /// # Example
1240 ///
1241 /// This routine can be used via the `-` operator. Since the default
1242 /// configuration is used and because a `Span` can represent the difference
1243 /// between any two possible times, it will never panic.
1244 ///
1245 /// ```
1246 /// use jiff::{civil::time, ToSpan};
1247 ///
1248 /// let earlier = time(1, 0, 0, 0);
1249 /// let later = time(22, 30, 0, 0);
1250 /// assert_eq!(later - earlier, 21.hours().minutes(30).fieldwise());
1251 /// ```
1252 #[inline]
1253 pub fn since<A: Into<TimeDifference>>(
1254 self,
1255 other: A,
1256 ) -> Result<Span, Error> {
1257 let args: TimeDifference = other.into();
1258 let span = -args.until_with_largest_unit(self)?;
1259 if args.rounding_may_change_span() {
1260 span.round(args.round)
1261 } else {
1262 Ok(span)
1263 }
1264 }
1265
1266 /// Returns an absolute duration representing the elapsed time from this
1267 /// time until the given `other` time.
1268 ///
1269 /// When `other` occurs before this time, then the duration returned will
1270 /// be negative.
1271 ///
1272 /// Unlike [`Time::until`], this returns a duration corresponding to a
1273 /// 96-bit integer of nanoseconds between two times. In this case of
1274 /// computing durations between civil times where all days are assumed to
1275 /// be 24 hours long, the duration returned will always be less than 24
1276 /// hours.
1277 ///
1278 /// # Fallibility
1279 ///
1280 /// This routine never panics or returns an error. Since there are no
1281 /// configuration options that can be incorrectly provided, no error is
1282 /// possible when calling this routine. In contrast, [`Time::until`] can
1283 /// return an error in some cases due to misconfiguration. But like this
1284 /// routine, [`Time::until`] never panics or returns an error in its
1285 /// default configuration.
1286 ///
1287 /// # When should I use this versus [`Time::until`]?
1288 ///
1289 /// See the type documentation for [`SignedDuration`] for the section on
1290 /// when one should use [`Span`] and when one should use `SignedDuration`.
1291 /// In short, use `Span` (and therefore `Time::until`) unless you have a
1292 /// specific reason to do otherwise.
1293 ///
1294 /// # Example
1295 ///
1296 /// ```
1297 /// use jiff::{civil::time, SignedDuration};
1298 ///
1299 /// let t1 = time(22, 35, 1, 0);
1300 /// let t2 = time(22, 35, 3, 500_000_000);
1301 /// assert_eq!(t1.duration_until(t2), SignedDuration::new(2, 500_000_000));
1302 /// // Flipping the time is fine, but you'll get a negative duration.
1303 /// assert_eq!(t2.duration_until(t1), -SignedDuration::new(2, 500_000_000));
1304 /// ```
1305 ///
1306 /// # Example: difference with [`Time::until`]
1307 ///
1308 /// Since the difference between two civil times is always expressed in
1309 /// units of hours or smaller, and units of hours or smaller are always
1310 /// uniform, there is no "expressive" difference between this routine and
1311 /// `Time::until`. The only difference is that this routine returns a
1312 /// `SignedDuration` and `Time::until` returns a [`Span`]. Moreover, since
1313 /// the difference is always less than 24 hours, the return values can
1314 /// always be infallibly and losslessly converted between each other:
1315 ///
1316 /// ```
1317 /// use jiff::{civil::time, SignedDuration, Span};
1318 ///
1319 /// let t1 = time(22, 35, 1, 0);
1320 /// let t2 = time(22, 35, 3, 500_000_000);
1321 /// let dur = t1.duration_until(t2);
1322 /// // Guaranteed to never fail because the duration
1323 /// // between two civil times never exceeds the limits
1324 /// // of a `Span`.
1325 /// let span = Span::try_from(dur).unwrap();
1326 /// assert_eq!(span, Span::new().seconds(2).milliseconds(500).fieldwise());
1327 /// // Guaranteed to succeed and always return the original
1328 /// // duration because the units are always hours or smaller,
1329 /// // and thus uniform. This means a relative datetime is
1330 /// // never required to do this conversion.
1331 /// let dur = SignedDuration::try_from(span).unwrap();
1332 /// assert_eq!(dur, SignedDuration::new(2, 500_000_000));
1333 /// ```
1334 ///
1335 /// This conversion guarantee also applies to [`Time::until`] since it
1336 /// always returns a balanced span. That is, it never returns spans like
1337 /// `1 second 1000 milliseconds`. (Those cannot be losslessly converted to
1338 /// a `SignedDuration` since a `SignedDuration` is only represented as a
1339 /// single 96-bit integer of nanoseconds.)
1340 ///
1341 /// # Example: getting an unsigned duration
1342 ///
1343 /// If you're looking to find the duration between two times as a
1344 /// [`std::time::Duration`], you'll need to use this method to get a
1345 /// [`SignedDuration`] and then convert it to a `std::time::Duration`:
1346 ///
1347 /// ```
1348 /// use std::time::Duration;
1349 ///
1350 /// use jiff::{civil::time, SignedDuration, Span};
1351 ///
1352 /// let t1 = time(22, 35, 1, 0);
1353 /// let t2 = time(22, 35, 3, 500_000_000);
1354 /// let dur = Duration::try_from(t1.duration_until(t2))?;;
1355 /// assert_eq!(dur, Duration::new(2, 500_000_000));
1356 ///
1357 /// // Note that unsigned durations cannot represent all
1358 /// // possible differences! If the duration would be negative,
1359 /// // then the conversion fails:
1360 /// assert!(Duration::try_from(t2.duration_until(t1)).is_err());
1361 ///
1362 /// # Ok::<(), Box<dyn std::error::Error>>(())
1363 /// ```
1364 #[inline]
1365 pub fn duration_until(self, other: Time) -> SignedDuration {
1366 SignedDuration::time_until(self, other)
1367 }
1368
1369 /// This routine is identical to [`Time::duration_until`], but the order of
1370 /// the parameters is flipped.
1371 ///
1372 /// # Example
1373 ///
1374 /// ```
1375 /// use jiff::{civil::time, SignedDuration};
1376 ///
1377 /// let earlier = time(1, 0, 0, 0);
1378 /// let later = time(22, 30, 0, 0);
1379 /// assert_eq!(
1380 /// later.duration_since(earlier),
1381 /// SignedDuration::from_secs((21 * 60 * 60) + (30 * 60)),
1382 /// );
1383 /// ```
1384 #[inline]
1385 pub fn duration_since(self, other: Time) -> SignedDuration {
1386 SignedDuration::time_until(other, self)
1387 }
1388
1389 /// Rounds this time according to the [`TimeRound`] configuration given.
1390 ///
1391 /// The principal option is [`TimeRound::smallest`], which allows one
1392 /// to configure the smallest units in the returned time. Rounding
1393 /// is what determines whether that unit should keep its current value
1394 /// or whether it should be incremented. Moreover, the amount it should
1395 /// be incremented can be configured via [`TimeRound::increment`].
1396 /// Finally, the rounding strategy itself can be configured via
1397 /// [`TimeRound::mode`].
1398 ///
1399 /// Note that this routine is generic and accepts anything that
1400 /// implements `Into<TimeRound>`. Some notable implementations are:
1401 ///
1402 /// * `From<Unit> for Round`, which will automatically create a
1403 /// `TimeRound::new().smallest(unit)` from the unit provided.
1404 /// * `From<(Unit, i64)> for Round`, which will automatically create a
1405 /// `TimeRound::new().smallest(unit).increment(number)` from the unit
1406 /// and increment provided.
1407 ///
1408 /// # Errors
1409 ///
1410 /// This returns an error if the smallest unit configured on the given
1411 /// [`TimeRound`] is bigger than hours.
1412 ///
1413 /// The rounding increment must divide evenly into the next highest unit
1414 /// after the smallest unit configured (and must not be equivalent to it).
1415 /// For example, if the smallest unit is [`Unit::Nanosecond`], then *some*
1416 /// of the valid values for the rounding increment are `1`, `2`, `4`, `5`,
1417 /// `100` and `500`. Namely, any integer that divides evenly into `1,000`
1418 /// nanoseconds since there are `1,000` nanoseconds in the next highest
1419 /// unit (microseconds).
1420 ///
1421 /// This can never fail because of overflow for any input. The only
1422 /// possible errors are "configuration" errors.
1423 ///
1424 /// # Example
1425 ///
1426 /// This is a basic example that demonstrates rounding a datetime to the
1427 /// nearest second. This also demonstrates calling this method with the
1428 /// smallest unit directly, instead of constructing a `TimeRound` manually.
1429 ///
1430 /// ```
1431 /// use jiff::{civil::time, Unit};
1432 ///
1433 /// let t = time(15, 45, 10, 123_456_789);
1434 /// assert_eq!(
1435 /// t.round(Unit::Second)?,
1436 /// time(15, 45, 10, 0),
1437 /// );
1438 /// let t = time(15, 45, 10, 500_000_001);
1439 /// assert_eq!(
1440 /// t.round(Unit::Second)?,
1441 /// time(15, 45, 11, 0),
1442 /// );
1443 ///
1444 /// # Ok::<(), Box<dyn std::error::Error>>(())
1445 /// ```
1446 ///
1447 /// # Example: changing the rounding mode
1448 ///
1449 /// The default rounding mode is [`RoundMode::HalfExpand`], which
1450 /// breaks ties by rounding away from zero. But other modes like
1451 /// [`RoundMode::Trunc`] can be used too:
1452 ///
1453 /// ```
1454 /// use jiff::{civil::{TimeRound, time}, RoundMode, Unit};
1455 ///
1456 /// let t = time(15, 45, 10, 999_999_999);
1457 /// assert_eq!(
1458 /// t.round(Unit::Second)?,
1459 /// time(15, 45, 11, 0),
1460 /// );
1461 /// // The default will round up to the next second for any fraction
1462 /// // greater than or equal to 0.5. But truncation will always round
1463 /// // toward zero.
1464 /// assert_eq!(
1465 /// t.round(
1466 /// TimeRound::new().smallest(Unit::Second).mode(RoundMode::Trunc),
1467 /// )?,
1468 /// time(15, 45, 10, 0),
1469 /// );
1470 ///
1471 /// # Ok::<(), Box<dyn std::error::Error>>(())
1472 /// ```
1473 ///
1474 /// # Example: rounding to the nearest 5 minute increment
1475 ///
1476 /// ```
1477 /// use jiff::{civil::time, Unit};
1478 ///
1479 /// // rounds down
1480 /// let t = time(15, 27, 29, 999_999_999);
1481 /// assert_eq!(t.round((Unit::Minute, 5))?, time(15, 25, 0, 0));
1482 /// // rounds up
1483 /// let t = time(15, 27, 30, 0);
1484 /// assert_eq!(t.round((Unit::Minute, 5))?, time(15, 30, 0, 0));
1485 ///
1486 /// # Ok::<(), Box<dyn std::error::Error>>(())
1487 /// ```
1488 ///
1489 /// # Example: rounding wraps around on overflow
1490 ///
1491 /// This example demonstrates that it's possible for this operation to
1492 /// overflow, and as a result, have the time wrap around.
1493 ///
1494 /// ```
1495 /// use jiff::{civil::Time, Unit};
1496 ///
1497 /// let t = Time::MAX;
1498 /// assert_eq!(t.round(Unit::Hour)?, Time::MIN);
1499 ///
1500 /// # Ok::<(), Box<dyn std::error::Error>>(())
1501 /// ```
1502 #[inline]
1503 pub fn round<R: Into<TimeRound>>(self, options: R) -> Result<Time, Error> {
1504 let options: TimeRound = options.into();
1505 options.round(self)
1506 }
1507
1508 /// Return an iterator of periodic times determined by the given span.
1509 ///
1510 /// The given span may be negative, in which case, the iterator will move
1511 /// backwards through time. The iterator won't stop until either the span
1512 /// itself overflows, or it would otherwise exceed the minimum or maximum
1513 /// `Time` value.
1514 ///
1515 /// # Example: visiting every third hour
1516 ///
1517 /// This shows how to visit each third hour of a 24 hour time interval:
1518 ///
1519 /// ```
1520 /// use jiff::{civil::{Time, time}, ToSpan};
1521 ///
1522 /// let start = Time::MIN;
1523 /// let mut every_third_hour = vec![];
1524 /// for t in start.series(3.hours()) {
1525 /// every_third_hour.push(t);
1526 /// }
1527 /// assert_eq!(every_third_hour, vec![
1528 /// time(0, 0, 0, 0),
1529 /// time(3, 0, 0, 0),
1530 /// time(6, 0, 0, 0),
1531 /// time(9, 0, 0, 0),
1532 /// time(12, 0, 0, 0),
1533 /// time(15, 0, 0, 0),
1534 /// time(18, 0, 0, 0),
1535 /// time(21, 0, 0, 0),
1536 /// ]);
1537 /// ```
1538 ///
1539 /// Or go backwards every 6.5 hours:
1540 ///
1541 /// ```
1542 /// use jiff::{civil::{Time, time}, ToSpan};
1543 ///
1544 /// let start = time(23, 0, 0, 0);
1545 /// let times: Vec<Time> = start.series(-6.hours().minutes(30)).collect();
1546 /// assert_eq!(times, vec![
1547 /// time(23, 0, 0, 0),
1548 /// time(16, 30, 0, 0),
1549 /// time(10, 0, 0, 0),
1550 /// time(3, 30, 0, 0),
1551 /// ]);
1552 /// ```
1553 #[inline]
1554 pub fn series(self, period: Span) -> TimeSeries {
1555 TimeSeries { start: self, period, step: 0 }
1556 }
1557}
1558
1559/// Parsing and formatting using a "printf"-style API.
1560impl Time {
1561 /// Parses a civil time in `input` matching the given `format`.
1562 ///
1563 /// The format string uses a "printf"-style API where conversion
1564 /// specifiers can be used as place holders to match components of
1565 /// a datetime. For details on the specifiers supported, see the
1566 /// [`fmt::strtime`] module documentation.
1567 ///
1568 /// # Errors
1569 ///
1570 /// This returns an error when parsing failed. This might happen because
1571 /// the format string itself was invalid, or because the input didn't match
1572 /// the format string.
1573 ///
1574 /// This also returns an error if there wasn't sufficient information to
1575 /// construct a civil time. For example, if an offset wasn't parsed.
1576 ///
1577 /// # Example
1578 ///
1579 /// This example shows how to parse a civil time:
1580 ///
1581 /// ```
1582 /// use jiff::civil::Time;
1583 ///
1584 /// // Parse with a 12-hour clock.
1585 /// let time = Time::strptime("%I:%M%P", "4:30pm")?;
1586 /// assert_eq!(time.to_string(), "16:30:00");
1587 ///
1588 /// # Ok::<(), Box<dyn std::error::Error>>(())
1589 /// ```
1590 #[inline]
1591 pub fn strptime(
1592 format: impl AsRef<[u8]>,
1593 input: impl AsRef<[u8]>,
1594 ) -> Result<Time, Error> {
1595 fmt::strtime::parse(format, input).and_then(|tm| tm.to_time())
1596 }
1597
1598 /// Formats this civil time according to the given `format`.
1599 ///
1600 /// The format string uses a "printf"-style API where conversion
1601 /// specifiers can be used as place holders to format components of
1602 /// a datetime. For details on the specifiers supported, see the
1603 /// [`fmt::strtime`] module documentation.
1604 ///
1605 /// # Errors and panics
1606 ///
1607 /// This will never error or panic. In particular,
1608 /// [lenient mode](crate::fmt::strtime::Config::lenient) is enabled, which
1609 /// means that all possible strings have some non-error interpretation.
1610 /// Note that because of this, and since Jiff may add new conversion
1611 /// specifiers in the future, the behavior of a format string may change
1612 /// when it would otherwise be invalid.
1613 ///
1614 /// To format in a way that surfaces errors, use either
1615 /// [`fmt::strtime::format`] or [`fmt::strtime::BrokenDownTime::format`].
1616 ///
1617 /// # Example
1618 ///
1619 /// This example shows how to format a civil time in a 12 hour clock with
1620 /// no padding for the hour:
1621 ///
1622 /// ```
1623 /// use jiff::civil::time;
1624 ///
1625 /// let t = time(16, 30, 59, 0);
1626 /// let string = t.strftime("%-I:%M%P").to_string();
1627 /// assert_eq!(string, "4:30pm");
1628 /// ```
1629 ///
1630 /// Note that one can round a `Time` before formatting. For example, to
1631 /// round to the nearest minute:
1632 ///
1633 /// ```
1634 /// use jiff::{civil::time, Unit};
1635 ///
1636 /// let t = time(16, 30, 59, 0);
1637 /// let string = t.round(Unit::Minute)?.strftime("%-I:%M%P").to_string();
1638 /// assert_eq!(string, "4:31pm");
1639 ///
1640 /// # Ok::<(), Box<dyn std::error::Error>>(())
1641 /// ```
1642 ///
1643 /// # Example: errors are silently ignored
1644 ///
1645 /// If the formatting string is malformed in some way, then it is silently
1646 /// ignored. For example, when using an invalid formatting directive:
1647 ///
1648 /// ```
1649 /// use jiff::civil::time;
1650 ///
1651 /// let t = time(16, 30, 59, 0);
1652 /// let string = t.strftime("%H %").to_string();
1653 /// assert_eq!(string, "16 %");
1654 /// ```
1655 ///
1656 /// If one wants to surface errors from a formatting string, use a lower
1657 /// level API:
1658 ///
1659 /// ```
1660 /// use jiff::civil::time;
1661 ///
1662 /// let t = time(16, 30, 59, 0);
1663 /// assert_eq!(
1664 /// jiff::fmt::strtime::format("%H %", t).unwrap_err().to_string(),
1665 /// "strftime formatting failed: invalid format string, \
1666 /// expected byte after `%`, but found end of format string",
1667 /// );
1668 /// ```
1669 #[inline]
1670 pub fn strftime<'f, F: 'f + ?Sized + AsRef<[u8]>>(
1671 &self,
1672 format: &'f F,
1673 ) -> fmt::strtime::Display<'f> {
1674 fmt::strtime::Display { fmt: format.as_ref(), tm: (*self).into() }
1675 }
1676}
1677
1678/// Crate internal APIs.
1679///
1680/// Many of these are mirrors of the public API, but on ranged types. These
1681/// are often much more convenient to use in composition with other parts of
1682/// the crate that also use ranged integer types. And this often permits the
1683/// routines to be infallible and (possibly) zero-cost.
1684impl Time {
1685 #[inline]
1686 pub(crate) fn until_nanoseconds(self, other: Time) -> i64 {
1687 other.to_nanosecond() - self.to_nanosecond()
1688 }
1689
1690 #[inline]
1691 pub(crate) fn to_duration(&self) -> SignedDuration {
1692 SignedDuration::from_nanos(self.to_nanosecond())
1693 }
1694
1695 /// Converts the given duration to a time value. The duration should
1696 /// correspond to the number of nanoseconds that have elapsed since
1697 /// `00:00:00.000000000`.
1698 ///
1699 /// This returns an error when the given duration exceeds the range
1700 /// specified by `b::CivilDayNanosecond`.
1701 #[cfg_attr(feature = "perf-inline", inline(always))]
1702 pub(crate) fn from_duration(dur: SignedDuration) -> Result<Time, Error> {
1703 let secs = b::CivilDaySecond::check(dur.as_secs())?;
1704 JTimeSecond::new(secs)
1705 .map(|second| second.to_time())
1706 .and_then(|time| time.with_subsec_nanosecond(dur.subsec_nanos()))
1707 .map(Time::from_jcore)
1708 .map_err(Error::jcore_range)
1709 }
1710
1711 /// Converts this time value to the number of seconds that has elapsed
1712 /// since `00:00:00`. This completely ignores seconds. Callers should
1713 /// likely ensure that the fractional second component is zero.
1714 ///
1715 /// The maximum possible value that can be returned represents the time
1716 /// `23:59:59`.
1717 #[inline]
1718 fn to_second(&self) -> i32 {
1719 self.inner.to_second().second()
1720 }
1721
1722 /// Converts the given second to a time value. The second should correspond
1723 /// to the number of seconds that have elapsed since `00:00:00`. The
1724 /// fractional second component of the `Time` returned is always `0`.
1725 ///
1726 /// This returns an error when the given `second` is invalid.
1727 #[cfg_attr(feature = "perf-inline", inline(always))]
1728 fn from_second(second: i32) -> Result<Time, Error> {
1729 JTimeSecond::new(second)
1730 .map(|second| second.to_time())
1731 .map(Time::from_jcore)
1732 .map_err(Error::jcore_range)
1733 }
1734
1735 /// Converts this time value to the number of nanoseconds that has elapsed
1736 /// since `00:00:00.000000000`.
1737 ///
1738 /// The maximum possible value that can be returned represents the time
1739 /// `23:59:59.999999999`.
1740 #[inline]
1741 fn to_nanosecond(&self) -> i64 {
1742 self.inner.to_nanosecond().nanosecond()
1743 }
1744
1745 /// Converts the given nanosecond to a time value. The nanosecond should
1746 /// correspond to the number of nanoseconds that have elapsed since
1747 /// `00:00:00.000000000`.
1748 ///
1749 /// This returns an error when the given `nanosecond` is invalid.
1750 #[cfg_attr(feature = "perf-inline", inline(always))]
1751 fn from_nanosecond(nanosecond: i64) -> Result<Time, Error> {
1752 JTimeNanosecond::new(nanosecond)
1753 .map(|nano| nano.to_time())
1754 .map(Time::from_jcore)
1755 .map_err(Error::jcore_range)
1756 }
1757
1758 #[inline]
1759 pub(crate) const fn to_jcore(self) -> JTime {
1760 self.inner
1761 }
1762
1763 #[inline]
1764 pub(crate) const fn from_jcore(time: JTime) -> Time {
1765 Time { inner: time }
1766 }
1767}
1768
1769impl Default for Time {
1770 #[inline]
1771 fn default() -> Time {
1772 Time::midnight()
1773 }
1774}
1775
1776/// Converts a `Time` into a human readable time string.
1777///
1778/// (This `Debug` representation currently emits the same string as the
1779/// `Display` representation, but this is not a guarantee.)
1780///
1781/// Options currently supported:
1782///
1783/// * [`std::fmt::Formatter::precision`] can be set to control the precision
1784/// of the fractional second component.
1785///
1786/// # Example
1787///
1788/// ```
1789/// use jiff::civil::time;
1790///
1791/// let t = time(7, 0, 0, 123_000_000);
1792/// assert_eq!(format!("{t:.6?}"), "07:00:00.123000");
1793/// // Precision values greater than 9 are clamped to 9.
1794/// assert_eq!(format!("{t:.300?}"), "07:00:00.123000000");
1795/// // A precision of 0 implies the entire fractional
1796/// // component is always truncated.
1797/// assert_eq!(format!("{t:.0?}"), "07:00:00");
1798///
1799/// # Ok::<(), Box<dyn std::error::Error>>(())
1800/// ```
1801impl core::fmt::Debug for Time {
1802 #[inline]
1803 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1804 core::fmt::Display::fmt(self, f)
1805 }
1806}
1807
1808/// Converts a `Time` into an ISO 8601 compliant string.
1809///
1810/// # Formatting options supported
1811///
1812/// * [`std::fmt::Formatter::precision`] can be set to control the precision
1813/// of the fractional second component. When not set, the minimum precision
1814/// required to losslessly render the value is used.
1815///
1816/// # Example
1817///
1818/// ```
1819/// use jiff::civil::time;
1820///
1821/// // No fractional seconds:
1822/// let t = time(7, 0, 0, 0);
1823/// assert_eq!(format!("{t}"), "07:00:00");
1824///
1825/// // With fractional seconds:
1826/// let t = time(7, 0, 0, 123_000_000);
1827/// assert_eq!(format!("{t}"), "07:00:00.123");
1828///
1829/// # Ok::<(), Box<dyn std::error::Error>>(())
1830/// ```
1831///
1832/// # Example: setting the precision
1833///
1834/// ```
1835/// use jiff::civil::time;
1836///
1837/// let t = time(7, 0, 0, 123_000_000);
1838/// assert_eq!(format!("{t:.6}"), "07:00:00.123000");
1839/// // Precision values greater than 9 are clamped to 9.
1840/// assert_eq!(format!("{t:.300}"), "07:00:00.123000000");
1841/// // A precision of 0 implies the entire fractional
1842/// // component is always truncated.
1843/// assert_eq!(format!("{t:.0}"), "07:00:00");
1844///
1845/// # Ok::<(), Box<dyn std::error::Error>>(())
1846/// ```
1847impl core::fmt::Display for Time {
1848 #[inline]
1849 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1850 use crate::fmt::StdFmtWrite;
1851
1852 let precision =
1853 f.precision().map(|p| u8::try_from(p).unwrap_or(u8::MAX));
1854 temporal::DateTimePrinter::new()
1855 .precision(precision)
1856 .print_time(self, StdFmtWrite(f))
1857 .map_err(|_| core::fmt::Error)
1858 }
1859}
1860
1861impl core::str::FromStr for Time {
1862 type Err = Error;
1863
1864 #[inline]
1865 fn from_str(string: &str) -> Result<Time, Error> {
1866 DEFAULT_DATETIME_PARSER.parse_time(string)
1867 }
1868}
1869
1870/// Adds a span of time. This uses wrapping arithmetic.
1871///
1872/// For checked arithmetic, see [`Time::checked_add`].
1873impl core::ops::Add<Span> for Time {
1874 type Output = Time;
1875
1876 #[inline]
1877 fn add(self, rhs: Span) -> Time {
1878 self.wrapping_add(rhs)
1879 }
1880}
1881
1882/// Adds a span of time in place. This uses wrapping arithmetic.
1883///
1884/// For checked arithmetic, see [`Time::checked_add`].
1885impl core::ops::AddAssign<Span> for Time {
1886 #[inline]
1887 fn add_assign(&mut self, rhs: Span) {
1888 *self = *self + rhs;
1889 }
1890}
1891
1892/// Subtracts a span of time. This uses wrapping arithmetic.
1893///
1894/// For checked arithmetic, see [`Time::checked_sub`].
1895impl core::ops::Sub<Span> for Time {
1896 type Output = Time;
1897
1898 #[inline]
1899 fn sub(self, rhs: Span) -> Time {
1900 self.wrapping_sub(rhs)
1901 }
1902}
1903
1904/// Subtracts a span of time in place. This uses wrapping arithmetic.
1905///
1906/// For checked arithmetic, see [`Time::checked_sub`].
1907impl core::ops::SubAssign<Span> for Time {
1908 #[inline]
1909 fn sub_assign(&mut self, rhs: Span) {
1910 *self = *self - rhs;
1911 }
1912}
1913
1914/// Computes the span of time between two times.
1915///
1916/// This will return a negative span when the time being subtracted is greater.
1917///
1918/// Since this uses the default configuration for calculating a span between
1919/// two times (no rounding and largest units is hours), this will never panic
1920/// or fail in any way.
1921///
1922/// To configure the largest unit or enable rounding, use [`Time::since`].
1923impl core::ops::Sub for Time {
1924 type Output = Span;
1925
1926 #[inline]
1927 fn sub(self, rhs: Time) -> Span {
1928 self.since(rhs).expect("since never fails when given Time")
1929 }
1930}
1931
1932/// Adds a signed duration of time. This uses wrapping arithmetic.
1933///
1934/// For checked arithmetic, see [`Time::checked_add`].
1935impl core::ops::Add<SignedDuration> for Time {
1936 type Output = Time;
1937
1938 #[inline]
1939 fn add(self, rhs: SignedDuration) -> Time {
1940 self.wrapping_add(rhs)
1941 }
1942}
1943
1944/// Adds a signed duration of time in place. This uses wrapping arithmetic.
1945///
1946/// For checked arithmetic, see [`Time::checked_add`].
1947impl core::ops::AddAssign<SignedDuration> for Time {
1948 #[inline]
1949 fn add_assign(&mut self, rhs: SignedDuration) {
1950 *self = *self + rhs;
1951 }
1952}
1953
1954/// Subtracts a signed duration of time. This uses wrapping arithmetic.
1955///
1956/// For checked arithmetic, see [`Time::checked_sub`].
1957impl core::ops::Sub<SignedDuration> for Time {
1958 type Output = Time;
1959
1960 #[inline]
1961 fn sub(self, rhs: SignedDuration) -> Time {
1962 self.wrapping_sub(rhs)
1963 }
1964}
1965
1966/// Subtracts a signed duration of time in place. This uses wrapping arithmetic.
1967///
1968/// For checked arithmetic, see [`Time::checked_sub`].
1969impl core::ops::SubAssign<SignedDuration> for Time {
1970 #[inline]
1971 fn sub_assign(&mut self, rhs: SignedDuration) {
1972 *self = *self - rhs;
1973 }
1974}
1975
1976/// Adds an unsigned duration of time. This uses wrapping arithmetic.
1977///
1978/// For checked arithmetic, see [`Time::checked_add`].
1979impl core::ops::Add<UnsignedDuration> for Time {
1980 type Output = Time;
1981
1982 #[inline]
1983 fn add(self, rhs: UnsignedDuration) -> Time {
1984 self.wrapping_add(rhs)
1985 }
1986}
1987
1988/// Adds an unsigned duration of time in place. This uses wrapping arithmetic.
1989///
1990/// For checked arithmetic, see [`Time::checked_add`].
1991impl core::ops::AddAssign<UnsignedDuration> for Time {
1992 #[inline]
1993 fn add_assign(&mut self, rhs: UnsignedDuration) {
1994 *self = *self + rhs;
1995 }
1996}
1997
1998/// Subtracts an unsigned duration of time. This uses wrapping arithmetic.
1999///
2000/// For checked arithmetic, see [`Time::checked_sub`].
2001impl core::ops::Sub<UnsignedDuration> for Time {
2002 type Output = Time;
2003
2004 #[inline]
2005 fn sub(self, rhs: UnsignedDuration) -> Time {
2006 self.wrapping_sub(rhs)
2007 }
2008}
2009
2010/// Subtracts an unsigned duration of time in place. This uses wrapping
2011/// arithmetic.
2012///
2013/// For checked arithmetic, see [`Time::checked_sub`].
2014impl core::ops::SubAssign<UnsignedDuration> for Time {
2015 #[inline]
2016 fn sub_assign(&mut self, rhs: UnsignedDuration) {
2017 *self = *self - rhs;
2018 }
2019}
2020
2021impl From<DateTime> for Time {
2022 #[inline]
2023 fn from(dt: DateTime) -> Time {
2024 dt.time()
2025 }
2026}
2027
2028impl From<ZonedDateTime> for Time {
2029 #[inline]
2030 fn from(zdt: ZonedDateTime) -> Time {
2031 zdt.datetime().time()
2032 }
2033}
2034
2035impl<'a> From<&'a ZonedDateTime> for Time {
2036 #[inline]
2037 fn from(zdt: &'a ZonedDateTime) -> Time {
2038 zdt.datetime().time()
2039 }
2040}
2041
2042#[cfg(feature = "defmt")]
2043impl defmt::Format for Time {
2044 fn format(&self, f: defmt::Formatter) {
2045 use crate::fmt::{DefmtWrite, temporal::DEFAULT_DATETIME_PRINTER};
2046
2047 defmt::unwrap!(
2048 DEFAULT_DATETIME_PRINTER.print_time(self, DefmtWrite(f))
2049 );
2050 }
2051}
2052
2053#[cfg(feature = "serde")]
2054impl serde_core::Serialize for Time {
2055 #[inline]
2056 fn serialize<S: serde_core::Serializer>(
2057 &self,
2058 serializer: S,
2059 ) -> Result<S::Ok, S::Error> {
2060 serializer.collect_str(self)
2061 }
2062}
2063
2064#[cfg(feature = "serde")]
2065impl<'de> serde_core::Deserialize<'de> for Time {
2066 #[inline]
2067 fn deserialize<D: serde_core::Deserializer<'de>>(
2068 deserializer: D,
2069 ) -> Result<Time, D::Error> {
2070 use serde_core::de;
2071
2072 struct TimeVisitor;
2073
2074 impl<'de> de::Visitor<'de> for TimeVisitor {
2075 type Value = Time;
2076
2077 fn expecting(
2078 &self,
2079 f: &mut core::fmt::Formatter,
2080 ) -> core::fmt::Result {
2081 f.write_str("a time string")
2082 }
2083
2084 #[inline]
2085 fn visit_bytes<E: de::Error>(
2086 self,
2087 value: &[u8],
2088 ) -> Result<Time, E> {
2089 DEFAULT_DATETIME_PARSER
2090 .parse_time(value)
2091 .map_err(de::Error::custom)
2092 }
2093
2094 #[inline]
2095 fn visit_str<E: de::Error>(self, value: &str) -> Result<Time, E> {
2096 self.visit_bytes(value.as_bytes())
2097 }
2098 }
2099
2100 deserializer.deserialize_str(TimeVisitor)
2101 }
2102}
2103
2104#[cfg(test)]
2105impl quickcheck::Arbitrary for Time {
2106 fn arbitrary(g: &mut quickcheck::Gen) -> Time {
2107 let hour = b::Hour::arbitrary(g);
2108 let minute = b::Minute::arbitrary(g);
2109 let second = b::Second::arbitrary(g);
2110 let subsec_nanosecond = b::SubsecNanosecond::arbitrary(g);
2111 Time::new(hour, minute, second, subsec_nanosecond).unwrap()
2112 }
2113
2114 fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Time>> {
2115 alloc::boxed::Box::new(
2116 (
2117 self.hour(),
2118 self.minute(),
2119 self.second(),
2120 self.subsec_nanosecond(),
2121 )
2122 .shrink()
2123 .filter_map(
2124 |(hour, minute, second, subsec_nanosecond)| {
2125 Time::new(hour, minute, second, subsec_nanosecond).ok()
2126 },
2127 ),
2128 )
2129 }
2130}
2131
2132/// An iterator over periodic times, created by [`Time::series`].
2133///
2134/// It is exhausted when the next value would exceed the limits of a [`Span`]
2135/// or [`Time`] value.
2136///
2137/// This iterator is created by [`Time::series`].
2138#[derive(Clone, Debug)]
2139pub struct TimeSeries {
2140 start: Time,
2141 period: Span,
2142 step: i64,
2143}
2144
2145impl Iterator for TimeSeries {
2146 type Item = Time;
2147
2148 #[inline]
2149 fn next(&mut self) -> Option<Time> {
2150 let span = self.period.checked_mul(self.step).ok()?;
2151 self.step = self.step.checked_add(1)?;
2152 let time = self.start.checked_add(span).ok()?;
2153 Some(time)
2154 }
2155}
2156
2157impl core::iter::FusedIterator for TimeSeries {}
2158
2159/// Options for [`Time::checked_add`] and [`Time::checked_sub`].
2160///
2161/// This type provides a way to ergonomically add one of a few different
2162/// duration types to a [`Time`].
2163///
2164/// The main way to construct values of this type is with its `From` trait
2165/// implementations:
2166///
2167/// * `From<Span> for TimeArithmetic` adds (or subtracts) the given span to the
2168/// receiver time.
2169/// * `From<SignedDuration> for TimeArithmetic` adds (or subtracts)
2170/// the given signed duration to the receiver time.
2171/// * `From<std::time::Duration> for TimeArithmetic` adds (or subtracts)
2172/// the given unsigned duration to the receiver time.
2173///
2174/// # Example
2175///
2176/// ```
2177/// use std::time::Duration;
2178///
2179/// use jiff::{civil::time, SignedDuration, ToSpan};
2180///
2181/// let t = time(0, 0, 0, 0);
2182/// assert_eq!(t.checked_add(2.hours())?, time(2, 0, 0, 0));
2183/// assert_eq!(t.checked_add(SignedDuration::from_hours(2))?, time(2, 0, 0, 0));
2184/// assert_eq!(t.checked_add(Duration::from_secs(2 * 60 * 60))?, time(2, 0, 0, 0));
2185///
2186/// # Ok::<(), Box<dyn std::error::Error>>(())
2187/// ```
2188#[derive(Clone, Copy, Debug)]
2189pub struct TimeArithmetic {
2190 duration: Duration,
2191}
2192
2193impl TimeArithmetic {
2194 #[inline]
2195 fn wrapping_add(self, time: Time) -> Time {
2196 match self.duration {
2197 Duration::Span(span) => time.wrapping_add_span(span),
2198 Duration::Signed(sdur) => time.wrapping_add_signed_duration(sdur),
2199 Duration::Unsigned(udur) => {
2200 time.wrapping_add_unsigned_duration(udur)
2201 }
2202 }
2203 }
2204
2205 #[inline]
2206 fn wrapping_sub(self, time: Time) -> Time {
2207 match self.duration {
2208 Duration::Span(span) => time.wrapping_add_span(span.negate()),
2209 Duration::Signed(sdur) => {
2210 if let Some(sdur) = sdur.checked_neg() {
2211 time.wrapping_add_signed_duration(sdur)
2212 } else {
2213 let udur = UnsignedDuration::new(
2214 i64::MIN.unsigned_abs(),
2215 sdur.subsec_nanos().unsigned_abs(),
2216 );
2217 time.wrapping_add_unsigned_duration(udur)
2218 }
2219 }
2220 Duration::Unsigned(udur) => {
2221 time.wrapping_sub_unsigned_duration(udur)
2222 }
2223 }
2224 }
2225
2226 #[inline]
2227 fn checked_add(self, time: Time) -> Result<Time, Error> {
2228 match self.duration.to_signed()? {
2229 SDuration::Span(span) => time.checked_add_span(span),
2230 SDuration::Absolute(sdur) => time.checked_add_duration(sdur),
2231 }
2232 }
2233
2234 #[inline]
2235 fn checked_neg(self) -> Result<TimeArithmetic, Error> {
2236 let duration = self.duration.checked_neg()?;
2237 Ok(TimeArithmetic { duration })
2238 }
2239
2240 #[inline]
2241 fn is_negative(&self) -> bool {
2242 self.duration.is_negative()
2243 }
2244}
2245
2246impl From<Span> for TimeArithmetic {
2247 fn from(span: Span) -> TimeArithmetic {
2248 let duration = Duration::from(span);
2249 TimeArithmetic { duration }
2250 }
2251}
2252
2253impl From<SignedDuration> for TimeArithmetic {
2254 fn from(sdur: SignedDuration) -> TimeArithmetic {
2255 let duration = Duration::from(sdur);
2256 TimeArithmetic { duration }
2257 }
2258}
2259
2260impl From<UnsignedDuration> for TimeArithmetic {
2261 fn from(udur: UnsignedDuration) -> TimeArithmetic {
2262 let duration = Duration::from(udur);
2263 TimeArithmetic { duration }
2264 }
2265}
2266
2267impl<'a> From<&'a Span> for TimeArithmetic {
2268 fn from(span: &'a Span) -> TimeArithmetic {
2269 TimeArithmetic::from(*span)
2270 }
2271}
2272
2273impl<'a> From<&'a SignedDuration> for TimeArithmetic {
2274 fn from(sdur: &'a SignedDuration) -> TimeArithmetic {
2275 TimeArithmetic::from(*sdur)
2276 }
2277}
2278
2279impl<'a> From<&'a UnsignedDuration> for TimeArithmetic {
2280 fn from(udur: &'a UnsignedDuration) -> TimeArithmetic {
2281 TimeArithmetic::from(*udur)
2282 }
2283}
2284
2285/// Options for [`Time::since`] and [`Time::until`].
2286///
2287/// This type provides a way to configure the calculation of spans between two
2288/// [`Time`] values. In particular, both `Time::since` and `Time::until` accept
2289/// anything that implements `Into<TimeDifference>`. There are a few key trait
2290/// implementations that make this convenient:
2291///
2292/// * `From<Time> for TimeDifference` will construct a configuration consisting
2293/// of just the time. So for example, `time1.until(time2)` will return the span
2294/// from `time1` to `time2`.
2295/// * `From<DateTime> for TimeDifference` will construct a configuration
2296/// consisting of just the time from the given datetime. So for example,
2297/// `time.since(datetime)` returns the span from `datetime.time()` to `time`.
2298/// * `From<(Unit, Time)>` is a convenient way to specify the largest units
2299/// that should be present on the span returned. By default, the largest units
2300/// are hours. Using this trait implementation is equivalent to
2301/// `TimeDifference::new(time).largest(unit)`.
2302/// * `From<(Unit, DateTime)>` is like the one above, but with the time from
2303/// the given datetime.
2304///
2305/// One can also provide a `TimeDifference` value directly. Doing so
2306/// is necessary to use the rounding features of calculating a span. For
2307/// example, setting the smallest unit (defaults to [`Unit::Nanosecond`]), the
2308/// rounding mode (defaults to [`RoundMode::Trunc`]) and the rounding increment
2309/// (defaults to `1`). The defaults are selected such that no rounding occurs.
2310///
2311/// Rounding a span as part of calculating it is provided as a convenience.
2312/// Callers may choose to round the span as a distinct step via
2313/// [`Span::round`].
2314///
2315/// # Example
2316///
2317/// This example shows how to round a span between two datetimes to the nearest
2318/// half-hour, with ties breaking away from zero.
2319///
2320/// ```
2321/// use jiff::{civil::{Time, TimeDifference}, RoundMode, ToSpan, Unit};
2322///
2323/// let t1 = "08:14:00.123456789".parse::<Time>()?;
2324/// let t2 = "15:00".parse::<Time>()?;
2325/// let span = t1.until(
2326/// TimeDifference::new(t2)
2327/// .smallest(Unit::Minute)
2328/// .mode(RoundMode::HalfExpand)
2329/// .increment(30),
2330/// )?;
2331/// assert_eq!(span, 7.hours().fieldwise());
2332///
2333/// // One less minute, and because of the HalfExpand mode, the span would
2334/// // get rounded down.
2335/// let t2 = "14:59".parse::<Time>()?;
2336/// let span = t1.until(
2337/// TimeDifference::new(t2)
2338/// .smallest(Unit::Minute)
2339/// .mode(RoundMode::HalfExpand)
2340/// .increment(30),
2341/// )?;
2342/// assert_eq!(span, 6.hours().minutes(30).fieldwise());
2343///
2344/// # Ok::<(), Box<dyn std::error::Error>>(())
2345/// ```
2346#[derive(Clone, Copy, Debug)]
2347pub struct TimeDifference {
2348 time: Time,
2349 round: SpanRound<'static>,
2350}
2351
2352impl TimeDifference {
2353 /// Create a new default configuration for computing the span between
2354 /// the given time and some other time (specified as the receiver in
2355 /// [`Time::since`] or [`Time::until`]).
2356 #[inline]
2357 pub fn new(time: Time) -> TimeDifference {
2358 // We use truncation rounding by default since it seems that's
2359 // what is generally expected when computing the difference between
2360 // datetimes.
2361 //
2362 // See: https://github.com/tc39/proposal-temporal/issues/1122
2363 let round = SpanRound::new().mode(RoundMode::Trunc);
2364 TimeDifference { time, round }
2365 }
2366
2367 /// Set the smallest units allowed in the span returned.
2368 ///
2369 /// # Errors
2370 ///
2371 /// The smallest units must be no greater than the largest units. If this
2372 /// is violated, then computing a span with this configuration will result
2373 /// in an error.
2374 ///
2375 /// The smallest unit must be no bigger than `Unit::Hour`.
2376 ///
2377 /// # Example
2378 ///
2379 /// This shows how to round a span between two times to units no less than
2380 /// seconds.
2381 ///
2382 /// ```
2383 /// use jiff::{civil::{Time, TimeDifference}, RoundMode, ToSpan, Unit};
2384 ///
2385 /// let t1 = "08:14:02.5001".parse::<Time>()?;
2386 /// let t2 = "08:30:03.0001".parse::<Time>()?;
2387 /// let span = t1.until(
2388 /// TimeDifference::new(t2)
2389 /// .smallest(Unit::Second)
2390 /// .mode(RoundMode::HalfExpand),
2391 /// )?;
2392 /// assert_eq!(span, 16.minutes().seconds(1).fieldwise());
2393 ///
2394 /// # Ok::<(), Box<dyn std::error::Error>>(())
2395 /// ```
2396 #[inline]
2397 pub fn smallest(self, unit: Unit) -> TimeDifference {
2398 TimeDifference { round: self.round.smallest(unit), ..self }
2399 }
2400
2401 /// Set the largest units allowed in the span returned.
2402 ///
2403 /// When a largest unit is not specified, computing a span between times
2404 /// behaves as if it were set to [`Unit::Hour`].
2405 ///
2406 /// # Errors
2407 ///
2408 /// The largest units, when set, must be at least as big as the smallest
2409 /// units (which defaults to [`Unit::Nanosecond`]). If this is violated,
2410 /// then computing a span with this configuration will result in an error.
2411 ///
2412 /// The largest unit must be no bigger than `Unit::Hour`.
2413 ///
2414 /// # Example
2415 ///
2416 /// This shows how to round a span between two times to units no
2417 /// bigger than seconds.
2418 ///
2419 /// ```
2420 /// use jiff::{civil::{Time, TimeDifference}, ToSpan, Unit};
2421 ///
2422 /// let t1 = "08:14".parse::<Time>()?;
2423 /// let t2 = "08:30".parse::<Time>()?;
2424 /// let span = t1.until(TimeDifference::new(t2).largest(Unit::Second))?;
2425 /// assert_eq!(span, 960.seconds().fieldwise());
2426 ///
2427 /// # Ok::<(), Box<dyn std::error::Error>>(())
2428 /// ```
2429 #[inline]
2430 pub fn largest(self, unit: Unit) -> TimeDifference {
2431 TimeDifference { round: self.round.largest(unit), ..self }
2432 }
2433
2434 /// Set the rounding mode.
2435 ///
2436 /// This defaults to [`RoundMode::Trunc`] since it's plausible that
2437 /// rounding "up" in the context of computing the span between two times
2438 /// could be surprising in a number of cases. The [`RoundMode::HalfExpand`]
2439 /// mode corresponds to typical rounding you might have learned about in
2440 /// school. But a variety of other rounding modes exist.
2441 ///
2442 /// # Example
2443 ///
2444 /// This shows how to always round "up" towards positive infinity.
2445 ///
2446 /// ```
2447 /// use jiff::{civil::{Time, TimeDifference}, RoundMode, ToSpan, Unit};
2448 ///
2449 /// let t1 = "08:10".parse::<Time>()?;
2450 /// let t2 = "08:11".parse::<Time>()?;
2451 /// let span = t1.until(
2452 /// TimeDifference::new(t2)
2453 /// .smallest(Unit::Hour)
2454 /// .mode(RoundMode::Ceil),
2455 /// )?;
2456 /// // Only one minute elapsed, but we asked to always round up!
2457 /// assert_eq!(span, 1.hour().fieldwise());
2458 ///
2459 /// // Since `Ceil` always rounds toward positive infinity, the behavior
2460 /// // flips for a negative span.
2461 /// let span = t1.since(
2462 /// TimeDifference::new(t2)
2463 /// .smallest(Unit::Hour)
2464 /// .mode(RoundMode::Ceil),
2465 /// )?;
2466 /// assert_eq!(span, 0.hour().fieldwise());
2467 ///
2468 /// # Ok::<(), Box<dyn std::error::Error>>(())
2469 /// ```
2470 #[inline]
2471 pub fn mode(self, mode: RoundMode) -> TimeDifference {
2472 TimeDifference { round: self.round.mode(mode), ..self }
2473 }
2474
2475 /// Set the rounding increment for the smallest unit.
2476 ///
2477 /// The default value is `1`. Other values permit rounding the smallest
2478 /// unit to the nearest integer increment specified. For example, if the
2479 /// smallest unit is set to [`Unit::Minute`], then a rounding increment of
2480 /// `30` would result in rounding in increments of a half hour. That is,
2481 /// the only minute value that could result would be `0` or `30`.
2482 ///
2483 /// # Errors
2484 ///
2485 /// The rounding increment must divide evenly into the next highest unit
2486 /// after the smallest unit configured (and must not be equivalent to it).
2487 /// For example, if the smallest unit is [`Unit::Nanosecond`], then *some*
2488 /// of the valid values for the rounding increment are `1`, `2`, `4`, `5`,
2489 /// `100` and `500`. Namely, any integer that divides evenly into `1,000`
2490 /// nanoseconds since there are `1,000` nanoseconds in the next highest
2491 /// unit (microseconds).
2492 ///
2493 /// In all cases, the increment must be greater than zero and less than
2494 /// or equal to `1_000_000_000`.
2495 ///
2496 /// The error will occur when computing the span, and not when setting
2497 /// the increment here.
2498 ///
2499 /// # Example
2500 ///
2501 /// This shows how to round the span between two times to the nearest 5
2502 /// minute increment.
2503 ///
2504 /// ```
2505 /// use jiff::{civil::{Time, TimeDifference}, RoundMode, ToSpan, Unit};
2506 ///
2507 /// let t1 = "08:19".parse::<Time>()?;
2508 /// let t2 = "12:52".parse::<Time>()?;
2509 /// let span = t1.until(
2510 /// TimeDifference::new(t2)
2511 /// .smallest(Unit::Minute)
2512 /// .increment(5)
2513 /// .mode(RoundMode::HalfExpand),
2514 /// )?;
2515 /// assert_eq!(span, 4.hour().minutes(35).fieldwise());
2516 ///
2517 /// # Ok::<(), Box<dyn std::error::Error>>(())
2518 /// ```
2519 #[inline]
2520 pub fn increment(self, increment: i64) -> TimeDifference {
2521 TimeDifference { round: self.round.increment(increment), ..self }
2522 }
2523
2524 /// Returns true if and only if this configuration could change the span
2525 /// via rounding.
2526 #[inline]
2527 fn rounding_may_change_span(&self) -> bool {
2528 self.round.rounding_may_change_span()
2529 }
2530
2531 /// Returns the span of time from `t1` to the time in this configuration.
2532 /// The biggest units allowed are determined by the `smallest` and
2533 /// `largest` settings, but defaults to `Unit::Hour`.
2534 #[inline]
2535 fn until_with_largest_unit(&self, t1: Time) -> Result<Span, Error> {
2536 if self.round.get_smallest() >= Unit::Day {
2537 return Err(Error::from(UnitConfigError::CivilTime {
2538 given: self.round.get_smallest(),
2539 }));
2540 }
2541
2542 let largest = self.round.get_largest().unwrap_or(Unit::Hour);
2543 if largest >= Unit::Day {
2544 return Err(Error::from(UnitConfigError::CivilTime {
2545 given: largest,
2546 }));
2547 }
2548
2549 let t2 = self.time;
2550 if t1 == t2 {
2551 return Ok(Span::new());
2552 }
2553 let start = t1.to_duration();
2554 let end = t2.to_duration();
2555 let span = Span::from_invariant_duration(largest, end - start)
2556 .expect("difference in civil times is always in bounds");
2557 Ok(span)
2558 }
2559}
2560
2561impl From<Time> for TimeDifference {
2562 #[inline]
2563 fn from(time: Time) -> TimeDifference {
2564 TimeDifference::new(time)
2565 }
2566}
2567
2568impl From<DateTime> for TimeDifference {
2569 #[inline]
2570 fn from(dt: DateTime) -> TimeDifference {
2571 TimeDifference::from(Time::from(dt))
2572 }
2573}
2574
2575impl From<ZonedDateTime> for TimeDifference {
2576 #[inline]
2577 fn from(zdt: ZonedDateTime) -> TimeDifference {
2578 TimeDifference::from(Time::from(zdt))
2579 }
2580}
2581
2582impl<'a> From<&'a ZonedDateTime> for TimeDifference {
2583 #[inline]
2584 fn from(zdt: &'a ZonedDateTime) -> TimeDifference {
2585 TimeDifference::from(zdt.datetime())
2586 }
2587}
2588
2589impl From<(Unit, Time)> for TimeDifference {
2590 #[inline]
2591 fn from((largest, time): (Unit, Time)) -> TimeDifference {
2592 TimeDifference::from(time).largest(largest)
2593 }
2594}
2595
2596impl From<(Unit, DateTime)> for TimeDifference {
2597 #[inline]
2598 fn from((largest, dt): (Unit, DateTime)) -> TimeDifference {
2599 TimeDifference::from((largest, Time::from(dt)))
2600 }
2601}
2602
2603impl From<(Unit, ZonedDateTime)> for TimeDifference {
2604 #[inline]
2605 fn from((largest, zdt): (Unit, ZonedDateTime)) -> TimeDifference {
2606 TimeDifference::from((largest, Time::from(zdt)))
2607 }
2608}
2609
2610impl<'a> From<(Unit, &'a ZonedDateTime)> for TimeDifference {
2611 #[inline]
2612 fn from((largest, zdt): (Unit, &'a ZonedDateTime)) -> TimeDifference {
2613 TimeDifference::from((largest, zdt.datetime()))
2614 }
2615}
2616
2617/// Options for [`Time::round`].
2618///
2619/// This type provides a way to configure the rounding of a civil time.
2620/// In particular, `Time::round` accepts anything that implements the
2621/// `Into<TimeRound>` trait. There are some trait implementations that
2622/// therefore make calling `Time::round` in some common cases more ergonomic:
2623///
2624/// * `From<Unit> for TimeRound` will construct a rounding configuration that
2625/// rounds to the unit given. Specifically, `TimeRound::new().smallest(unit)`.
2626/// * `From<(Unit, i64)> for TimeRound` is like the one above, but also
2627/// specifies the rounding increment for [`TimeRound::increment`].
2628///
2629/// Note that in the default configuration, no rounding occurs.
2630///
2631/// # Example
2632///
2633/// This example shows how to round a time to the nearest second:
2634///
2635/// ```
2636/// use jiff::{civil::{Time, time}, Unit};
2637///
2638/// let t: Time = "16:24:59.5".parse()?;
2639/// assert_eq!(
2640/// t.round(Unit::Second)?,
2641/// // The second rounds up and causes minutes to increase.
2642/// time(16, 25, 0, 0),
2643/// );
2644///
2645/// # Ok::<(), Box<dyn std::error::Error>>(())
2646/// ```
2647///
2648/// The above makes use of the fact that `Unit` implements
2649/// `Into<TimeRound>`. If you want to change the rounding mode to, say,
2650/// truncation, then you'll need to construct a `TimeRound` explicitly
2651/// since there are no convenience `Into` trait implementations for
2652/// [`RoundMode`].
2653///
2654/// ```
2655/// use jiff::{civil::{Time, TimeRound, time}, RoundMode, Unit};
2656///
2657/// let t: Time = "2024-06-20 16:24:59.5".parse()?;
2658/// assert_eq!(
2659/// t.round(
2660/// TimeRound::new().smallest(Unit::Second).mode(RoundMode::Trunc),
2661/// )?,
2662/// // The second just gets truncated as if it wasn't there.
2663/// time(16, 24, 59, 0),
2664/// );
2665///
2666/// # Ok::<(), Box<dyn std::error::Error>>(())
2667/// ```
2668#[derive(Clone, Copy, Debug)]
2669pub struct TimeRound {
2670 smallest: Unit,
2671 mode: RoundMode,
2672 increment: i64,
2673}
2674
2675impl TimeRound {
2676 /// Create a new default configuration for rounding a [`Time`].
2677 #[inline]
2678 pub fn new() -> TimeRound {
2679 TimeRound {
2680 smallest: Unit::Nanosecond,
2681 mode: RoundMode::HalfExpand,
2682 increment: 1,
2683 }
2684 }
2685
2686 /// Set the smallest units allowed in the time returned after rounding.
2687 ///
2688 /// Any units below the smallest configured unit will be used, along with
2689 /// the rounding increment and rounding mode, to determine the value of the
2690 /// smallest unit. For example, when rounding `03:25:30` to the
2691 /// nearest minute, the `30` second unit will result in rounding the minute
2692 /// unit of `25` up to `26` and zeroing out everything below minutes.
2693 ///
2694 /// This defaults to [`Unit::Nanosecond`].
2695 ///
2696 /// # Errors
2697 ///
2698 /// The smallest units must be no greater than [`Unit::Hour`].
2699 ///
2700 /// # Example
2701 ///
2702 /// ```
2703 /// use jiff::{civil::{TimeRound, time}, Unit};
2704 ///
2705 /// let t = time(3, 25, 30, 0);
2706 /// assert_eq!(
2707 /// t.round(TimeRound::new().smallest(Unit::Minute))?,
2708 /// time(3, 26, 0, 0),
2709 /// );
2710 /// // Or, utilize the `From<Unit> for TimeRound` impl:
2711 /// assert_eq!(t.round(Unit::Minute)?, time(3, 26, 0, 0));
2712 ///
2713 /// # Ok::<(), Box<dyn std::error::Error>>(())
2714 /// ```
2715 #[inline]
2716 pub fn smallest(self, unit: Unit) -> TimeRound {
2717 TimeRound { smallest: unit, ..self }
2718 }
2719
2720 /// Set the rounding mode.
2721 ///
2722 /// This defaults to [`RoundMode::HalfExpand`], which rounds away from
2723 /// zero. It matches the kind of rounding you might have been taught in
2724 /// school.
2725 ///
2726 /// # Example
2727 ///
2728 /// This shows how to always round times up towards positive infinity.
2729 ///
2730 /// ```
2731 /// use jiff::{civil::{Time, TimeRound, time}, RoundMode, Unit};
2732 ///
2733 /// let t: Time = "03:25:01".parse()?;
2734 /// assert_eq!(
2735 /// t.round(
2736 /// TimeRound::new()
2737 /// .smallest(Unit::Minute)
2738 /// .mode(RoundMode::Ceil),
2739 /// )?,
2740 /// time(3, 26, 0, 0),
2741 /// );
2742 ///
2743 /// # Ok::<(), Box<dyn std::error::Error>>(())
2744 /// ```
2745 #[inline]
2746 pub fn mode(self, mode: RoundMode) -> TimeRound {
2747 TimeRound { mode, ..self }
2748 }
2749
2750 /// Set the rounding increment for the smallest unit.
2751 ///
2752 /// The default value is `1`. Other values permit rounding the smallest
2753 /// unit to the nearest integer increment specified. For example, if the
2754 /// smallest unit is set to [`Unit::Minute`], then a rounding increment of
2755 /// `30` would result in rounding in increments of a half hour. That is,
2756 /// the only minute value that could result would be `0` or `30`.
2757 ///
2758 /// # Errors
2759 ///
2760 /// The rounding increment must divide evenly into the
2761 /// next highest unit above the smallest unit set. The rounding increment
2762 /// must also not be equal to the next highest unit. For example, if the
2763 /// smallest unit is [`Unit::Nanosecond`], then *some* of the valid values
2764 /// for the rounding increment are `1`, `2`, `4`, `5`, `100` and `500`.
2765 /// Namely, any integer that divides evenly into `1,000` nanoseconds since
2766 /// there are `1,000` nanoseconds in the next highest unit (microseconds).
2767 ///
2768 /// In all cases, the increment must be greater than zero and less than or
2769 /// equal to `1_000_000_000`.
2770 ///
2771 /// # Example
2772 ///
2773 /// This example shows how to round a time to the nearest 10 minute
2774 /// increment.
2775 ///
2776 /// ```
2777 /// use jiff::{civil::{Time, TimeRound, time}, RoundMode, Unit};
2778 ///
2779 /// let t: Time = "03:24:59".parse()?;
2780 /// assert_eq!(t.round((Unit::Minute, 10))?, time(3, 20, 0, 0));
2781 ///
2782 /// # Ok::<(), Box<dyn std::error::Error>>(())
2783 /// ```
2784 #[inline]
2785 pub fn increment(self, increment: i64) -> TimeRound {
2786 TimeRound { increment, ..self }
2787 }
2788
2789 /// Does the actual rounding.
2790 fn round(&self, t: Time) -> Result<Time, Error> {
2791 let increment = Increment::for_time(self.smallest, self.increment)?;
2792 let rounded = increment.round(self.mode, t.to_duration())?;
2793 if rounded.as_secs() == i64::from(b::CivilDaySecond::MAX + 1) {
2794 return Ok(Time::MIN);
2795 }
2796 // OK because the maximum value for `rounded` is the number of
2797 // nanoseconds in a civil day. In which case, that wraps around to
2798 // `Time::MIN` and we handle that case above. `rounded` can't be any
2799 // bigger because of the requirement that the rounding increment divide
2800 // evenly into the next biggest unit (and thus all such increments must
2801 // divide evenly into a single civil day).
2802 Ok(Time::from_duration(rounded).unwrap())
2803 }
2804}
2805
2806impl Default for TimeRound {
2807 #[inline]
2808 fn default() -> TimeRound {
2809 TimeRound::new()
2810 }
2811}
2812
2813impl From<Unit> for TimeRound {
2814 #[inline]
2815 fn from(unit: Unit) -> TimeRound {
2816 TimeRound::default().smallest(unit)
2817 }
2818}
2819
2820impl From<(Unit, i64)> for TimeRound {
2821 #[inline]
2822 fn from((unit, increment): (Unit, i64)) -> TimeRound {
2823 TimeRound::from(unit).increment(increment)
2824 }
2825}
2826
2827/// A builder for setting the fields on a [`Time`].
2828///
2829/// This builder is constructed via [`Time::with`].
2830///
2831/// # Example
2832///
2833/// Unlike [`Date`], a [`Time`] is valid for all possible valid values of its
2834/// fields. That is, there is no way for two valid field values to combine
2835/// into an invalid `Time`. So, for `Time`, this builder does have as much of
2836/// a benefit versus an API design with methods like `Time::with_hour` and
2837/// `Time::with_minute`. Nevertheless, this builder permits settings multiple
2838/// fields at the same time and performing only one validity check. Moreover,
2839/// this provides a consistent API with other date and time types in this
2840/// crate.
2841///
2842/// ```
2843/// use jiff::civil::time;
2844///
2845/// let t1 = time(0, 0, 24, 0);
2846/// let t2 = t1.with().hour(15).minute(30).millisecond(10).build()?;
2847/// assert_eq!(t2, time(15, 30, 24, 10_000_000));
2848///
2849/// # Ok::<(), Box<dyn std::error::Error>>(())
2850/// ```
2851#[derive(Clone, Copy, Debug)]
2852pub struct TimeWith {
2853 original: Time,
2854 hour: Option<i8>,
2855 minute: Option<i8>,
2856 second: Option<i8>,
2857 millisecond: Option<i16>,
2858 microsecond: Option<i16>,
2859 nanosecond: Option<i16>,
2860 subsec_nanosecond: Option<i32>,
2861}
2862
2863impl TimeWith {
2864 #[inline]
2865 fn new(original: Time) -> TimeWith {
2866 TimeWith {
2867 original,
2868 hour: None,
2869 minute: None,
2870 second: None,
2871 millisecond: None,
2872 microsecond: None,
2873 nanosecond: None,
2874 subsec_nanosecond: None,
2875 }
2876 }
2877
2878 /// Create a new `Time` from the fields set on this configuration.
2879 ///
2880 /// An error occurs when the fields combine to an invalid time. This only
2881 /// occurs when at least one field has an invalid value, or if at least
2882 /// one of `millisecond`, `microsecond` or `nanosecond` is set _and_
2883 /// `subsec_nanosecond` is set. Otherwise, if all fields are valid, then
2884 /// the entire `Time` is guaranteed to be valid.
2885 ///
2886 /// For any fields not set on this configuration, the values are taken from
2887 /// the [`Time`] that originally created this configuration. When no values
2888 /// are set, this routine is guaranteed to succeed and will always return
2889 /// the original time without modification.
2890 ///
2891 /// # Example
2892 ///
2893 /// This creates a time but with its fractional nanosecond component
2894 /// stripped:
2895 ///
2896 /// ```
2897 /// use jiff::civil::time;
2898 ///
2899 /// let t = time(14, 27, 30, 123_456_789);
2900 /// assert_eq!(t.with().subsec_nanosecond(0).build()?, time(14, 27, 30, 0));
2901 ///
2902 /// # Ok::<(), Box<dyn std::error::Error>>(())
2903 /// ```
2904 ///
2905 /// # Example: error for invalid time
2906 ///
2907 /// ```
2908 /// use jiff::civil::time;
2909 ///
2910 /// let t = time(14, 27, 30, 0);
2911 /// assert!(t.with().hour(24).build().is_err());
2912 /// ```
2913 ///
2914 /// # Example: error for ambiguous sub-second value
2915 ///
2916 /// ```
2917 /// use jiff::civil::time;
2918 ///
2919 /// let t = time(14, 27, 30, 123_456_789);
2920 /// // Setting both the individual sub-second fields and the entire
2921 /// // fractional component could lead to a misleading configuration. So
2922 /// // if it's done, it results in an error in all cases. Callers must
2923 /// // choose one or the other.
2924 /// assert!(t.with().microsecond(1).subsec_nanosecond(0).build().is_err());
2925 /// ```
2926 #[inline]
2927 pub fn build(self) -> Result<Time, Error> {
2928 let hour = self.hour.unwrap_or_else(|| self.original.hour());
2929 let minute = self.minute.unwrap_or_else(|| self.original.minute());
2930 let second = self.second.unwrap_or_else(|| self.original.second());
2931 let millisecond =
2932 self.millisecond.unwrap_or_else(|| self.original.millisecond());
2933 let microsecond =
2934 self.microsecond.unwrap_or_else(|| self.original.microsecond());
2935 let nanosecond =
2936 self.nanosecond.unwrap_or_else(|| self.original.nanosecond());
2937 let subsec_nanosecond = match self.subsec_nanosecond {
2938 None => self.original.subsec_nanosecond(),
2939 Some(subsec_nanosecond) => {
2940 if self.millisecond.is_some() {
2941 return Err(Error::from(E::IllegalTimeWithMillisecond));
2942 }
2943 if self.microsecond.is_some() {
2944 return Err(Error::from(E::IllegalTimeWithMicrosecond));
2945 }
2946 if self.nanosecond.is_some() {
2947 return Err(Error::from(E::IllegalTimeWithNanosecond));
2948 }
2949 subsec_nanosecond
2950 }
2951 };
2952 let jtime = if self.subsec_nanosecond.is_some() {
2953 JTime::new(hour, minute, second, subsec_nanosecond)
2954 } else {
2955 JTime::new(hour, minute, second, 0).and_then(|time: JTime| {
2956 time.with_subsec_parts(millisecond, microsecond, nanosecond)
2957 })
2958 };
2959 jtime.map(Time::from_jcore).map_err(Error::jcore_range)
2960 }
2961
2962 /// Set the hour field on a [`Time`].
2963 ///
2964 /// One can access this value via [`Time::hour`].
2965 ///
2966 /// This overrides any previous hour settings.
2967 ///
2968 /// # Errors
2969 ///
2970 /// This returns an error when [`TimeWith::build`] is called if the given
2971 /// hour is outside the range `0..=23`.
2972 ///
2973 /// # Example
2974 ///
2975 /// ```
2976 /// use jiff::civil::time;
2977 ///
2978 /// let t1 = time(15, 21, 59, 0);
2979 /// assert_eq!(t1.hour(), 15);
2980 /// let t2 = t1.with().hour(3).build()?;
2981 /// assert_eq!(t2.hour(), 3);
2982 ///
2983 /// # Ok::<(), Box<dyn std::error::Error>>(())
2984 /// ```
2985 #[inline]
2986 pub fn hour(self, hour: i8) -> TimeWith {
2987 TimeWith { hour: Some(hour), ..self }
2988 }
2989
2990 /// Set the minute field on a [`Time`].
2991 ///
2992 /// One can access this value via [`Time::minute`].
2993 ///
2994 /// This overrides any previous minute settings.
2995 ///
2996 /// # Errors
2997 ///
2998 /// This returns an error when [`TimeWith::build`] is called if the given
2999 /// minute is outside the range `0..=59`.
3000 ///
3001 /// # Example
3002 ///
3003 /// ```
3004 /// use jiff::civil::time;
3005 ///
3006 /// let t1 = time(15, 21, 59, 0);
3007 /// assert_eq!(t1.minute(), 21);
3008 /// let t2 = t1.with().minute(3).build()?;
3009 /// assert_eq!(t2.minute(), 3);
3010 ///
3011 /// # Ok::<(), Box<dyn std::error::Error>>(())
3012 /// ```
3013 #[inline]
3014 pub fn minute(self, minute: i8) -> TimeWith {
3015 TimeWith { minute: Some(minute), ..self }
3016 }
3017
3018 /// Set the second field on a [`Time`].
3019 ///
3020 /// One can access this value via [`Time::second`].
3021 ///
3022 /// This overrides any previous second settings.
3023 ///
3024 /// # Errors
3025 ///
3026 /// This returns an error when [`TimeWith::build`] is called if the given
3027 /// second is outside the range `0..=59`.
3028 ///
3029 /// # Example
3030 ///
3031 /// ```
3032 /// use jiff::civil::time;
3033 ///
3034 /// let t1 = time(15, 21, 59, 0);
3035 /// assert_eq!(t1.second(), 59);
3036 /// let t2 = t1.with().second(3).build()?;
3037 /// assert_eq!(t2.second(), 3);
3038 ///
3039 /// # Ok::<(), Box<dyn std::error::Error>>(())
3040 /// ```
3041 #[inline]
3042 pub fn second(self, second: i8) -> TimeWith {
3043 TimeWith { second: Some(second), ..self }
3044 }
3045
3046 /// Set the millisecond field on a [`Time`].
3047 ///
3048 /// One can access this value via [`Time::millisecond`].
3049 ///
3050 /// This overrides any previous millisecond settings.
3051 ///
3052 /// Note that this only sets the millisecond component. It does
3053 /// not change the microsecond or nanosecond components. To set
3054 /// the fractional second component to nanosecond precision, use
3055 /// [`TimeWith::subsec_nanosecond`].
3056 ///
3057 /// # Errors
3058 ///
3059 /// This returns an error when [`TimeWith::build`] is called if the given
3060 /// millisecond is outside the range `0..=999`, or if both this and
3061 /// [`TimeWith::subsec_nanosecond`] are set.
3062 ///
3063 /// # Example
3064 ///
3065 /// This shows the relationship between [`Time::millisecond`] and
3066 /// [`Time::subsec_nanosecond`]:
3067 ///
3068 /// ```
3069 /// use jiff::civil::time;
3070 ///
3071 /// let t = time(15, 21, 35, 0).with().millisecond(123).build()?;
3072 /// assert_eq!(t.subsec_nanosecond(), 123_000_000);
3073 ///
3074 /// # Ok::<(), Box<dyn std::error::Error>>(())
3075 /// ```
3076 #[inline]
3077 pub fn millisecond(self, millisecond: i16) -> TimeWith {
3078 TimeWith { millisecond: Some(millisecond), ..self }
3079 }
3080
3081 /// Set the microsecond field on a [`Time`].
3082 ///
3083 /// One can access this value via [`Time::microsecond`].
3084 ///
3085 /// This overrides any previous microsecond settings.
3086 ///
3087 /// Note that this only sets the microsecond component. It does
3088 /// not change the millisecond or nanosecond components. To set
3089 /// the fractional second component to nanosecond precision, use
3090 /// [`TimeWith::subsec_nanosecond`].
3091 ///
3092 /// # Errors
3093 ///
3094 /// This returns an error when [`TimeWith::build`] is called if the given
3095 /// microsecond is outside the range `0..=999`, or if both this and
3096 /// [`TimeWith::subsec_nanosecond`] are set.
3097 ///
3098 /// # Example
3099 ///
3100 /// This shows the relationship between [`Time::microsecond`] and
3101 /// [`Time::subsec_nanosecond`]:
3102 ///
3103 /// ```
3104 /// use jiff::civil::time;
3105 ///
3106 /// let t = time(15, 21, 35, 0).with().microsecond(123).build()?;
3107 /// assert_eq!(t.subsec_nanosecond(), 123_000);
3108 ///
3109 /// # Ok::<(), Box<dyn std::error::Error>>(())
3110 /// ```
3111 #[inline]
3112 pub fn microsecond(self, microsecond: i16) -> TimeWith {
3113 TimeWith { microsecond: Some(microsecond), ..self }
3114 }
3115
3116 /// Set the nanosecond field on a [`Time`].
3117 ///
3118 /// One can access this value via [`Time::nanosecond`].
3119 ///
3120 /// This overrides any previous nanosecond settings.
3121 ///
3122 /// Note that this only sets the nanosecond component. It does
3123 /// not change the millisecond or microsecond components. To set
3124 /// the fractional second component to nanosecond precision, use
3125 /// [`TimeWith::subsec_nanosecond`].
3126 ///
3127 /// # Errors
3128 ///
3129 /// This returns an error when [`TimeWith::build`] is called if the given
3130 /// nanosecond is outside the range `0..=999`, or if both this and
3131 /// [`TimeWith::subsec_nanosecond`] are set.
3132 ///
3133 /// # Example
3134 ///
3135 /// This shows the relationship between [`Time::nanosecond`] and
3136 /// [`Time::subsec_nanosecond`]:
3137 ///
3138 /// ```
3139 /// use jiff::civil::time;
3140 ///
3141 /// let t = time(15, 21, 35, 0).with().nanosecond(123).build()?;
3142 /// assert_eq!(t.subsec_nanosecond(), 123);
3143 ///
3144 /// # Ok::<(), Box<dyn std::error::Error>>(())
3145 /// ```
3146 #[inline]
3147 pub fn nanosecond(self, nanosecond: i16) -> TimeWith {
3148 TimeWith { nanosecond: Some(nanosecond), ..self }
3149 }
3150
3151 /// Set the subsecond nanosecond field on a [`Time`].
3152 ///
3153 /// If you want to access this value on `Time`, then use
3154 /// [`Time::subsec_nanosecond`].
3155 ///
3156 /// This overrides any previous subsecond nanosecond settings.
3157 ///
3158 /// Note that this sets the entire fractional second component to
3159 /// nanosecond precision, and overrides any individual millisecond,
3160 /// microsecond or nanosecond settings. To set individual components,
3161 /// use [`TimeWith::millisecond`], [`TimeWith::microsecond`] or
3162 /// [`TimeWith::nanosecond`].
3163 ///
3164 /// # Errors
3165 ///
3166 /// This returns an error when [`TimeWith::build`] is called if the given
3167 /// subsecond nanosecond is outside the range `0..=999,999,999`, or if both
3168 /// this and one of [`TimeWith::millisecond`], [`TimeWith::microsecond`] or
3169 /// [`TimeWith::nanosecond`] are set.
3170 ///
3171 /// # Example
3172 ///
3173 /// This shows the relationship between constructing a `Time` value with
3174 /// subsecond nanoseconds and its individual subsecond fields:
3175 ///
3176 /// ```
3177 /// use jiff::civil::time;
3178 ///
3179 /// let t1 = time(15, 21, 35, 0);
3180 /// let t2 = t1.with().subsec_nanosecond(123_456_789).build()?;
3181 /// assert_eq!(t2.millisecond(), 123);
3182 /// assert_eq!(t2.microsecond(), 456);
3183 /// assert_eq!(t2.nanosecond(), 789);
3184 ///
3185 /// # Ok::<(), Box<dyn std::error::Error>>(())
3186 /// ```
3187 #[inline]
3188 pub fn subsec_nanosecond(self, subsec_nanosecond: i32) -> TimeWith {
3189 TimeWith { subsec_nanosecond: Some(subsec_nanosecond), ..self }
3190 }
3191}
3192
3193#[cfg(test)]
3194mod tests {
3195 use std::io::Cursor;
3196
3197 use crate::{ToSpan, civil::time, span::span_eq};
3198
3199 use super::*;
3200
3201 #[test]
3202 fn min() {
3203 let t = Time::MIN;
3204 assert_eq!(t.hour(), 0);
3205 assert_eq!(t.minute(), 0);
3206 assert_eq!(t.second(), 0);
3207 assert_eq!(t.subsec_nanosecond(), 0);
3208 }
3209
3210 #[test]
3211 fn max() {
3212 let t = Time::MAX;
3213 assert_eq!(t.hour(), 23);
3214 assert_eq!(t.minute(), 59);
3215 assert_eq!(t.second(), 59);
3216 assert_eq!(t.subsec_nanosecond(), 999_999_999);
3217 }
3218
3219 #[test]
3220 fn invalid() {
3221 assert!(Time::new(24, 0, 0, 0).is_err());
3222 assert!(Time::new(23, 60, 0, 0).is_err());
3223 assert!(Time::new(23, 59, 60, 0).is_err());
3224 assert!(Time::new(23, 59, 61, 0).is_err());
3225 assert!(Time::new(-1, 0, 0, 0).is_err());
3226 assert!(Time::new(0, -1, 0, 0).is_err());
3227 assert!(Time::new(0, 0, -1, 0).is_err());
3228
3229 assert!(Time::new(0, 0, 0, 1_000_000_000).is_err());
3230 assert!(Time::new(0, 0, 0, -1).is_err());
3231 assert!(Time::new(23, 59, 59, 1_000_000_000).is_err());
3232 assert!(Time::new(23, 59, 59, -1).is_err());
3233 }
3234
3235 #[test]
3236 fn rounding_cross_midnight() {
3237 let t1 = time(23, 59, 59, 999_999_999);
3238
3239 let t2 = t1.round(Unit::Nanosecond).unwrap();
3240 assert_eq!(t2, t1);
3241
3242 let t2 = t1.round(Unit::Millisecond).unwrap();
3243 assert_eq!(t2, time(0, 0, 0, 0));
3244
3245 let t2 = t1.round(Unit::Microsecond).unwrap();
3246 assert_eq!(t2, time(0, 0, 0, 0));
3247
3248 let t2 = t1.round(Unit::Millisecond).unwrap();
3249 assert_eq!(t2, time(0, 0, 0, 0));
3250
3251 let t2 = t1.round(Unit::Second).unwrap();
3252 assert_eq!(t2, time(0, 0, 0, 0));
3253
3254 let t2 = t1.round(Unit::Minute).unwrap();
3255 assert_eq!(t2, time(0, 0, 0, 0));
3256
3257 let t2 = t1.round(Unit::Hour).unwrap();
3258 assert_eq!(t2, time(0, 0, 0, 0));
3259
3260 let t1 = time(22, 15, 0, 0);
3261 assert_eq!(
3262 time(22, 30, 0, 0),
3263 t1.round(TimeRound::new().smallest(Unit::Minute).increment(30))
3264 .unwrap()
3265 );
3266 }
3267
3268 #[cfg(not(miri))]
3269 quickcheck::quickcheck! {
3270 fn prop_ordering_same_as_civil_nanosecond(
3271 ns1: i64,
3272 ns2: i64
3273 ) -> quickcheck::TestResult {
3274 let Ok(ns1) = b::CivilDayNanosecond::check(ns1) else {
3275 return quickcheck::TestResult::discard();
3276 };
3277 let Ok(ns2) = b::CivilDayNanosecond::check(ns2) else {
3278 return quickcheck::TestResult::discard();
3279 };
3280 let t1 = Time::from_nanosecond(ns1).unwrap();
3281 let t2 = Time::from_nanosecond(ns2).unwrap();
3282 quickcheck::TestResult::from_bool(t1.cmp(&t2) == ns1.cmp(&ns2))
3283 }
3284
3285 fn prop_checked_add_then_sub(
3286 time: Time,
3287 nano_span: i64
3288 ) -> quickcheck::TestResult {
3289 let Ok(nano_span) = b::CivilDayNanosecond::check(nano_span) else {
3290 return quickcheck::TestResult::discard();
3291 };
3292 let span = Span::new().nanoseconds(nano_span);
3293 let Ok(sum) = time.checked_add(span) else {
3294 return quickcheck::TestResult::discard()
3295 };
3296 let diff = sum.checked_sub(span).unwrap();
3297 quickcheck::TestResult::from_bool(time == diff)
3298 }
3299
3300 fn prop_wrapping_add_then_sub(
3301 time: Time,
3302 nano_span: i64
3303 ) -> quickcheck::TestResult {
3304 let Ok(nano_span) = b::CivilDayNanosecond::check(nano_span) else {
3305 return quickcheck::TestResult::discard();
3306 };
3307 let span = Span::new().nanoseconds(nano_span);
3308 let sum = time.wrapping_add(span);
3309 let diff = sum.wrapping_sub(span);
3310 quickcheck::TestResult::from_bool(time == diff)
3311 }
3312
3313 fn prop_checked_add_equals_wrapping_add(
3314 time: Time,
3315 nano_span: i64
3316 ) -> quickcheck::TestResult {
3317 let Ok(nano_span) = b::CivilDayNanosecond::check(nano_span) else {
3318 return quickcheck::TestResult::discard();
3319 };
3320 let span = Span::new().nanoseconds(nano_span);
3321 let Ok(sum_checked) = time.checked_add(span) else {
3322 return quickcheck::TestResult::discard()
3323 };
3324 let sum_wrapped = time.wrapping_add(span);
3325 quickcheck::TestResult::from_bool(sum_checked == sum_wrapped)
3326 }
3327
3328 fn prop_checked_sub_equals_wrapping_sub(
3329 time: Time,
3330 nano_span: i64
3331 ) -> quickcheck::TestResult {
3332 let Ok(nano_span) = b::CivilDayNanosecond::check(nano_span) else {
3333 return quickcheck::TestResult::discard();
3334 };
3335 let span = Span::new().nanoseconds(nano_span);
3336 let Ok(diff_checked) = time.checked_sub(span) else {
3337 return quickcheck::TestResult::discard()
3338 };
3339 let diff_wrapped = time.wrapping_sub(span);
3340 quickcheck::TestResult::from_bool(diff_checked == diff_wrapped)
3341 }
3342
3343 fn prop_until_then_add(t1: Time, t2: Time) -> bool {
3344 let span = t1.until(t2).unwrap();
3345 t1.checked_add(span).unwrap() == t2
3346 }
3347
3348 fn prop_until_then_sub(t1: Time, t2: Time) -> bool {
3349 let span = t1.until(t2).unwrap();
3350 t2.checked_sub(span).unwrap() == t1
3351 }
3352
3353 fn prop_since_then_add(t1: Time, t2: Time) -> bool {
3354 let span = t1.since(t2).unwrap();
3355 t2.checked_add(span).unwrap() == t1
3356 }
3357
3358 fn prop_since_then_sub(t1: Time, t2: Time) -> bool {
3359 let span = t1.since(t2).unwrap();
3360 t1.checked_sub(span).unwrap() == t2
3361 }
3362
3363 fn prop_until_is_since_negated(t1: Time, t2: Time) -> bool {
3364 t1.until(t2).unwrap().get_nanoseconds()
3365 == t1.since(t2).unwrap().negate().get_nanoseconds()
3366 }
3367 }
3368
3369 #[test]
3370 fn overflowing_add() {
3371 let t1 = time(23, 30, 0, 0);
3372 let (t2, span) = t1.overflowing_add(&5.hours()).unwrap();
3373 assert_eq!(t2, time(4, 30, 0, 0));
3374 span_eq!(span, 1.days());
3375 }
3376
3377 #[test]
3378 fn overflowing_add_overflows() {
3379 let t1 = time(23, 30, 0, 0);
3380 let span = Span::new()
3381 .hours(b::SpanHours::MAX)
3382 .minutes(b::SpanMinutes::MAX)
3383 .seconds(b::SpanSeconds::MAX)
3384 .milliseconds(b::SpanMilliseconds::MAX)
3385 .microseconds(b::SpanMicroseconds::MAX)
3386 .nanoseconds(b::SpanNanoseconds::MAX);
3387 assert!(t1.overflowing_add(&span).is_err());
3388 }
3389
3390 #[test]
3391 fn overflowing_add_span_negative() {
3392 let t1 = time(0, 0, 0, 0);
3393
3394 let (t2, span) = t1.overflowing_add(&1.second()).unwrap();
3395 assert_eq!(t2, time(0, 0, 1, 0));
3396 span_eq!(span, 0.days());
3397
3398 let (t2, span) = t1.overflowing_add(&-1.second()).unwrap();
3399 assert_eq!(t2, time(23, 59, 59, 0));
3400 span_eq!(span, -1.days());
3401
3402 let (t2, span) = t1.overflowing_add(&1.nanosecond()).unwrap();
3403 assert_eq!(t2, time(0, 0, 0, 1));
3404 span_eq!(span, 0.days());
3405
3406 let (t2, span) = t1.overflowing_add(&-1.nanosecond()).unwrap();
3407 assert_eq!(t2, time(23, 59, 59, 999_999_999));
3408 span_eq!(span, -1.days());
3409
3410 let (t2, span) =
3411 t1.overflowing_add(&1.second().nanoseconds(2)).unwrap();
3412 assert_eq!(t2, time(0, 0, 1, 2));
3413 span_eq!(span, 0.days());
3414
3415 let (t2, span) =
3416 t1.overflowing_add(&-1.second().nanoseconds(2)).unwrap();
3417 assert_eq!(t2, time(23, 59, 58, 999_999_998));
3418 span_eq!(span, -1.days());
3419 }
3420
3421 #[test]
3422 fn overflowing_add_duration_negative() {
3423 let t1 = time(0, 0, 0, 0);
3424
3425 let (t2, dur) =
3426 t1.overflowing_add_duration(SignedDuration::from_secs(1)).unwrap();
3427 assert_eq!(t2, time(0, 0, 1, 0));
3428 assert_eq!(dur, SignedDuration::ZERO);
3429
3430 let (t2, dur) = t1
3431 .overflowing_add_duration(SignedDuration::from_secs(-1))
3432 .unwrap();
3433 assert_eq!(t2, time(23, 59, 59, 0));
3434 assert_eq!(dur, SignedDuration::from_hours(-24));
3435
3436 let (t2, dur) = t1
3437 .overflowing_add_duration(SignedDuration::from_nanos(1))
3438 .unwrap();
3439 assert_eq!(t2, time(0, 0, 0, 1));
3440 assert_eq!(dur, SignedDuration::ZERO);
3441
3442 let (t2, dur) = t1
3443 .overflowing_add_duration(SignedDuration::from_nanos(-1))
3444 .unwrap();
3445 assert_eq!(t2, time(23, 59, 59, 999_999_999));
3446 assert_eq!(dur, SignedDuration::from_hours(-24));
3447
3448 let (t2, dur) =
3449 t1.overflowing_add_duration(SignedDuration::new(1, 2)).unwrap();
3450 assert_eq!(t2, time(0, 0, 1, 2));
3451 assert_eq!(dur, SignedDuration::ZERO);
3452
3453 let (t2, dur) =
3454 t1.overflowing_add_duration(SignedDuration::new(-1, -2)).unwrap();
3455 assert_eq!(t2, time(23, 59, 58, 999_999_998));
3456 assert_eq!(dur, SignedDuration::from_hours(-24));
3457 }
3458
3459 #[test]
3460 fn time_size() {
3461 #[cfg(debug_assertions)]
3462 {
3463 assert_eq!(8, core::mem::size_of::<Time>());
3464 }
3465 #[cfg(not(debug_assertions))]
3466 {
3467 assert_eq!(8, core::mem::size_of::<Time>());
3468 }
3469 }
3470
3471 // This test checks that a wrapping subtraction with the minimum signed
3472 // duration is as expected.
3473 #[test]
3474 fn wrapping_sub_signed_duration_min() {
3475 let max = -SignedDuration::MIN.as_nanos();
3476 let got = i128::from(time(15, 30, 8, 999_999_999).to_nanosecond());
3477 let expected = max.rem_euclid(i128::from(c::NANOS_PER_CIVIL_DAY));
3478 assert_eq!(got, expected);
3479 }
3480
3481 // This test checks that a wrapping subtraction with the maximum signed
3482 // duration is as expected.
3483 #[test]
3484 fn wrapping_sub_signed_duration_max() {
3485 let max = -SignedDuration::MAX.as_nanos();
3486 let got = i128::from(time(8, 29, 52, 1).to_nanosecond());
3487 let expected = max.rem_euclid(i128::from(c::NANOS_PER_CIVIL_DAY));
3488 assert_eq!(got, expected);
3489 }
3490
3491 // This test checks that a wrapping subtraction with the maximum unsigned
3492 // duration is as expected.
3493 #[test]
3494 fn wrapping_sub_unsigned_duration_max() {
3495 let max =
3496 -i128::try_from(std::time::Duration::MAX.as_nanos()).unwrap();
3497 let got = i128::from(time(16, 59, 44, 1).to_nanosecond());
3498 let expected = max.rem_euclid(i128::from(c::NANOS_PER_CIVIL_DAY));
3499 assert_eq!(got, expected);
3500
3501 let dur = UnsignedDuration::MAX;
3502 let t = Time::midnight().wrapping_sub(dur);
3503 assert_eq!(t, Time::new(16, 59, 44, 1).unwrap());
3504 }
3505
3506 #[test]
3507 fn wrapping_add_span_max() {
3508 let span = Span::new()
3509 .hours(b::SpanHours::MAX)
3510 .minutes(b::SpanMinutes::MAX)
3511 .seconds(b::SpanSeconds::MAX)
3512 .milliseconds(b::SpanMilliseconds::MAX)
3513 .microseconds(b::SpanMicroseconds::MAX)
3514 .nanoseconds(b::SpanNanoseconds::MAX);
3515 let t = Time::midnight().wrapping_add(span);
3516 assert_eq!(t, Time::new(0, 42, 38, 811_897_855).unwrap());
3517 }
3518
3519 #[test]
3520 fn wrapping_add_span_min() {
3521 let span = Span::new()
3522 .hours(b::SpanHours::MIN)
3523 .minutes(b::SpanMinutes::MIN)
3524 .seconds(b::SpanSeconds::MIN)
3525 .milliseconds(b::SpanMilliseconds::MIN)
3526 .microseconds(b::SpanMicroseconds::MIN)
3527 .nanoseconds(b::SpanNanoseconds::MIN);
3528 let t = Time::midnight().wrapping_add(span);
3529 assert_eq!(t, Time::new(23, 17, 21, 188_102_145).unwrap());
3530 }
3531
3532 #[test]
3533 fn wrapping_add_signed_duration_max() {
3534 let dur = SignedDuration::MAX;
3535 let t = Time::midnight().wrapping_add(dur);
3536 assert_eq!(t, Time::new(15, 30, 7, 999_999_999).unwrap());
3537 }
3538
3539 #[test]
3540 fn wrapping_add_signed_duration_min() {
3541 let dur = SignedDuration::MIN;
3542 let t = Time::midnight().wrapping_add(dur);
3543 assert_eq!(t, Time::new(8, 29, 51, 1).unwrap());
3544 }
3545
3546 #[test]
3547 fn wrapping_add_unsigned_duration_max() {
3548 let dur = UnsignedDuration::MAX;
3549 let t = Time::midnight().wrapping_add(dur);
3550 assert_eq!(t, Time::new(7, 0, 15, 999_999_999).unwrap());
3551 }
3552
3553 /// # `serde` deserializer compatibility test
3554 ///
3555 /// Serde YAML used to be unable to deserialize `jiff` types,
3556 /// as deserializing from bytes is not supported by the deserializer.
3557 ///
3558 /// - <https://github.com/BurntSushi/jiff/issues/138>
3559 /// - <https://github.com/BurntSushi/jiff/discussions/148>
3560 #[test]
3561 fn civil_time_deserialize_yaml() {
3562 let expected = time(16, 35, 4, 987654321);
3563
3564 let deserialized: Time =
3565 serde_yaml::from_str("16:35:04.987654321").unwrap();
3566
3567 assert_eq!(deserialized, expected);
3568
3569 let deserialized: Time =
3570 serde_yaml::from_slice("16:35:04.987654321".as_bytes()).unwrap();
3571
3572 assert_eq!(deserialized, expected);
3573
3574 let cursor = Cursor::new(b"16:35:04.987654321");
3575 let deserialized: Time = serde_yaml::from_reader(cursor).unwrap();
3576
3577 assert_eq!(deserialized, expected);
3578 }
3579}