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