Skip to main content

jiff_core/civil/
time.rs

1use crate::{
2    bounds::{self as b, RangeError},
3    civil::{self, DateTime},
4    constants as c,
5    macros::{rbail, rtry, unwrapr},
6};
7
8/// The civil time of day.
9///
10/// This time's representation uses nanosecond precision. The full range of
11/// clock values are `00:00:00.000000000` to `23:59:59.999999999` inclusive.
12#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Time {
}
#[automatically_derived]impl ::core::clone::Clone for Time {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<i8>;
        let _: ::core::clone::AssertParamIsClone<i32>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Time { }Copy, #[automatically_derived]impl ::core::cmp::Eq for Time {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<i8>;
        let _: ::core::cmp::AssertParamIsEq<i32>;
    }
}Eq, #[automatically_derived]impl ::core::hash::Hash for Time {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.hour, state);
        ::core::hash::Hash::hash(&self.minute, state);
        ::core::hash::Hash::hash(&self.second, state);
        ::core::hash::Hash::hash(&self.subsec_nanosecond, state)
    }
}Hash, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Time { }
#[automatically_derived]impl ::core::cmp::PartialEq for Time {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.hour == other.hour && self.minute == other.minute &&
                self.second == other.second &&
            self.subsec_nanosecond == other.subsec_nanosecond
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::PartialOrd for Time {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]impl ::core::cmp::Ord for Time {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.hour, &other.hour) {
            ::core::cmp::Ordering::Equal =>
                match ::core::cmp::Ord::cmp(&self.minute, &other.minute) {
                    ::core::cmp::Ordering::Equal =>
                        match ::core::cmp::Ord::cmp(&self.second, &other.second) {
                            ::core::cmp::Ordering::Equal =>
                                ::core::cmp::Ord::cmp(&self.subsec_nanosecond,
                                    &other.subsec_nanosecond),
                            cmp => cmp,
                        },
                    cmp => cmp,
                },
            cmp => cmp,
        }
    }
}Ord)]
13#[cfg_attr(feature = "defmt", derive(defmt::Format))]
14pub struct Time {
15    hour: i8,
16    minute: i8,
17    second: i8,
18    subsec_nanosecond: i32,
19}
20
21impl Time {
22    /// The minimum allowed civil time.
23    ///
24    /// This corresponds to midnight.
25    pub const MIN: Time =
26        Time { hour: 0, minute: 0, second: 0, subsec_nanosecond: 0 };
27
28    /// The maximum allowed civil time.
29    ///
30    /// This corresponds to the last nanosecond in a civil day.
31    pub const MAX: Time = Time {
32        hour: 23,
33        minute: 59,
34        second: 59,
35        subsec_nanosecond: 999_999_999,
36    };
37
38    /// Creates a new civil time from its constituent components.
39    ///
40    /// If any of the values are out of their supported ranges, then an error
41    /// is returned.
42    #[inline]
43    pub const fn new(
44        hour: i8,
45        minute: i8,
46        second: i8,
47        subsec_nanosecond: i32,
48    ) -> Result<Time, RangeError> {
49        let hour = match b::Hour::checkc(hour as i64) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::Hour::checkc(hour as i64));
50        let minute = match b::Minute::checkc(minute as i64) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::Minute::checkc(minute as i64));
51        let second = match b::Second::checkc(second as i64) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::Second::checkc(second as i64));
52        let subsec_nanosecond =
53            match b::SubsecNanosecond::checkc(subsec_nanosecond as i64) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::SubsecNanosecond::checkc(subsec_nanosecond as i64));
54        Ok(Time { hour, minute, second, subsec_nanosecond })
55    }
56
57    /// Returns the hour component of this civil time.
58    ///
59    /// The value returned is guaranteed to be in the range specified by
60    /// [`Hour`](crate::bounds::Hour).
61    #[inline]
62    pub const fn hour(self) -> i8 {
63        self.hour
64    }
65
66    /// Returns the minute component of this civil time.
67    ///
68    /// The value returned is guaranteed to be in the range specified by
69    /// [`Minute`](crate::bounds::Minute).
70    #[inline]
71    pub const fn minute(self) -> i8 {
72        self.minute
73    }
74
75    /// Returns the second component of this civil time.
76    ///
77    /// The value returned is guaranteed to be in the range specified by
78    /// [`Second`](crate::bounds::Second).
79    #[inline]
80    pub const fn second(self) -> i8 {
81        self.second
82    }
83
84    /// Returns the "millisecond" component of this time.
85    ///
86    /// The value returned is guaranteed to be in the range `0..=999`.
87    #[inline]
88    pub const fn millisecond(self) -> i16 {
89        (self.subsec_nanosecond() as u32 / c::NANOS_PER_MILLI_32 as u32) as i16
90    }
91
92    /// Returns the "microsecond" component of this time.
93    ///
94    /// The value returned is guaranteed to be in the range `0..=999`.
95    #[inline]
96    pub const fn microsecond(self) -> i16 {
97        ((self.subsec_nanosecond() as u32 / c::NANOS_PER_MICRO_32 as u32)
98            % c::MICROS_PER_MILLI_32 as u32) as i16
99    }
100
101    /// Returns the "nanosecond" component of this time.
102    ///
103    /// The value returned is guaranteed to be in the range `0..=999`.
104    #[inline]
105    pub const fn nanosecond(self) -> i16 {
106        (self.subsec_nanosecond() as u32 % c::NANOS_PER_MICRO_32 as u32) as i16
107    }
108
109    /// Returns the fractional second (to nanosecond precision) component of
110    /// this civil time.
111    ///
112    /// The value returned is guaranteed to be in the range specified by
113    /// [`SubsecNanosecond`](crate::bounds::SubsecNanosecond).
114    #[inline]
115    pub const fn subsec_nanosecond(self) -> i32 {
116        self.subsec_nanosecond
117    }
118
119    /// Returns this time with its subsecond component replaced with the three
120    /// given subsecond components.
121    ///
122    /// If any of the given components are out of range (`0..=999`), then an
123    /// error is returned.
124    #[inline]
125    pub const fn with_subsec_parts(
126        self,
127        millisecond: i16,
128        microsecond: i16,
129        nanosecond: i16,
130    ) -> Result<Time, RangeError> {
131        let millisecond = match b::Millisecond::checkc(millisecond as i64) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::Millisecond::checkc(millisecond as i64));
132        let microsecond = match b::Microsecond::checkc(microsecond as i64) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::Microsecond::checkc(microsecond as i64));
133        let nanosecond = match b::Nanosecond::checkc(nanosecond as i64) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::Nanosecond::checkc(nanosecond as i64));
134        let subsec_nanosecond = (millisecond as i32 * c::NANOS_PER_MILLI_32)
135            + (microsecond as i32 * c::NANOS_PER_MICRO_32)
136            + (nanosecond as i32);
137        Ok(Time { subsec_nanosecond, ..self })
138    }
139
140    /// Returns this time with its subsecond component replaced with the
141    /// nanosecond component given.
142    ///
143    /// If the number of nanoseconds is out of range (`0..=999_999_999`), then
144    /// an error is returned.
145    #[inline]
146    pub const fn with_subsec_nanosecond(
147        self,
148        subsec_nanosecond: i32,
149    ) -> Result<Time, RangeError> {
150        let subsec_nanosecond =
151            match b::SubsecNanosecond::checkc(subsec_nanosecond as i64) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::SubsecNanosecond::checkc(subsec_nanosecond as i64));
152        Ok(Time { subsec_nanosecond, ..self })
153    }
154
155    /// Converts this civil time to a second value corresponding to the number
156    /// of seconds that has elapsed since midnight until this time. If this
157    /// time is midnight, then the second value returned is `0`.
158    ///
159    /// Note that this drops any subsecond component on this civil time.
160    ///
161    /// The value returned is guaranteed to be in the range specified by
162    /// [`CivilDaySecond`](crate::bounds::CivilDaySecond).
163    #[inline]
164    pub const fn to_second(self) -> TimeSecond {
165        let mut second: i32 = 0;
166        second += (self.hour() as i32) * 3600;
167        second += (self.minute() as i32) * 60;
168        second += self.second() as i32;
169        TimeSecond { second }
170    }
171
172    /// Converts this civil time to a nanosecond value corresponding to the
173    /// number of nanoseconds that has elapsed since midnight until this time.
174    /// If this time is midnight, then the nanosecond value returned is `0`.
175    ///
176    /// The value returned is guaranteed to be in the range specified by
177    /// [`CivilDayNanosecond`](crate::bounds::CivilDayNanosecond).
178    #[inline]
179    pub const fn to_nanosecond(self) -> TimeNanosecond {
180        let mut nanosecond: i64 = 0;
181        nanosecond += (self.hour() as i64) * 3_600_000_000_000;
182        nanosecond += (self.minute() as i64) * 60_000_000_000;
183        nanosecond += (self.second() as i64) * 1_000_000_000;
184        nanosecond += self.subsec_nanosecond() as i64;
185        TimeNanosecond { nanosecond }
186    }
187
188    /// A convenience function for constructing a [`DateTime`] from this time
189    /// on the date given by its components.
190    ///
191    /// # Panics
192    ///
193    /// This routine panics when [`Date::new`](crate::civil::Date) with
194    /// the given inputs would return an error. That is, when the given
195    /// year-month-day does not correspond to a valid date. Namely, all of the
196    /// following must be true:
197    ///
198    /// * The year must be in the range `-9999..=9999`.
199    /// * The month must be in the range `1..=12`.
200    /// * The day must be at least `1` and must be at most the number of days
201    /// in the corresponding month. So for example, `2024-02-29` is valid but
202    /// `2023-02-29` is not.
203    ///
204    /// Similarly, when used in a const context, invalid parameters will
205    /// prevent your Rust program from compiling.
206    #[inline]
207    pub const fn on(self, year: i16, month: i8, day: i8) -> DateTime {
208        DateTime::from_parts(civil::date(year, month, day), self)
209    }
210}
211
212impl core::fmt::Debug for Time {
213    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
214        f.write_fmt(format_args!("{0:02}:{1:02}:{2:02}", self.hour(), self.minute(),
        self.second()))write!(
215            f,
216            "{:02}:{:02}:{:02}",
217            self.hour(),
218            self.minute(),
219            self.second()
220        )?;
221        let mut subsec = self.subsec_nanosecond();
222        if subsec == 0 {
223            return Ok(());
224        }
225
226        // This is really annoying. But we don't have Jiff's formatting
227        // facilities to handle this for us. We should also support precision
228        // settings from `Formatter`.
229        let mut buf = [b'0'; 9];
230        for i in (0..9).rev() {
231            buf[i] += (subsec % 10) as u8;
232            subsec /= 10;
233        }
234        let mut end = 9;
235        while end > 0 && buf[usize::from(end) - 1] == b'0' {
236            end -= 1;
237        }
238        // OK because `buf` only ever contains ASCII digits.
239        let fractional_digits = core::str::from_utf8(&buf[..end]).unwrap();
240        f.write_fmt(format_args!(".{0}", fractional_digits))write!(f, ".{fractional_digits}")
241    }
242}
243
244#[cfg(feature = "arbitrary")]
245impl<'a> arbitrary::Arbitrary<'a> for Time {
246    fn arbitrary(
247        u: &mut arbitrary::Unstructured<'a>,
248    ) -> arbitrary::Result<Time> {
249        let hour = u.int_in_range(b::Hour::MIN..=b::Hour::MAX)?;
250        let minute = u.int_in_range(b::Minute::MIN..=b::Minute::MAX)?;
251        let second = u.int_in_range(b::Second::MIN..=b::Second::MAX)?;
252        let subsec_nanosecond = u.int_in_range(
253            b::SubsecNanosecond::MIN..=b::SubsecNanosecond::MAX,
254        )?;
255        Ok(Time::new(hour, minute, second, subsec_nanosecond).unwrap())
256    }
257
258    fn size_hint(depth: usize) -> (usize, Option<usize>) {
259        arbitrary::size_hint::and_all(&[
260            <i8 as arbitrary::Arbitrary>::size_hint(depth),
261            <i8 as arbitrary::Arbitrary>::size_hint(depth),
262            <i8 as arbitrary::Arbitrary>::size_hint(depth),
263            <i32 as arbitrary::Arbitrary>::size_hint(depth),
264        ])
265    }
266}
267
268#[cfg(test)]
269impl quickcheck::Arbitrary for Time {
270    fn arbitrary(g: &mut quickcheck::Gen) -> Time {
271        let hour = b::Hour::arbitrary(g);
272        let minute = b::Minute::arbitrary(g);
273        let second = b::Second::arbitrary(g);
274        let subsec_nanosecond = b::SubsecNanosecond::arbitrary(g);
275        Time::new(hour, minute, second, subsec_nanosecond).unwrap()
276    }
277
278    fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Time>> {
279        alloc::boxed::Box::new(
280            (
281                self.hour(),
282                self.minute(),
283                self.second(),
284                self.subsec_nanosecond(),
285            )
286                .shrink()
287                .filter_map(
288                    |(hour, minute, second, subsec_nanosecond)| {
289                        Time::new(hour, minute, second, subsec_nanosecond).ok()
290                    },
291                ),
292        )
293    }
294}
295
296/// Represents a single point in a civil day, to second precision.
297#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for TimeSecond {
}
#[automatically_derived]impl ::core::clone::Clone for TimeSecond {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<i32>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for TimeSecond { }Copy, #[automatically_derived]impl ::core::fmt::Debug for TimeSecond {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "TimeSecond second", &&self.second)
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for TimeSecond {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<i32>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    TimeSecond {
}
#[automatically_derived]impl ::core::cmp::PartialEq for TimeSecond {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.second == other.second }
}PartialEq, #[automatically_derived]impl ::core::cmp::PartialOrd for TimeSecond {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]impl ::core::cmp::Ord for TimeSecond {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&self.second, &other.second)
    }
}Ord)]
298#[cfg_attr(feature = "defmt", derive(defmt::Format))]
299pub struct TimeSecond {
300    second: i32,
301}
302
303impl TimeSecond {
304    /// Creates a new civil time from a given second value.
305    ///
306    /// The value must correspond to the number of seconds elapsed since
307    /// the start of a civil day. It cannot exceed the length of a civil day
308    /// (in seconds).
309    #[inline]
310    pub const fn new(second: i32) -> Result<TimeSecond, RangeError> {
311        let second = match b::CivilDaySecond::checkc(second as i64) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::CivilDaySecond::checkc(second as i64));
312        Ok(TimeSecond { second })
313    }
314
315    /// Creates a new civil time from a given second value.
316    ///
317    /// This panics when `second` exceeds the maximum number of seconds in a
318    /// single civil day.
319    #[inline]
320    pub const fn constant(second: i32) -> TimeSecond {
321        match TimeSecond::new(second) {
    Ok(val) => val,
    Err(_) => {
        ::core::panicking::panic_fmt(format_args!("invalid civil day second"));
    }
}unwrapr!(TimeSecond::new(second), "invalid civil day second")
322    }
323
324    /// Returns the second value.
325    ///
326    /// The value returned is guaranteed to be in the range specified by
327    /// [`CivilDaySecond`](crate::bounds::CivilDaySecond).
328    #[inline]
329    pub const fn second(self) -> i32 {
330        self.second
331    }
332
333    /// Adds the given number of seconds to this civil time and returns the
334    /// resulting civil time with any overflowing amount in units of civil
335    /// days.
336    ///
337    /// This returns an error when integer overflow occurs. For example, when
338    /// `seconds` is `i32::MAX` and this civil time is any time other than
339    /// midnight.
340    ///
341    /// Note that the number of days returned may exceed the range supported
342    /// by [`UnixEpochDay`](crate::civil::UnixEpochDay). Moreover, the number
343    /// of days returned may be negative. This occurs only when `seconds` is
344    /// negative enough to result in the time wrapping around at `0`.
345    #[inline]
346    pub const fn overflowing_add(
347        self,
348        seconds: i32,
349    ) -> Result<(TimeSecond, i32), RangeError> {
350        let Some(sum) = self.second().checked_add(seconds) else {
351            return Err(b::CivilDaySecond::error().into_range_error());rbail!(b::CivilDaySecond::error());
352        };
353        let days = sum.div_euclid(c::SECS_PER_CIVIL_DAY_32);
354        let rem = sum.rem_euclid(c::SECS_PER_CIVIL_DAY_32);
355        Ok((TimeSecond { second: rem }, days))
356    }
357
358    /// Converts this second representation of a civil time into the
359    /// components of a civil time.
360    ///
361    /// The subsecond component on the `Time` returned is always `0`.
362    #[inline]
363    pub const fn to_time(&self) -> Time {
364        // Uses a non-obvious sequence to allow component extraction
365        // to have overlapping execution.
366        //
367        // Calculation of `minute` and `second` use an optimised
368        // "power-complement-padding" technique instead of standard mod.
369        // Relies on the identity: 60 + 2^2 = 2^6.
370        //
371        // Ref: https://www.benjoffe.com/fast-time-of-day
372
373        // cast to unsigned for faster division:
374        let secs: u32 = self.second as u32;
375        let hour: u32 = (secs / 3600) as u32;
376        let tmin: u32 = (secs / 60) as u32;
377
378        Time {
379            hour: hour as i8,
380            minute: ((tmin + 4 * hour) % 64) as i8,
381            second: ((secs + 4 * tmin) % 64) as i8,
382            subsec_nanosecond: 0,
383        }
384    }
385}
386
387/// Represents a single point in a civil day, to nanosecond precision.
388#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for TimeNanosecond {
}
#[automatically_derived]impl ::core::clone::Clone for TimeNanosecond {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<i64>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for TimeNanosecond { }Copy, #[automatically_derived]impl ::core::fmt::Debug for TimeNanosecond {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "TimeNanosecond nanosecond", &&self.nanosecond)
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for TimeNanosecond {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<i64>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    TimeNanosecond {
}
#[automatically_derived]impl ::core::cmp::PartialEq for TimeNanosecond {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.nanosecond == other.nanosecond }
}PartialEq, #[automatically_derived]impl ::core::cmp::PartialOrd for TimeNanosecond {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]impl ::core::cmp::Ord for TimeNanosecond {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&self.nanosecond, &other.nanosecond)
    }
}Ord)]
389#[cfg_attr(feature = "defmt", derive(defmt::Format))]
390pub struct TimeNanosecond {
391    nanosecond: i64,
392}
393
394impl TimeNanosecond {
395    /// Creates a new civil time from a given nanosecond value.
396    ///
397    /// The value must correspond to the number of nanoseconds elapsed since
398    /// the start of a civil day. It cannot exceed the length of a civil day
399    /// (in nanoseconds).
400    #[inline]
401    pub const fn new(nanosecond: i64) -> Result<TimeNanosecond, RangeError> {
402        let nanosecond =
403            match b::CivilDayNanosecond::checkc(nanosecond as i64) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::CivilDayNanosecond::checkc(nanosecond as i64));
404        Ok(TimeNanosecond { nanosecond })
405    }
406
407    /// Returns the nanosecond value.
408    ///
409    /// The value returned is guaranteed to be in the range specified by
410    /// [`CivilDayNanosecond`](crate::bounds::CivilDayNanosecond).
411    #[inline]
412    pub const fn nanosecond(self) -> i64 {
413        self.nanosecond
414    }
415
416    /// Adds the given number of nanoseconds to this civil time and returns the
417    /// resulting civil time with any overflowing amount in units of civil
418    /// days.
419    ///
420    /// This returns an error when integer overflow occurs. For example, when
421    /// `seconds` is `i64::MAX` and this civil time is any time other than
422    /// midnight.
423    ///
424    /// Note that the number of days returned may exceed the range supported by
425    /// [`UnixEpochDay`](crate::civil::UnixEpochDay). Moreover, the number of
426    /// days returned may be negative. This occurs only when `nanoseconds` is
427    /// negative enough to result in the time wrapping around at `0`.
428    #[inline]
429    pub const fn overflowing_add(
430        self,
431        nanoseconds: i64,
432    ) -> Result<(TimeNanosecond, i64), RangeError> {
433        let Some(sum) = self.nanosecond().checked_add(nanoseconds) else {
434            return Err(b::CivilDayNanosecond::error().into_range_error());rbail!(b::CivilDayNanosecond::error());
435        };
436        let days = sum.div_euclid(c::NANOS_PER_CIVIL_DAY);
437        let rem = sum.rem_euclid(c::NANOS_PER_CIVIL_DAY);
438        Ok((TimeNanosecond { nanosecond: rem }, days))
439    }
440
441    /// Converts this nanosecond representation of a civil time into the
442    /// components of a civil time.
443    ///
444    /// The subsecond component is preserved in the returned `Time`.
445    #[inline]
446    pub const fn to_time(&self) -> Time {
447        // Nanosecond is enforced as non-negative elsewhere
448        // as such, we can cast to unsigned for faster division:
449        let nanos: u64 = self.nanosecond as u64;
450
451        let mut time: Time =
452            TimeSecond { second: (nanos / 1_000_000_000) as i32 }.to_time();
453        time.subsec_nanosecond = (nanos % 1_000_000_000) as i32;
454        time
455    }
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461
462    fn time(hour: i8, minute: i8, second: i8) -> Time {
463        timesub(hour, minute, second, 0)
464    }
465
466    fn timesub(hour: i8, minute: i8, second: i8, subsec: i32) -> Time {
467        Time::new(hour, minute, second, subsec).unwrap()
468    }
469
470    fn timesec(second: i32) -> TimeSecond {
471        TimeSecond::new(second).unwrap()
472    }
473
474    fn timenano(nanosecond: i64) -> TimeNanosecond {
475        TimeNanosecond::new(nanosecond).unwrap()
476    }
477
478    #[test]
479    fn time_to_second_various() {
480        let t = time(0, 0, 0);
481        assert_eq!(t.to_second().second(), 0);
482
483        let t = timesub(0, 0, 0, 1);
484        assert_eq!(t.to_second().second(), 0);
485
486        let t = timesub(0, 0, 0, 999_999_999);
487        assert_eq!(t.to_second().second(), 0);
488
489        let t = time(0, 0, 1);
490        assert_eq!(t.to_second().second(), 1);
491
492        let t = time(0, 1, 1);
493        assert_eq!(t.to_second().second(), 60 + 1);
494
495        let t = time(1, 1, 1);
496        assert_eq!(t.to_second().second(), 3600 + 60 + 1);
497
498        let t = time(23, 59, 59);
499        assert_eq!(t.to_second().second(), 86_399);
500    }
501
502    #[test]
503    fn second_to_time_various() {
504        let ts = timesec(0);
505        assert_eq!(ts.to_time(), time(0, 0, 0));
506
507        let ts = timesec(1);
508        assert_eq!(ts.to_time(), time(0, 0, 1));
509
510        let ts = timesec(60 + 1);
511        assert_eq!(ts.to_time(), time(0, 1, 1));
512
513        let ts = timesec(3600 + 60 + 1);
514        assert_eq!(ts.to_time(), time(1, 1, 1));
515
516        let ts = timesec(86_399);
517        assert_eq!(ts.to_time(), time(23, 59, 59));
518    }
519
520    #[test]
521    fn time_to_nanosecond_various() {
522        let t = timesub(0, 0, 0, 0);
523        assert_eq!(t.to_nanosecond().nanosecond(), 0);
524
525        let t = timesub(0, 0, 0, 1);
526        assert_eq!(t.to_nanosecond().nanosecond(), 1);
527
528        let t = timesub(0, 0, 0, 999_999_999);
529        assert_eq!(t.to_nanosecond().nanosecond(), 999_999_999);
530
531        let t = timesub(0, 0, 1, 1);
532        assert_eq!(t.to_nanosecond().nanosecond(), 1_000_000_000 + 1);
533
534        let t = timesub(0, 1, 1, 1);
535        assert_eq!(
536            t.to_nanosecond().nanosecond(),
537            (60 + 1) * 1_000_000_000 + 1
538        );
539
540        let t = timesub(1, 1, 1, 1);
541        assert_eq!(
542            t.to_nanosecond().nanosecond(),
543            (3600 + 60 + 1) * 1_000_000_000 + 1
544        );
545
546        let t = timesub(23, 59, 59, 1);
547        assert_eq!(t.to_nanosecond().nanosecond(), 86_399 * 1_000_000_000 + 1);
548
549        let t = timesub(23, 59, 59, 999_999_999);
550        assert_eq!(
551            t.to_nanosecond().nanosecond(),
552            86_399 * 1_000_000_000 + 999_999_999
553        );
554    }
555
556    #[test]
557    fn nanosecond_to_time_various() {
558        let ts = timenano(0);
559        assert_eq!(ts.to_time(), timesub(0, 0, 0, 0));
560
561        let ts = timenano(1);
562        assert_eq!(ts.to_time(), timesub(0, 0, 0, 1));
563
564        let ts = timenano(1_000_000_000 + 1);
565        assert_eq!(ts.to_time(), timesub(0, 0, 1, 1));
566
567        let ts = timenano(61 * 1_000_000_000 + 1);
568        assert_eq!(ts.to_time(), timesub(0, 1, 1, 1));
569
570        let ts = timenano((3600 + 60 + 1) * 1_000_000_000 + 1);
571        assert_eq!(ts.to_time(), timesub(1, 1, 1, 1));
572
573        let ts = timenano(86_399 * 1_000_000_000);
574        assert_eq!(ts.to_time(), timesub(23, 59, 59, 0));
575
576        let ts = timenano(86_399 * 1_000_000_000 + 1);
577        assert_eq!(ts.to_time(), timesub(23, 59, 59, 1));
578
579        let ts = timenano(86_399 * 1_000_000_000 + 999_999_999);
580        assert_eq!(ts.to_time(), timesub(23, 59, 59, 999_999_999));
581    }
582
583    #[test]
584    fn second_overflowing_add() {
585        let ts = timesec(0);
586        assert_eq!(ts.overflowing_add(86_399), Ok((timesec(86_399), 0)));
587        assert_eq!(ts.overflowing_add(86_400), Ok((timesec(0), 1)));
588        assert_eq!(ts.overflowing_add(86_401), Ok((timesec(1), 1)));
589        assert_eq!(ts.overflowing_add(i32::MAX), Ok((timesec(11_647), 24855)));
590
591        assert_eq!(ts.overflowing_add(-1), Ok((timesec(86_399), -1)));
592        assert_eq!(ts.overflowing_add(-86_399), Ok((timesec(1), -1)));
593        assert_eq!(ts.overflowing_add(-86_400), Ok((timesec(0), -1)));
594        assert_eq!(ts.overflowing_add(-86_401), Ok((timesec(86_399), -2)));
595        assert_eq!(
596            ts.overflowing_add(i32::MIN),
597            Ok((timesec(74_752), -24856))
598        );
599
600        let ts = timesec(86_399);
601        assert_eq!(
602            ts.overflowing_add(i32::MIN),
603            Ok((timesec(74_751), -24855))
604        );
605
606        let ts = timesec(1);
607        assert!(ts.overflowing_add(i32::MAX).is_err());
608    }
609
610    #[test]
611    fn nanosecond_overflowing_add() {
612        let ts = timenano(0);
613        assert_eq!(
614            ts.overflowing_add(86_399_000_000_000),
615            Ok((timenano(86_399_000_000_000), 0))
616        );
617        assert_eq!(
618            ts.overflowing_add(86_400_000_000_000),
619            Ok((timenano(0), 1))
620        );
621        assert_eq!(
622            ts.overflowing_add(86_401_000_000_000),
623            Ok((timenano(1_000_000_000), 1))
624        );
625        assert_eq!(
626            ts.overflowing_add(i64::MAX),
627            Ok((timenano(85_636_854_775_807), 106_751))
628        );
629
630        assert_eq!(
631            ts.overflowing_add(-1),
632            Ok((timenano(86_399_999_999_999), -1))
633        );
634        assert_eq!(
635            ts.overflowing_add(-1_000_000_000),
636            Ok((timenano(86_399_000_000_000), -1))
637        );
638        assert_eq!(
639            ts.overflowing_add(-86_399_000_000_000),
640            Ok((timenano(1_000_000_000), -1))
641        );
642        assert_eq!(
643            ts.overflowing_add(-86_400_000_000_000),
644            Ok((timenano(0), -1))
645        );
646        assert_eq!(
647            ts.overflowing_add(-86_401_000_000_000),
648            Ok((timenano(86_399_000_000_000), -2))
649        );
650        assert_eq!(
651            ts.overflowing_add(i64::MIN),
652            Ok((timenano(763_145_224_192), -106_752))
653        );
654
655        let ts = timenano(86_399_000_000_000);
656        assert_eq!(
657            ts.overflowing_add(i64::MIN),
658            Ok((timenano(762_145_224_192), -106_751))
659        );
660
661        let ts = timenano(1_000_000_000);
662        assert!(ts.overflowing_add(i64::MAX).is_err());
663        let ts = timenano(1);
664        assert!(ts.overflowing_add(i64::MAX).is_err());
665    }
666
667    quickcheck::quickcheck! {
668        fn prop_time_to_second_roundtrip(t: Time) -> bool {
669            let t = Time::new(t.hour(), t.minute(), t.second(), 0).unwrap();
670            t == t.to_second().to_time()
671        }
672
673        fn prop_time_to_nanosecond_roundtrip(t: Time) -> bool {
674            t == t.to_nanosecond().to_time()
675        }
676    }
677}