Skip to content

Commit

Permalink
Add Duration::new
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Oct 2, 2023
1 parent d847576 commit afc42ea
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
17 changes: 17 additions & 0 deletions src/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,23 @@ pub(crate) const MAX: Duration = Duration {
};

impl Duration {
/// Makes a new `Duration` with given number of seconds and nanoseconds.
///
/// # Errors
///
/// Returns `None` when the duration is out of bounds, or if `nanos` ≥ 1,000,000,000.
pub(crate) const fn new(secs: i64, nanos: u32) -> Option<Duration> {
if secs < MIN.secs
|| secs > MAX.secs
|| nanos > 1_000_000_000
|| (secs == MAX.secs && nanos > MAX.nanos as u32)
|| (secs == MIN.secs && nanos < MIN.nanos as u32)
{
return None;
}
Some(Duration { secs, nanos: nanos as i32 })
}

/// Makes a new `Duration` with given number of weeks.
/// Equivalent to `Duration::seconds(weeks * 7 * 24 * 60 * 60)` with overflow checks.
/// Panics when the duration is out of bounds.
Expand Down
4 changes: 2 additions & 2 deletions src/naive/time/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1194,7 +1194,7 @@ impl Add<Duration> for NaiveTime {
// overflow during the conversion to `chrono::Duration`.
// But we limit to double that just in case `self` is a leap-second.
let secs = rhs.as_secs() % (2 * 24 * 60 * 60);
let d = OldDuration::from_std(Duration::new(secs, rhs.subsec_nanos())).unwrap();
let d = OldDuration::new(secs as i64, rhs.subsec_nanos()).unwrap();
self.overflowing_add_signed(d).0
}
}
Expand Down Expand Up @@ -1304,7 +1304,7 @@ impl Sub<Duration> for NaiveTime {
// overflow during the conversion to `chrono::Duration`.
// But we limit to double that just in case `self` is a leap-second.
let secs = rhs.as_secs() % (2 * 24 * 60 * 60);
let d = OldDuration::from_std(Duration::new(secs, rhs.subsec_nanos())).unwrap();
let d = OldDuration::new(secs as i64, rhs.subsec_nanos()).unwrap();
self.overflowing_sub_signed(d).0
}
}
Expand Down

0 comments on commit afc42ea

Please sign in to comment.