Skip to content

Commit

Permalink
Make NaiveTime::from_num_seconds_from_midnight return Result
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Feb 5, 2024
1 parent 389c798 commit dd8e32e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 14 deletions.
2 changes: 1 addition & 1 deletion src/naive/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ impl NaiveDateTime {
NaiveDate::from_num_days_from_ce_opt(try_opt!((days as i32).checked_add(719_163)));
let time = NaiveTime::from_num_seconds_from_midnight(secs as u32, nsecs);
match (date, time) {
(Some(date), Some(time)) => Some(NaiveDateTime { date, time }),
(Some(date), Ok(time)) => Some(NaiveDateTime { date, time }),
(_, _) => None,
}
}
Expand Down
31 changes: 18 additions & 13 deletions src/naive/time/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -391,28 +391,33 @@ impl NaiveTime {
///
/// # Errors
///
/// Returns `None` on invalid number of seconds and/or nanosecond.
/// Returns `[`Error::InvalidParameter`]` on invalid number of seconds and/or nanosecond.
///
/// Returns [`Error::DoesNotExist`] if the nanosecond part to represent a leap second is not on
/// a minute boundary.
///
/// # Example
///
/// ```
/// use chrono::NaiveTime;
/// use chrono::{Error, NaiveTime};
///
/// let from_nsecs_opt = NaiveTime::from_num_seconds_from_midnight;
/// let from_nsecs = NaiveTime::from_num_seconds_from_midnight;
///
/// assert!(from_nsecs_opt(0, 0).is_some());
/// assert!(from_nsecs_opt(86399, 999_999_999).is_some());
/// assert!(from_nsecs_opt(86399, 1_999_999_999).is_some()); // a leap second after 23:59:59
/// assert!(from_nsecs_opt(86_400, 0).is_none());
/// assert!(from_nsecs_opt(86399, 2_000_000_000).is_none());
/// assert!(from_nsecs(0, 0).is_ok());
/// assert!(from_nsecs(86399, 999_999_999).is_ok());
/// assert!(from_nsecs(86399, 1_999_999_999).is_ok()); // a leap second after 23:59:59
/// assert_eq!(from_nsecs(86_400, 0), Err(Error::InvalidParameter));
/// assert_eq!(from_nsecs(86399, 2_000_000_000), Err(Error::InvalidParameter));
/// assert_eq!(from_nsecs(1, 1_999_999_999), Err(Error::DoesNotExist));
/// ```
#[inline]
#[must_use]
pub const fn from_num_seconds_from_midnight(secs: u32, nano: u32) -> Option<NaiveTime> {
if secs >= 86_400 || nano >= 2_000_000_000 || (nano >= 1_000_000_000 && secs % 60 != 59) {
return None;
pub const fn from_num_seconds_from_midnight(secs: u32, nano: u32) -> Result<NaiveTime, Error> {
if secs >= 86_400 || nano >= 2_000_000_000 {
return Err(INVALID);
} else if nano >= 1_000_000_000 && secs % 60 != 59 {
return Err(DOES_NOT_EXIST);
}
Some(NaiveTime { secs, frac: nano })
Ok(NaiveTime { secs, frac: nano })
}

/// Parses a string with the specified format string and returns a new `NaiveTime`.
Expand Down

0 comments on commit dd8e32e

Please sign in to comment.