// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
//! Temporal quantification
#[cfg(all(not(feature = "std"), feature = "core-error"))] use core::error::Error; use core::fmt; use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign}; use core::time::Duration; #[cfg(feature = "std")] use std::error::Error;
/// The number of nanoseconds in a microsecond. const NANOS_PER_MICRO: i32 = 1000; /// The number of nanoseconds in a millisecond. const NANOS_PER_MILLI: i32 = 1_000_000; /// The number of nanoseconds in seconds. pub(crate) const NANOS_PER_SEC: i32 = 1_000_000_000; /// The number of microseconds per second. const MICROS_PER_SEC: i64 = 1_000_000; /// The number of milliseconds per second. const MILLIS_PER_SEC: i64 = 1000; /// The number of seconds in a minute. const SECS_PER_MINUTE: i64 = 60; /// The number of seconds in an hour. const SECS_PER_HOUR: i64 = 3600; /// The number of (non-leap) seconds in days. const SECS_PER_DAY: i64 = 86_400; /// The number of (non-leap) seconds in a week. const SECS_PER_WEEK: i64 = 604_800;
/// Time duration with nanosecond precision. /// /// This also allows for negative durations; see individual methods for details. /// /// A `TimeDelta` is represented internally as a complement of seconds and /// nanoseconds. The range is restricted to that of `i64` milliseconds, with the /// minimum value notably being set to `-i64::MAX` rather than allowing the full /// range of `i64::MIN`. This is to allow easy flipping of sign, so that for /// instance `abs()` can be called without any checks. #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] #[cfg_attr(
any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"),
derive(Archive, Deserialize, Serialize),
archive(compare(PartialEq, PartialOrd)),
archive_attr(derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash))
)] #[cfg_attr(feature = "rkyv-validation", archive(check_bytes))] pubstruct TimeDelta {
secs: i64,
nanos: i32, // Always 0 <= nanos < NANOS_PER_SEC
}
/// The maximum possible `TimeDelta`: `i64::MAX` milliseconds. pub(crate) const MAX: TimeDelta = TimeDelta {
secs: i64::MAX / MILLIS_PER_SEC,
nanos: (i64::MAX % MILLIS_PER_SEC) as i32 * NANOS_PER_MILLI,
};
impl TimeDelta { /// Makes a new `TimeDelta` with given number of seconds and nanoseconds. /// /// # Errors /// /// Returns `None` when the duration is out of bounds, or if `nanos` ≥ 1,000,000,000. pubconstfn new(secs: i64, nanos: u32) -> Option<TimeDelta> { 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(TimeDelta { secs, nanos: nanos as i32 })
}
/// Makes a new `TimeDelta` with the given number of weeks. /// /// Equivalent to `TimeDelta::seconds(weeks * 7 * 24 * 60 * 60)` with /// overflow checks. /// /// # Panics /// /// Panics when the duration is out of bounds. #[inline] #[must_use] pubconstfn weeks(weeks: i64) -> TimeDelta {
expect(TimeDelta::try_weeks(weeks), "TimeDelta::weeks out of bounds")
}
/// Makes a new `TimeDelta` with the given number of weeks. /// /// Equivalent to `TimeDelta::try_seconds(weeks * 7 * 24 * 60 * 60)` with /// overflow checks. /// /// # Errors /// /// Returns `None` when the `TimeDelta` would be out of bounds. #[inline] pubconstfn try_weeks(weeks: i64) -> Option<TimeDelta> {
TimeDelta::try_seconds(try_opt!(weeks.checked_mul(SECS_PER_WEEK)))
}
/// Makes a new `TimeDelta` with the given number of days. /// /// Equivalent to `TimeDelta::seconds(days * 24 * 60 * 60)` with overflow /// checks. /// /// # Panics /// /// Panics when the `TimeDelta` would be out of bounds. #[inline] #[must_use] pubconstfn days(days: i64) -> TimeDelta {
expect(TimeDelta::try_days(days), "TimeDelta::days out of bounds")
}
/// Makes a new `TimeDelta` with the given number of days. /// /// Equivalent to `TimeDelta::try_seconds(days * 24 * 60 * 60)` with overflow /// checks. /// /// # Errors /// /// Returns `None` when the `TimeDelta` would be out of bounds. #[inline] pubconstfn try_days(days: i64) -> Option<TimeDelta> {
TimeDelta::try_seconds(try_opt!(days.checked_mul(SECS_PER_DAY)))
}
/// Makes a new `TimeDelta` with the given number of hours. /// /// Equivalent to `TimeDelta::seconds(hours * 60 * 60)` with overflow checks. /// /// # Panics /// /// Panics when the `TimeDelta` would be out of bounds. #[inline] #[must_use] pubconstfn hours(hours: i64) -> TimeDelta {
expect(TimeDelta::try_hours(hours), "TimeDelta::hours out of bounds")
}
/// Makes a new `TimeDelta` with the given number of hours. /// /// Equivalent to `TimeDelta::try_seconds(hours * 60 * 60)` with overflow checks. /// /// # Errors /// /// Returns `None` when the `TimeDelta` would be out of bounds. #[inline] pubconstfn try_hours(hours: i64) -> Option<TimeDelta> {
TimeDelta::try_seconds(try_opt!(hours.checked_mul(SECS_PER_HOUR)))
}
/// Makes a new `TimeDelta` with the given number of minutes. /// /// Equivalent to `TimeDelta::seconds(minutes * 60)` with overflow checks. /// /// # Panics /// /// Panics when the `TimeDelta` would be out of bounds. #[inline] #[must_use] pubconstfn minutes(minutes: i64) -> TimeDelta {
expect(TimeDelta::try_minutes(minutes), "TimeDelta::minutes out of bounds")
}
/// Makes a new `TimeDelta` with the given number of minutes. /// /// Equivalent to `TimeDelta::try_seconds(minutes * 60)` with overflow checks. /// /// # Errors /// /// Returns `None` when the `TimeDelta` would be out of bounds. #[inline] pubconstfn try_minutes(minutes: i64) -> Option<TimeDelta> {
TimeDelta::try_seconds(try_opt!(minutes.checked_mul(SECS_PER_MINUTE)))
}
/// Makes a new `TimeDelta` with the given number of seconds. /// /// # Panics /// /// Panics when `seconds` is more than `i64::MAX / 1_000` or less than `-i64::MAX / 1_000` /// (in this context, this is the same as `i64::MIN / 1_000` due to rounding). #[inline] #[must_use] pubconstfn seconds(seconds: i64) -> TimeDelta {
expect(TimeDelta::try_seconds(seconds), "TimeDelta::seconds out of bounds")
}
/// Makes a new `TimeDelta` with the given number of seconds. /// /// # Errors /// /// Returns `None` when `seconds` is more than `i64::MAX / 1_000` or less than /// `-i64::MAX / 1_000` (in this context, this is the same as `i64::MIN / 1_000` due to /// rounding). #[inline] pubconstfn try_seconds(seconds: i64) -> Option<TimeDelta> {
TimeDelta::new(seconds, 0)
}
/// Makes a new `TimeDelta` with the given number of milliseconds. /// /// # Panics /// /// Panics when the `TimeDelta` would be out of bounds, i.e. when `milliseconds` is more than /// `i64::MAX` or less than `-i64::MAX`. Notably, this is not the same as `i64::MIN`. #[inline] pubconstfn milliseconds(milliseconds: i64) -> TimeDelta {
expect(TimeDelta::try_milliseconds(milliseconds), "TimeDelta::milliseconds out of bounds")
}
/// Makes a new `TimeDelta` with the given number of milliseconds. /// /// # Errors /// /// Returns `None` the `TimeDelta` would be out of bounds, i.e. when `milliseconds` is more /// than `i64::MAX` or less than `-i64::MAX`. Notably, this is not the same as `i64::MIN`. #[inline] pubconstfn try_milliseconds(milliseconds: i64) -> Option<TimeDelta> { // We don't need to compare against MAX, as this function accepts an // i64, and MAX is aligned to i64::MAX milliseconds. if milliseconds < -i64::MAX { return None;
} let (secs, millis) = div_mod_floor_64(milliseconds, MILLIS_PER_SEC); let d = TimeDelta { secs, nanos: millis as i32 * NANOS_PER_MILLI };
Some(d)
}
/// Makes a new `TimeDelta` with the given number of microseconds. /// /// The number of microseconds acceptable by this constructor is less than /// the total number that can actually be stored in a `TimeDelta`, so it is /// not possible to specify a value that would be out of bounds. This /// function is therefore infallible. #[inline] pubconstfn microseconds(microseconds: i64) -> TimeDelta { let (secs, micros) = div_mod_floor_64(microseconds, MICROS_PER_SEC); let nanos = micros as i32 * NANOS_PER_MICRO;
TimeDelta { secs, nanos }
}
/// Makes a new `TimeDelta` with the given number of nanoseconds. /// /// The number of nanoseconds acceptable by this constructor is less than /// the total number that can actually be stored in a `TimeDelta`, so it is /// not possible to specify a value that would be out of bounds. This /// function is therefore infallible. #[inline] pubconstfn nanoseconds(nanos: i64) -> TimeDelta { let (secs, nanos) = div_mod_floor_64(nanos, NANOS_PER_SEC as i64);
TimeDelta { secs, nanos: nanos as i32 }
}
/// Returns the total number of whole weeks in the `TimeDelta`. #[inline] pubconstfn num_weeks(&self) -> i64 { self.num_days() / 7
}
/// Returns the total number of whole days in the `TimeDelta`. #[inline] pubconstfn num_days(&self) -> i64 { self.num_seconds() / SECS_PER_DAY
}
/// Returns the total number of whole hours in the `TimeDelta`. #[inline] pubconstfn num_hours(&self) -> i64 { self.num_seconds() / SECS_PER_HOUR
}
/// Returns the total number of whole minutes in the `TimeDelta`. #[inline] pubconstfn num_minutes(&self) -> i64 { self.num_seconds() / SECS_PER_MINUTE
}
/// Returns the total number of whole seconds in the `TimeDelta`. pubconstfn num_seconds(&self) -> i64 { // If secs is negative, nanos should be subtracted from the duration. ifself.secs < 0 && self.nanos > 0 { self.secs + 1 } else { self.secs }
}
/// Returns the fractional number of seconds in the `TimeDelta`. pubfn as_seconds_f64(self) -> f64 { self.secs as f64 + self.nanos as f64 / NANOS_PER_SEC as f64
}
/// Returns the fractional number of seconds in the `TimeDelta`. pubfn as_seconds_f32(self) -> f32 { self.secs as f32 + self.nanos as f32 / NANOS_PER_SEC as f32
}
/// Returns the total number of whole milliseconds in the `TimeDelta`. pubconstfn num_milliseconds(&self) -> i64 { // A proper TimeDelta will not overflow, because MIN and MAX are defined such // that the range is within the bounds of an i64, from -i64::MAX through to // +i64::MAX inclusive. Notably, i64::MIN is excluded from this range. let secs_part = self.num_seconds() * MILLIS_PER_SEC; let nanos_part = self.subsec_nanos() / NANOS_PER_MILLI;
secs_part + nanos_part as i64
}
/// Returns the number of milliseconds in the fractional part of the duration. /// /// This is the number of milliseconds such that /// `subsec_millis() + num_seconds() * 1_000` is the truncated number of /// milliseconds in the duration. pubconstfn subsec_millis(&self) -> i32 { self.subsec_nanos() / NANOS_PER_MILLI
}
/// Returns the total number of whole microseconds in the `TimeDelta`, /// or `None` on overflow (exceeding 2^63 microseconds in either direction). pubconstfn num_microseconds(&self) -> Option<i64> { let secs_part = try_opt!(self.num_seconds().checked_mul(MICROS_PER_SEC)); let nanos_part = self.subsec_nanos() / NANOS_PER_MICRO;
secs_part.checked_add(nanos_part as i64)
}
/// Returns the number of microseconds in the fractional part of the duration. /// /// This is the number of microseconds such that /// `subsec_micros() + num_seconds() * 1_000_000` is the truncated number of /// microseconds in the duration. pubconstfn subsec_micros(&self) -> i32 { self.subsec_nanos() / NANOS_PER_MICRO
}
/// Returns the total number of whole nanoseconds in the `TimeDelta`, /// or `None` on overflow (exceeding 2^63 nanoseconds in either direction). pubconstfn num_nanoseconds(&self) -> Option<i64> { let secs_part = try_opt!(self.num_seconds().checked_mul(NANOS_PER_SEC as i64)); let nanos_part = self.subsec_nanos();
secs_part.checked_add(nanos_part as i64)
}
/// Returns the number of nanoseconds in the fractional part of the duration. /// /// This is the number of nanoseconds such that /// `subsec_nanos() + num_seconds() * 1_000_000_000` is the total number of /// nanoseconds in the `TimeDelta`. pubconstfn subsec_nanos(&self) -> i32 { ifself.secs < 0 && self.nanos > 0 { self.nanos - NANOS_PER_SEC } else { self.nanos }
}
/// Add two `TimeDelta`s, returning `None` if overflow occurred. #[must_use] pubconstfn checked_add(&self, rhs: &TimeDelta) -> Option<TimeDelta> { // No overflow checks here because we stay comfortably within the range of an `i64`. // Range checks happen in `TimeDelta::new`. letmut secs = self.secs + rhs.secs; letmut nanos = self.nanos + rhs.nanos; if nanos >= NANOS_PER_SEC {
nanos -= NANOS_PER_SEC;
secs += 1;
}
TimeDelta::new(secs, nanos as u32)
}
/// Subtract two `TimeDelta`s, returning `None` if overflow occurred. #[must_use] pubconstfn checked_sub(&self, rhs: &TimeDelta) -> Option<TimeDelta> { // No overflow checks here because we stay comfortably within the range of an `i64`. // Range checks happen in `TimeDelta::new`. letmut secs = self.secs - rhs.secs; letmut nanos = self.nanos - rhs.nanos; if nanos < 0 {
nanos += NANOS_PER_SEC;
secs -= 1;
}
TimeDelta::new(secs, nanos as u32)
}
/// Multiply a `TimeDelta` with a i32, returning `None` if overflow occurred. #[must_use] pubconstfn checked_mul(&self, rhs: i32) -> Option<TimeDelta> { // Multiply nanoseconds as i64, because it cannot overflow that way. let total_nanos = self.nanos as i64 * rhs as i64; let (extra_secs, nanos) = div_mod_floor_64(total_nanos, NANOS_PER_SEC as i64); // Multiply seconds as i128 to prevent overflow let secs: i128 = self.secs as i128 * rhs as i128 + extra_secs as i128; if secs <= i64::MIN as i128 || secs >= i64::MAX as i128 { return None;
};
Some(TimeDelta { secs: secs as i64, nanos: nanos as i32 })
}
/// Divide a `TimeDelta` with a i32, returning `None` if dividing by 0. #[must_use] pubconstfn checked_div(&self, rhs: i32) -> Option<TimeDelta> { if rhs == 0 { return None;
} let secs = self.secs / rhs as i64; let carry = self.secs % rhs as i64; let extra_nanos = carry * NANOS_PER_SEC as i64 / rhs as i64; let nanos = self.nanos / rhs + extra_nanos as i32;
/// The minimum possible `TimeDelta`: `-i64::MAX` milliseconds. #[deprecated(since = "0.4.39", note = "Use `TimeDelta::MIN` instead")] #[inline] pubconstfn min_value() -> TimeDelta {
MIN
}
/// The maximum possible `TimeDelta`: `i64::MAX` milliseconds. #[deprecated(since = "0.4.39", note = "Use `TimeDelta::MAX` instead")] #[inline] pubconstfn max_value() -> TimeDelta {
MAX
}
/// A `TimeDelta` where the stored seconds and nanoseconds are equal to zero. #[inline] pubconstfn zero() -> TimeDelta {
TimeDelta { secs: 0, nanos: 0 }
}
/// Creates a `TimeDelta` object from `std::time::Duration` /// /// This function errors when original duration is larger than the maximum /// value supported for this type. pubconstfn from_std(duration: Duration) -> Result<TimeDelta, OutOfRangeError> { // We need to check secs as u64 before coercing to i64 if duration.as_secs() > MAX.secs as u64 { return Err(OutOfRangeError(()));
} match TimeDelta::new(duration.as_secs() as i64, duration.subsec_nanos()) {
Some(d) => Ok(d),
None => Err(OutOfRangeError(())),
}
}
/// Creates a `std::time::Duration` object from a `TimeDelta`. /// /// This function errors when duration is less than zero. As standard /// library implementation is limited to non-negative values. pubconstfn to_std(&self) -> Result<Duration, OutOfRangeError> { ifself.secs < 0 { return Err(OutOfRangeError(()));
}
Ok(Duration::new(self.secs as u64, self.nanos as u32))
}
impl fmt::Display for TimeDelta { /// Format a `TimeDelta` using the [ISO 8601] format /// /// [ISO 8601]: https://en.wikipedia.org/wiki/ISO_8601#Durations fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // technically speaking, negative duration is not valid ISO 8601, // but we need to print it anyway. let (abs, sign) = ifself.secs < 0 { (-*self, "-") } else { (*self, "") };
write!(f, "{sign}P")?; // Plenty of ways to encode an empty string. `P0D` is short and not too strange. if abs.secs == 0 && abs.nanos == 0 { return f.write_str("0D");
}
f.write_fmt(format_args!("T{}", abs.secs))?;
if abs.nanos > 0 { // Count the number of significant digits, while removing all trailing zero's. letmut figures = 9usize; letmut fraction_digits = abs.nanos; loop { let div = fraction_digits / 10; let last_digit = fraction_digits % 10; if last_digit != 0 { break;
}
fraction_digits = div;
figures -= 1;
}
f.write_fmt(format_args!(".{fraction_digits:0figures$}"))?;
}
f.write_str("S")?;
Ok(())
}
}
/// Represents error when converting `TimeDelta` to/from a standard library /// implementation /// /// The `std::time::Duration` supports a range from zero to `u64::MAX` /// *seconds*, while this module supports signed range of up to /// `i64::MAX` of *milliseconds*. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pubstruct OutOfRangeError(());
impl fmt::Display for OutOfRangeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Source duration value is out of range for the target type")
}
}
#[cfg(any(feature = "std", feature = "core-error"))] impl Error for OutOfRangeError { #[allow(deprecated)] fn description(&self) -> &str { "out of range error"
}
}
impl<'de> Deserialize<'de> for TimeDelta { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { let (secs, nanos) = <(i64, i32) as Deserialize>::deserialize(deserializer)?;
TimeDelta::new(secs, nanos as u32).ok_or(Error::custom("TimeDelta out of bounds"))
}
}
#[cfg(test)] mod tests { usesuper::{super::MAX, TimeDelta};
#[test] #[should_panic(expected = "TimeDelta::seconds out of bounds")] fn test_duration_seconds_max_overflow_panic() { let _ = TimeDelta::seconds(i64::MAX / 1_000 + 1);
}
#[test] fn test_duration_seconds_min_allowed() { let duration = TimeDelta::try_seconds(i64::MIN / 1_000).unwrap(); // Same as -i64::MAX / 1_000 due to rounding
assert_eq!(duration.num_seconds(), i64::MIN / 1_000); // Same as -i64::MAX / 1_000 due to rounding
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
-i64::MAX as i128 / 1_000 * 1_000_000_000
);
}
#[test] fn test_duration_milliseconds_max_allowed() { // The maximum number of milliseconds acceptable through the constructor is // equal to the number that can be stored in a TimeDelta. let duration = TimeDelta::try_milliseconds(i64::MAX).unwrap();
assert_eq!(duration.num_milliseconds(), i64::MAX);
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
i64::MAX as i128 * 1_000_000
);
}
#[test] fn test_duration_milliseconds_max_overflow() { // Here we ensure that trying to add one millisecond to the maximum storable // value will fail.
assert!(
TimeDelta::try_milliseconds(i64::MAX)
.unwrap()
.checked_add(&TimeDelta::try_milliseconds(1).unwrap())
.is_none()
);
}
#[test] fn test_duration_milliseconds_min_allowed() { // The minimum number of milliseconds acceptable through the constructor is // not equal to the number that can be stored in a TimeDelta - there is a // difference of one (i64::MIN vs -i64::MAX). let duration = TimeDelta::try_milliseconds(-i64::MAX).unwrap();
assert_eq!(duration.num_milliseconds(), -i64::MAX);
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
-i64::MAX as i128 * 1_000_000
);
}
#[test] fn test_duration_milliseconds_min_underflow() { // Here we ensure that trying to subtract one millisecond from the minimum // storable value will fail.
assert!(
TimeDelta::try_milliseconds(-i64::MAX)
.unwrap()
.checked_sub(&TimeDelta::try_milliseconds(1).unwrap())
.is_none()
);
}
#[test] #[should_panic(expected = "TimeDelta::milliseconds out of bounds")] fn test_duration_milliseconds_min_underflow_panic() { // Here we ensure that trying to create a value one millisecond below the // minimum storable value will fail. This test is necessary because the // storable range is -i64::MAX, but the constructor type of i64 will allow // i64::MIN, which is one value below. let _ = TimeDelta::milliseconds(i64::MIN); // Same as -i64::MAX - 1
}
// overflow checks const MICROS_PER_DAY: i64 = 86_400_000_000;
assert_eq!(
TimeDelta::try_days(i64::MAX / MICROS_PER_DAY).unwrap().num_microseconds(),
Some(i64::MAX / MICROS_PER_DAY * MICROS_PER_DAY)
);
assert_eq!(
TimeDelta::try_days(-i64::MAX / MICROS_PER_DAY).unwrap().num_microseconds(),
Some(-i64::MAX / MICROS_PER_DAY * MICROS_PER_DAY)
);
assert_eq!(
TimeDelta::try_days(i64::MAX / MICROS_PER_DAY + 1).unwrap().num_microseconds(),
None
);
assert_eq!(
TimeDelta::try_days(-i64::MAX / MICROS_PER_DAY - 1).unwrap().num_microseconds(),
None
);
} #[test] fn test_duration_microseconds_max_allowed() { // The number of microseconds acceptable through the constructor is far // fewer than the number that can actually be stored in a TimeDelta, so this // is not a particular insightful test. let duration = TimeDelta::microseconds(i64::MAX);
assert_eq!(duration.num_microseconds(), Some(i64::MAX));
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
i64::MAX as i128 * 1_000
); // Here we create a TimeDelta with the maximum possible number of // microseconds by creating a TimeDelta with the maximum number of // milliseconds and then checking that the number of microseconds matches // the storage limit. let duration = TimeDelta::try_milliseconds(i64::MAX).unwrap();
assert!(duration.num_microseconds().is_none());
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
i64::MAX as i128 * 1_000_000
);
} #[test] fn test_duration_microseconds_max_overflow() { // This test establishes that a TimeDelta can store more microseconds than // are representable through the return of duration.num_microseconds(). let duration = TimeDelta::microseconds(i64::MAX) + TimeDelta::microseconds(1);
assert!(duration.num_microseconds().is_none());
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
(i64::MAX as i128 + 1) * 1_000
); // Here we ensure that trying to add one microsecond to the maximum storable // value will fail.
assert!(
TimeDelta::try_milliseconds(i64::MAX)
.unwrap()
.checked_add(&TimeDelta::microseconds(1))
.is_none()
);
} #[test] fn test_duration_microseconds_min_allowed() { // The number of microseconds acceptable through the constructor is far // fewer than the number that can actually be stored in a TimeDelta, so this // is not a particular insightful test. let duration = TimeDelta::microseconds(i64::MIN);
assert_eq!(duration.num_microseconds(), Some(i64::MIN));
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
i64::MIN as i128 * 1_000
); // Here we create a TimeDelta with the minimum possible number of // microseconds by creating a TimeDelta with the minimum number of // milliseconds and then checking that the number of microseconds matches // the storage limit. let duration = TimeDelta::try_milliseconds(-i64::MAX).unwrap();
assert!(duration.num_microseconds().is_none());
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
-i64::MAX as i128 * 1_000_000
);
} #[test] fn test_duration_microseconds_min_underflow() { // This test establishes that a TimeDelta can store more microseconds than // are representable through the return of duration.num_microseconds(). let duration = TimeDelta::microseconds(i64::MIN) - TimeDelta::microseconds(1);
assert!(duration.num_microseconds().is_none());
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
(i64::MIN as i128 - 1) * 1_000
); // Here we ensure that trying to subtract one microsecond from the minimum // storable value will fail.
assert!(
TimeDelta::try_milliseconds(-i64::MAX)
.unwrap()
.checked_sub(&TimeDelta::microseconds(1))
.is_none()
);
}
// overflow checks const NANOS_PER_DAY: i64 = 86_400_000_000_000;
assert_eq!(
TimeDelta::try_days(i64::MAX / NANOS_PER_DAY).unwrap().num_nanoseconds(),
Some(i64::MAX / NANOS_PER_DAY * NANOS_PER_DAY)
);
assert_eq!(
TimeDelta::try_days(-i64::MAX / NANOS_PER_DAY).unwrap().num_nanoseconds(),
Some(-i64::MAX / NANOS_PER_DAY * NANOS_PER_DAY)
);
assert_eq!(
TimeDelta::try_days(i64::MAX / NANOS_PER_DAY + 1).unwrap().num_nanoseconds(),
None
);
assert_eq!(
TimeDelta::try_days(-i64::MAX / NANOS_PER_DAY - 1).unwrap().num_nanoseconds(),
None
);
} #[test] fn test_duration_nanoseconds_max_allowed() { // The number of nanoseconds acceptable through the constructor is far fewer // than the number that can actually be stored in a TimeDelta, so this is not // a particular insightful test. let duration = TimeDelta::nanoseconds(i64::MAX);
assert_eq!(duration.num_nanoseconds(), Some(i64::MAX));
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
i64::MAX as i128
); // Here we create a TimeDelta with the maximum possible number of nanoseconds // by creating a TimeDelta with the maximum number of milliseconds and then // checking that the number of nanoseconds matches the storage limit. let duration = TimeDelta::try_milliseconds(i64::MAX).unwrap();
assert!(duration.num_nanoseconds().is_none());
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
i64::MAX as i128 * 1_000_000
);
}
#[test] fn test_duration_nanoseconds_max_overflow() { // This test establishes that a TimeDelta can store more nanoseconds than are // representable through the return of duration.num_nanoseconds(). let duration = TimeDelta::nanoseconds(i64::MAX) + TimeDelta::nanoseconds(1);
assert!(duration.num_nanoseconds().is_none());
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
i64::MAX as i128 + 1
); // Here we ensure that trying to add one nanosecond to the maximum storable // value will fail.
assert!(
TimeDelta::try_milliseconds(i64::MAX)
.unwrap()
.checked_add(&TimeDelta::nanoseconds(1))
.is_none()
);
}
#[test] fn test_duration_nanoseconds_min_allowed() { // The number of nanoseconds acceptable through the constructor is far fewer // than the number that can actually be stored in a TimeDelta, so this is not // a particular insightful test. let duration = TimeDelta::nanoseconds(i64::MIN);
assert_eq!(duration.num_nanoseconds(), Some(i64::MIN));
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
i64::MIN as i128
); // Here we create a TimeDelta with the minimum possible number of nanoseconds // by creating a TimeDelta with the minimum number of milliseconds and then // checking that the number of nanoseconds matches the storage limit. let duration = TimeDelta::try_milliseconds(-i64::MAX).unwrap();
assert!(duration.num_nanoseconds().is_none());
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
-i64::MAX as i128 * 1_000_000
);
}
#[test] fn test_duration_nanoseconds_min_underflow() { // This test establishes that a TimeDelta can store more nanoseconds than are // representable through the return of duration.num_nanoseconds(). let duration = TimeDelta::nanoseconds(i64::MIN) - TimeDelta::nanoseconds(1);
assert!(duration.num_nanoseconds().is_none());
assert_eq!(
duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
i64::MIN as i128 - 1
); // Here we ensure that trying to subtract one nanosecond from the minimum // storable value will fail.
assert!(
TimeDelta::try_milliseconds(-i64::MAX)
.unwrap()
.checked_sub(&TimeDelta::nanoseconds(1))
.is_none()
);
}
#[test] fn test_max() {
assert_eq!(
MAX.secs as i128 * 1_000_000_000 + MAX.nanos as i128,
i64::MAX as i128 * 1_000_000
);
assert_eq!(MAX, TimeDelta::try_milliseconds(i64::MAX).unwrap());
assert_eq!(MAX.num_milliseconds(), i64::MAX);
assert_eq!(MAX.num_microseconds(), None);
assert_eq!(MAX.num_nanoseconds(), None);
}
#[test] fn test_min() {
assert_eq!(
MIN.secs as i128 * 1_000_000_000 + MIN.nanos as i128,
-i64::MAX as i128 * 1_000_000
);
assert_eq!(MIN, TimeDelta::try_milliseconds(-i64::MAX).unwrap());
assert_eq!(MIN.num_milliseconds(), -i64::MAX);
assert_eq!(MIN.num_microseconds(), None);
assert_eq!(MIN.num_nanoseconds(), None);
}
#[test] fn test_duration_ord() { let milliseconds = |ms| TimeDelta::try_milliseconds(ms).unwrap();
// the format specifier should have no effect on `TimeDelta`
assert_eq!(
format!( "{:30}",
TimeDelta::try_days(1).unwrap() + TimeDelta::try_milliseconds(2345).unwrap()
), "PT86402.345S"
);
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.