1use crate::{
2 bounds::{selfas b, RangeError},
3 civil::{self, DateTime},
4constantsas c,
5 macros::{rbail, rtry, unwrapr},
6};
78/// 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}
2021impl Time {
22/// The minimum allowed civil time.
23 ///
24 /// This corresponds to midnight.
25pub const MIN: Time =
26Time { hour: 0, minute: 0, second: 0, subsec_nanosecond: 0 };
2728/// The maximum allowed civil time.
29 ///
30 /// This corresponds to the last nanosecond in a civil day.
31pub const MAX: Time = Time {
32 hour: 23,
33 minute: 59,
34 second: 59,
35 subsec_nanosecond: 999_999_999,
36 };
3738/// 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]
43pub const fn new(
44 hour: i8,
45 minute: i8,
46 second: i8,
47 subsec_nanosecond: i32,
48 ) -> Result<Time, RangeError> {
49let 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));
50let 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));
51let 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));
52let subsec_nanosecond =
53match 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));
54Ok(Time { hour, minute, second, subsec_nanosecond })
55 }
5657/// 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]
62pub const fn hour(self) -> i8 {
63self.hour
64 }
6566/// 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]
71pub const fn minute(self) -> i8 {
72self.minute
73 }
7475/// 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]
80pub const fn second(self) -> i8 {
81self.second
82 }
8384/// Returns the "millisecond" component of this time.
85 ///
86 /// The value returned is guaranteed to be in the range `0..=999`.
87#[inline]
88pub const fn millisecond(self) -> i16 {
89 (self.subsec_nanosecond() as u32 / c::NANOS_PER_MILLI_32as u32) as i1690 }
9192/// Returns the "microsecond" component of this time.
93 ///
94 /// The value returned is guaranteed to be in the range `0..=999`.
95#[inline]
96pub const fn microsecond(self) -> i16 {
97 ((self.subsec_nanosecond() as u32 / c::NANOS_PER_MICRO_32as u32)
98 % c::MICROS_PER_MILLI_32as u32) as i1699 }
100101/// Returns the "nanosecond" component of this time.
102 ///
103 /// The value returned is guaranteed to be in the range `0..=999`.
104#[inline]
105pub const fn nanosecond(self) -> i16 {
106 (self.subsec_nanosecond() as u32 % c::NANOS_PER_MICRO_32as u32) as i16107 }
108109/// 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]
115pub const fn subsec_nanosecond(self) -> i32 {
116self.subsec_nanosecond
117 }
118119/// 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]
125pub const fn with_subsec_parts(
126self,
127 millisecond: i16,
128 microsecond: i16,
129 nanosecond: i16,
130 ) -> Result<Time, RangeError> {
131let 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));
132let 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));
133let 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));
134let subsec_nanosecond = (millisecondas i32 * c::NANOS_PER_MILLI_32)
135 + (microsecondas i32 * c::NANOS_PER_MICRO_32)
136 + (nanosecondas i32);
137Ok(Time { subsec_nanosecond, ..self })
138 }
139140/// 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]
146pub const fn with_subsec_nanosecond(
147self,
148 subsec_nanosecond: i32,
149 ) -> Result<Time, RangeError> {
150let subsec_nanosecond =
151match 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));
152Ok(Time { subsec_nanosecond, ..self })
153 }
154155/// 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]
164pub const fn to_second(self) -> TimeSecond {
165let mut second: i32 = 0;
166second += (self.hour() as i32) * 3600;
167second += (self.minute() as i32) * 60;
168second += self.second() as i32;
169TimeSecond { second }
170 }
171172/// 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]
179pub const fn to_nanosecond(self) -> TimeNanosecond {
180let mut nanosecond: i64 = 0;
181nanosecond += (self.hour() as i64) * 3_600_000_000_000;
182nanosecond += (self.minute() as i64) * 60_000_000_000;
183nanosecond += (self.second() as i64) * 1_000_000_000;
184nanosecond += self.subsec_nanosecond() as i64;
185TimeNanosecond { nanosecond }
186 }
187188/// 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]
207pub const fn on(self, year: i16, month: i8, day: i8) -> DateTime {
208DateTime::from_parts(civil::date(year, month, day), self)
209 }
210}
211212impl core::fmt::Debugfor Time {
213fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
214f.write_fmt(format_args!("{0:02}:{1:02}:{2:02}", self.hour(), self.minute(),
self.second()))write!(
215 f,
216"{:02}:{:02}:{:02}",
217self.hour(),
218self.minute(),
219self.second()
220 )?;
221let mut subsec = self.subsec_nanosecond();
222if subsec == 0 {
223return Ok(());
224 }
225226// 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`.
229let mut buf = [b'0'; 9];
230for i in (0..9).rev() {
231 buf[i] += (subsec % 10) as u8;
232 subsec /= 10;
233 }
234let mut end = 9;
235while end > 0 && buf[usize::from(end) - 1] == b'0' {
236 end -= 1;
237 }
238// OK because `buf` only ever contains ASCII digits.
239let fractional_digits = core::str::from_utf8(&buf[..end]).unwrap();
240f.write_fmt(format_args!(".{0}", fractional_digits))write!(f, ".{fractional_digits}")241 }
242}
243244#[cfg(feature = "arbitrary")]
245impl<'a> arbitrary::Arbitrary<'a> for Time {
246fn arbitrary(
247 u: &mut arbitrary::Unstructured<'a>,
248 ) -> arbitrary::Result<Time> {
249let hour = u.int_in_range(b::Hour::MIN..=b::Hour::MAX)?;
250let minute = u.int_in_range(b::Minute::MIN..=b::Minute::MAX)?;
251let second = u.int_in_range(b::Second::MIN..=b::Second::MAX)?;
252let subsec_nanosecond = u.int_in_range(
253 b::SubsecNanosecond::MIN..=b::SubsecNanosecond::MAX,
254 )?;
255Ok(Time::new(hour, minute, second, subsec_nanosecond).unwrap())
256 }
257258fn 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}
267268#[cfg(test)]
269impl quickcheck::Arbitrary for Time {
270fn arbitrary(g: &mut quickcheck::Gen) -> Time {
271let hour = b::Hour::arbitrary(g);
272let minute = b::Minute::arbitrary(g);
273let second = b::Second::arbitrary(g);
274let subsec_nanosecond = b::SubsecNanosecond::arbitrary(g);
275 Time::new(hour, minute, second, subsec_nanosecond).unwrap()
276 }
277278fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Time>> {
279 alloc::boxed::Box::new(
280 (
281self.hour(),
282self.minute(),
283self.second(),
284self.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}
295296/// 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}
302303impl 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]
310pub const fn new(second: i32) -> Result<TimeSecond, RangeError> {
311let 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));
312Ok(TimeSecond { second })
313 }
314315/// 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]
320pub const fn constant(second: i32) -> TimeSecond {
321match 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 }
323324/// 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]
329pub const fn second(self) -> i32 {
330self.second
331 }
332333/// 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]
346pub const fn overflowing_add(
347self,
348 seconds: i32,
349 ) -> Result<(TimeSecond, i32), RangeError> {
350let Some(sum) = self.second().checked_add(seconds) else {
351return Err(b::CivilDaySecond::error().into_range_error());rbail!(b::CivilDaySecond::error());
352 };
353let days = sum.div_euclid(c::SECS_PER_CIVIL_DAY_32);
354let rem = sum.rem_euclid(c::SECS_PER_CIVIL_DAY_32);
355Ok((TimeSecond { second: rem }, days))
356 }
357358/// 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]
363pub 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
372373 // cast to unsigned for faster division:
374let secs: u32 = self.second as u32;
375let hour: u32 = (secs / 3600) as u32;
376let tmin: u32 = (secs / 60) as u32;
377378Time {
379 hour: houras i8,
380 minute: ((tmin + 4 * hour) % 64) as i8,
381 second: ((secs + 4 * tmin) % 64) as i8,
382 subsec_nanosecond: 0,
383 }
384 }
385}
386387/// 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}
393394impl 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]
401pub const fn new(nanosecond: i64) -> Result<TimeNanosecond, RangeError> {
402let nanosecond =
403match b::CivilDayNanosecond::checkc(nanosecond as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::CivilDayNanosecond::checkc(nanosecond as i64));
404Ok(TimeNanosecond { nanosecond })
405 }
406407/// 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]
412pub const fn nanosecond(self) -> i64 {
413self.nanosecond
414 }
415416/// 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]
429pub const fn overflowing_add(
430self,
431 nanoseconds: i64,
432 ) -> Result<(TimeNanosecond, i64), RangeError> {
433let Some(sum) = self.nanosecond().checked_add(nanoseconds) else {
434return Err(b::CivilDayNanosecond::error().into_range_error());rbail!(b::CivilDayNanosecond::error());
435 };
436let days = sum.div_euclid(c::NANOS_PER_CIVIL_DAY);
437let rem = sum.rem_euclid(c::NANOS_PER_CIVIL_DAY);
438Ok((TimeNanosecond { nanosecond: rem }, days))
439 }
440441/// 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]
446pub 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:
449let nanos: u64 = self.nanosecond as u64;
450451let mut time: Time =
452TimeSecond { second: (nanos / 1_000_000_000) as i32 }.to_time();
453time.subsec_nanosecond = (nanos % 1_000_000_000) as i32;
454time455 }
456}
457458#[cfg(test)]
459mod tests {
460use super::*;
461462fn time(hour: i8, minute: i8, second: i8) -> Time {
463 timesub(hour, minute, second, 0)
464 }
465466fn timesub(hour: i8, minute: i8, second: i8, subsec: i32) -> Time {
467 Time::new(hour, minute, second, subsec).unwrap()
468 }
469470fn timesec(second: i32) -> TimeSecond {
471 TimeSecond::new(second).unwrap()
472 }
473474fn timenano(nanosecond: i64) -> TimeNanosecond {
475 TimeNanosecond::new(nanosecond).unwrap()
476 }
477478#[test]
479fn time_to_second_various() {
480let t = time(0, 0, 0);
481assert_eq!(t.to_second().second(), 0);
482483let t = timesub(0, 0, 0, 1);
484assert_eq!(t.to_second().second(), 0);
485486let t = timesub(0, 0, 0, 999_999_999);
487assert_eq!(t.to_second().second(), 0);
488489let t = time(0, 0, 1);
490assert_eq!(t.to_second().second(), 1);
491492let t = time(0, 1, 1);
493assert_eq!(t.to_second().second(), 60 + 1);
494495let t = time(1, 1, 1);
496assert_eq!(t.to_second().second(), 3600 + 60 + 1);
497498let t = time(23, 59, 59);
499assert_eq!(t.to_second().second(), 86_399);
500 }
501502#[test]
503fn second_to_time_various() {
504let ts = timesec(0);
505assert_eq!(ts.to_time(), time(0, 0, 0));
506507let ts = timesec(1);
508assert_eq!(ts.to_time(), time(0, 0, 1));
509510let ts = timesec(60 + 1);
511assert_eq!(ts.to_time(), time(0, 1, 1));
512513let ts = timesec(3600 + 60 + 1);
514assert_eq!(ts.to_time(), time(1, 1, 1));
515516let ts = timesec(86_399);
517assert_eq!(ts.to_time(), time(23, 59, 59));
518 }
519520#[test]
521fn time_to_nanosecond_various() {
522let t = timesub(0, 0, 0, 0);
523assert_eq!(t.to_nanosecond().nanosecond(), 0);
524525let t = timesub(0, 0, 0, 1);
526assert_eq!(t.to_nanosecond().nanosecond(), 1);
527528let t = timesub(0, 0, 0, 999_999_999);
529assert_eq!(t.to_nanosecond().nanosecond(), 999_999_999);
530531let t = timesub(0, 0, 1, 1);
532assert_eq!(t.to_nanosecond().nanosecond(), 1_000_000_000 + 1);
533534let t = timesub(0, 1, 1, 1);
535assert_eq!(
536 t.to_nanosecond().nanosecond(),
537 (60 + 1) * 1_000_000_000 + 1
538);
539540let t = timesub(1, 1, 1, 1);
541assert_eq!(
542 t.to_nanosecond().nanosecond(),
543 (3600 + 60 + 1) * 1_000_000_000 + 1
544);
545546let t = timesub(23, 59, 59, 1);
547assert_eq!(t.to_nanosecond().nanosecond(), 86_399 * 1_000_000_000 + 1);
548549let t = timesub(23, 59, 59, 999_999_999);
550assert_eq!(
551 t.to_nanosecond().nanosecond(),
55286_399 * 1_000_000_000 + 999_999_999
553);
554 }
555556#[test]
557fn nanosecond_to_time_various() {
558let ts = timenano(0);
559assert_eq!(ts.to_time(), timesub(0, 0, 0, 0));
560561let ts = timenano(1);
562assert_eq!(ts.to_time(), timesub(0, 0, 0, 1));
563564let ts = timenano(1_000_000_000 + 1);
565assert_eq!(ts.to_time(), timesub(0, 0, 1, 1));
566567let ts = timenano(61 * 1_000_000_000 + 1);
568assert_eq!(ts.to_time(), timesub(0, 1, 1, 1));
569570let ts = timenano((3600 + 60 + 1) * 1_000_000_000 + 1);
571assert_eq!(ts.to_time(), timesub(1, 1, 1, 1));
572573let ts = timenano(86_399 * 1_000_000_000);
574assert_eq!(ts.to_time(), timesub(23, 59, 59, 0));
575576let ts = timenano(86_399 * 1_000_000_000 + 1);
577assert_eq!(ts.to_time(), timesub(23, 59, 59, 1));
578579let ts = timenano(86_399 * 1_000_000_000 + 999_999_999);
580assert_eq!(ts.to_time(), timesub(23, 59, 59, 999_999_999));
581 }
582583#[test]
584fn second_overflowing_add() {
585let ts = timesec(0);
586assert_eq!(ts.overflowing_add(86_399), Ok((timesec(86_399), 0)));
587assert_eq!(ts.overflowing_add(86_400), Ok((timesec(0), 1)));
588assert_eq!(ts.overflowing_add(86_401), Ok((timesec(1), 1)));
589assert_eq!(ts.overflowing_add(i32::MAX), Ok((timesec(11_647), 24855)));
590591assert_eq!(ts.overflowing_add(-1), Ok((timesec(86_399), -1)));
592assert_eq!(ts.overflowing_add(-86_399), Ok((timesec(1), -1)));
593assert_eq!(ts.overflowing_add(-86_400), Ok((timesec(0), -1)));
594assert_eq!(ts.overflowing_add(-86_401), Ok((timesec(86_399), -2)));
595assert_eq!(
596 ts.overflowing_add(i32::MIN),
597Ok((timesec(74_752), -24856))
598 );
599600let ts = timesec(86_399);
601assert_eq!(
602 ts.overflowing_add(i32::MIN),
603Ok((timesec(74_751), -24855))
604 );
605606let ts = timesec(1);
607assert!(ts.overflowing_add(i32::MAX).is_err());
608 }
609610#[test]
611fn nanosecond_overflowing_add() {
612let ts = timenano(0);
613assert_eq!(
614 ts.overflowing_add(86_399_000_000_000),
615Ok((timenano(86_399_000_000_000), 0))
616 );
617assert_eq!(
618 ts.overflowing_add(86_400_000_000_000),
619Ok((timenano(0), 1))
620 );
621assert_eq!(
622 ts.overflowing_add(86_401_000_000_000),
623Ok((timenano(1_000_000_000), 1))
624 );
625assert_eq!(
626 ts.overflowing_add(i64::MAX),
627Ok((timenano(85_636_854_775_807), 106_751))
628 );
629630assert_eq!(
631 ts.overflowing_add(-1),
632Ok((timenano(86_399_999_999_999), -1))
633 );
634assert_eq!(
635 ts.overflowing_add(-1_000_000_000),
636Ok((timenano(86_399_000_000_000), -1))
637 );
638assert_eq!(
639 ts.overflowing_add(-86_399_000_000_000),
640Ok((timenano(1_000_000_000), -1))
641 );
642assert_eq!(
643 ts.overflowing_add(-86_400_000_000_000),
644Ok((timenano(0), -1))
645 );
646assert_eq!(
647 ts.overflowing_add(-86_401_000_000_000),
648Ok((timenano(86_399_000_000_000), -2))
649 );
650assert_eq!(
651 ts.overflowing_add(i64::MIN),
652Ok((timenano(763_145_224_192), -106_752))
653 );
654655let ts = timenano(86_399_000_000_000);
656assert_eq!(
657 ts.overflowing_add(i64::MIN),
658Ok((timenano(762_145_224_192), -106_751))
659 );
660661let ts = timenano(1_000_000_000);
662assert!(ts.overflowing_add(i64::MAX).is_err());
663let ts = timenano(1);
664assert!(ts.overflowing_add(i64::MAX).is_err());
665 }
666667quickcheck::quickcheck! {
668fn prop_time_to_second_roundtrip(t: Time) -> bool {
669let t = Time::new(t.hour(), t.minute(), t.second(), 0).unwrap();
670 t == t.to_second().to_time()
671 }
672673fn prop_time_to_nanosecond_roundtrip(t: Time) -> bool {
674 t == t.to_nanosecond().to_time()
675 }
676 }
677}