Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Duration features part 1 #1327

Merged
merged 5 commits into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 74 additions & 31 deletions src/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

//! Temporal quantification

use core::ops::{Add, Div, Mul, Neg, Sub};
use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
use core::time::Duration as StdDuration;
use core::{fmt, i64};
#[cfg(feature = "std")]
Expand Down Expand Up @@ -50,7 +50,7 @@
/// ISO 8601 time duration with nanosecond precision.
///
/// This also allows for the negative duration; see individual methods for details.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
#[cfg_attr(feature = "rkyv", derive(Archive, Deserialize, Serialize))]
#[cfg_attr(
feature = "rkyv",
Expand Down Expand Up @@ -80,8 +80,15 @@
#[inline]
#[must_use]
pub fn weeks(weeks: i64) -> Duration {
let secs = weeks.checked_mul(SECS_PER_WEEK).expect("Duration::weeks out of bounds");
Duration::seconds(secs)
Duration::try_weeks(weeks).expect("Duration::weeks out of bounds")
}

/// Makes a new `Duration` with given number of weeks.
/// Equivalent to `Duration::seconds(weeks * 7 * 24 * 60 * 60)` with overflow checks.
/// Returns `None` when the duration is out of bounds.
#[inline]
pub fn try_weeks(weeks: i64) -> Option<Duration> {
weeks.checked_mul(SECS_PER_WEEK).and_then(Duration::try_seconds)
}

/// Makes a new `Duration` with given number of days.
Expand All @@ -90,8 +97,15 @@
#[inline]
#[must_use]
pub fn days(days: i64) -> Duration {
let secs = days.checked_mul(SECS_PER_DAY).expect("Duration::days out of bounds");
Duration::seconds(secs)
Duration::try_days(days).expect("Duration::days out of bounds")
}

/// Makes a new `Duration` with given number of days.
/// Equivalent to `Duration::seconds(days * 24 * 60 * 60)` with overflow checks.
/// Returns `None` when the duration is out of bounds.
#[inline]
pub fn try_days(days: i64) -> Option<Duration> {
days.checked_mul(SECS_PER_DAY).and_then(Duration::try_seconds)
}

/// Makes a new `Duration` with given number of hours.
Expand All @@ -100,8 +114,15 @@
#[inline]
#[must_use]
pub fn hours(hours: i64) -> Duration {
let secs = hours.checked_mul(SECS_PER_HOUR).expect("Duration::hours ouf of bounds");
Duration::seconds(secs)
Duration::try_hours(hours).expect("Duration::hours ouf of bounds")
}

/// Makes a new `Duration` with given number of hours.
/// Equivalent to `Duration::seconds(hours * 60 * 60)` with overflow checks.
/// Returns `None` when the duration is out of bounds.
#[inline]
pub fn try_hours(hours: i64) -> Option<Duration> {
hours.checked_mul(SECS_PER_HOUR).and_then(Duration::try_seconds)
}

/// Makes a new `Duration` with given number of minutes.
Expand All @@ -110,8 +131,15 @@
#[inline]
#[must_use]
pub fn minutes(minutes: i64) -> Duration {
let secs = minutes.checked_mul(SECS_PER_MINUTE).expect("Duration::minutes out of bounds");
Duration::seconds(secs)
Duration::try_minutes(minutes).expect("Duration::minutes out of bounds")
}

/// Makes a new `Duration` with given number of minutes.
/// Equivalent to `Duration::seconds(minutes * 60)` with overflow checks.
/// Returns `None` when the duration is out of bounds.
#[inline]
pub fn try_minutes(minutes: i64) -> Option<Duration> {
minutes.checked_mul(SECS_PER_MINUTE).and_then(Duration::try_seconds)
}

/// Makes a new `Duration` with given number of seconds.
Expand All @@ -120,11 +148,19 @@
#[inline]
#[must_use]
pub fn seconds(seconds: i64) -> Duration {
Duration::try_seconds(seconds).expect("Duration::seconds out of bounds")
}

/// Makes a new `Duration` with given number of seconds.
/// Returns `None` when the duration is more than `i64::MAX` milliseconds
/// or less than `i64::MIN` milliseconds.
#[inline]
pub fn try_seconds(seconds: i64) -> Option<Duration> {
let d = Duration { secs: seconds, nanos: 0 };
if d < MIN || d > MAX {
panic!("Duration::seconds out of bounds");
return None;

Check warning on line 161 in src/duration.rs

View check run for this annotation

Codecov / codecov/patch

src/duration.rs#L161

Added line #L161 was not covered by tests
}
d
Some(d)
}

/// Makes a new `Duration` with given number of milliseconds.
Expand Down Expand Up @@ -184,9 +220,9 @@
}

/// Returns the number of nanoseconds such that
/// `nanos_mod_sec() + num_seconds() * NANOS_PER_SEC` is the total number of
/// `subsec_nanos() + num_seconds() * NANOS_PER_SEC` is the total number of
/// nanoseconds in the duration.
const fn nanos_mod_sec(&self) -> i32 {
pub const fn subsec_nanos(&self) -> i32 {
if self.secs < 0 && self.nanos > 0 {
self.nanos - NANOS_PER_SEC
} else {
Expand All @@ -199,23 +235,23 @@
// A proper Duration will not overflow, because MIN and MAX are defined
// such that the range is exactly i64 milliseconds.
let secs_part = self.num_seconds() * MILLIS_PER_SEC;
let nanos_part = self.nanos_mod_sec() / NANOS_PER_MILLI;
let nanos_part = self.subsec_nanos() / NANOS_PER_MILLI;
secs_part + nanos_part as i64
}

/// Returns the total number of whole microseconds in the duration,
/// or `None` on overflow (exceeding 2^63 microseconds in either direction).
pub const fn num_microseconds(&self) -> Option<i64> {
let secs_part = try_opt!(self.num_seconds().checked_mul(MICROS_PER_SEC));
let nanos_part = self.nanos_mod_sec() / NANOS_PER_MICRO;
let nanos_part = self.subsec_nanos() / NANOS_PER_MICRO;
secs_part.checked_add(nanos_part as i64)
}

/// Returns the total number of whole nanoseconds in the duration,
/// or `None` on overflow (exceeding 2^63 nanoseconds in either direction).
pub const fn num_nanoseconds(&self) -> Option<i64> {
let secs_part = try_opt!(self.num_seconds().checked_mul(NANOS_PER_SEC as i64));
let nanos_part = self.nanos_mod_sec();
let nanos_part = self.subsec_nanos();
secs_part.checked_add(nanos_part as i64)
}

Expand Down Expand Up @@ -336,27 +372,29 @@
type Output = Duration;

fn add(self, rhs: Duration) -> Duration {
let mut secs = self.secs + rhs.secs;
let mut nanos = self.nanos + rhs.nanos;
if nanos >= NANOS_PER_SEC {
nanos -= NANOS_PER_SEC;
secs += 1;
}
Duration { secs, nanos }
self.checked_add(&rhs).expect("`Duration + Duration` overflowed")
}
}

impl Sub for Duration {
type Output = Duration;

fn sub(self, rhs: Duration) -> Duration {
let mut secs = self.secs - rhs.secs;
let mut nanos = self.nanos - rhs.nanos;
if nanos < 0 {
nanos += NANOS_PER_SEC;
secs -= 1;
}
Duration { secs, nanos }
self.checked_sub(&rhs).expect("`Duration - Duration` overflowed")
}
}

impl AddAssign for Duration {
fn add_assign(&mut self, rhs: Duration) {
let new = self.checked_add(&rhs).expect("`Duration + Duration` overflowed");
*self = new;
}
}

impl SubAssign for Duration {
fn sub_assign(&mut self, rhs: Duration) {
let new = self.checked_sub(&rhs).expect("`Duration - Duration` overflowed");
*self = new;
}
}

Expand Down Expand Up @@ -509,6 +547,11 @@
-(Duration::days(3) + Duration::seconds(70)),
Duration::days(-4) + Duration::seconds(86_400 - 70)
);

let mut d = Duration::default();
d += Duration::minutes(1);
d -= Duration::seconds(30);
assert_eq!(d, Duration::seconds(30));
}

#[test]
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 @@ -590,11 +590,11 @@ impl NaiveTime {
if frac >= 1_000_000_000 {
let rfrac = 2_000_000_000 - frac;
if rhs >= OldDuration::nanoseconds(i64::from(rfrac)) {
rhs = rhs - OldDuration::nanoseconds(i64::from(rfrac));
rhs -= OldDuration::nanoseconds(i64::from(rfrac));
secs += 1;
frac = 0;
} else if rhs < OldDuration::nanoseconds(-i64::from(frac)) {
rhs = rhs + OldDuration::nanoseconds(i64::from(frac));
rhs += OldDuration::nanoseconds(i64::from(frac));
frac = 0;
} else {
frac = (i64::from(frac) + rhs.num_nanoseconds().unwrap()) as u32;
Expand Down
Loading