Struct hifitime::Duration

source ·
#[repr(C)]
pub struct Duration { /* private fields */ }
Expand description

Defines generally usable durations for nanosecond precision valid for 32,768 centuries in either direction, and only on 80 bits / 10 octets.

Important conventions:

  1. The negative durations can be mentally modeled “BC” years. One hours before 01 Jan 0000, it was “-1” years but 365 days and 23h into the current day. It was decided that the nanoseconds corresponds to the nanoseconds into the current century. In other words, a duration with centuries = -1 and nanoseconds = 0 is a greater duration (further from zero) than centuries = -1 and nanoseconds = 1. Duration zero minus one nanosecond returns a century of -1 and a nanosecond set to the number of nanoseconds in one century minus one. That difference is exactly 1 nanoseconds, where the former duration is “closer to zero” than the latter. As such, the largest negative duration that can be represented sets the centuries to i16::MAX and its nanoseconds to NANOSECONDS_PER_CENTURY.
  2. It was also decided that opposite durations are equal, e.g. -15 minutes == 15 minutes. If the direction of time matters, use the signum function.

Implementations§

source§

impl Duration

source

pub fn new(centuries: i16, nanoseconds: u64) -> Self

👎Deprecated since 3.6.0: Prefer from_parts()

Builds a new duration from the number of centuries and the number of nanoseconds

source

pub fn from_parts(centuries: i16, nanoseconds: u64) -> Self

Create a normalized duration from its parts

source

pub fn from_total_nanoseconds(nanos: i128) -> Self

Converts the total nanoseconds as i128 into this Duration (saving 48 bits)

source

pub fn from_truncated_nanoseconds(nanos: i64) -> Self

Create a new duration from the truncated nanoseconds (+/- 2927.1 years of duration)

source

pub fn from_f64(value: f64, unit: Unit) -> Self

Creates a new duration from the provided unit

source

pub fn from_days(value: f64) -> Self

Creates a new duration from the provided number of days

source

pub fn from_hours(value: f64) -> Self

Creates a new duration from the provided number of hours

source

pub fn from_seconds(value: f64) -> Self

Creates a new duration from the provided number of seconds

source

pub fn from_milliseconds(value: f64) -> Self

Creates a new duration from the provided number of milliseconds

source

pub fn from_microseconds(value: f64) -> Self

Creates a new duration from the provided number of microsecond

source

pub fn from_nanoseconds(value: f64) -> Self

Creates a new duration from the provided number of nanoseconds

source

pub fn compose( sign: i8, days: u64, hours: u64, minutes: u64, seconds: u64, milliseconds: u64, microseconds: u64, nanoseconds: u64 ) -> Self

Creates a new duration from its parts. Set the sign to a negative number for the duration to be negative.

source

pub fn compose_f64( sign: i8, days: f64, hours: f64, minutes: f64, seconds: f64, milliseconds: f64, microseconds: f64, nanoseconds: f64 ) -> Self

Creates a new duration from its parts. Set the sign to a negative number for the duration to be negative.

source

pub fn from_tz_offset(sign: i8, hours: i64, minutes: i64) -> Self

Initializes a Duration from a timezone offset

source§

impl Duration

source

pub const fn to_parts(&self) -> (i16, u64)

Returns the centuries and nanoseconds of this duration NOTE: These items are not public to prevent incorrect durations from being created by modifying the values of the structure directly.

source

pub fn total_nanoseconds(&self) -> i128

Returns the total nanoseconds in a signed 128 bit integer

source

pub fn try_truncated_nanoseconds(&self) -> Result<i64, Errors>

Returns the truncated nanoseconds in a signed 64 bit integer, if the duration fits.

source

pub fn truncated_nanoseconds(&self) -> i64

Returns the truncated nanoseconds in a signed 64 bit integer, if the duration fits. WARNING: This function will NOT fail and will return the i64::MIN or i64::MAX depending on the sign of the centuries if the Duration does not fit on aa i64

source

pub fn to_seconds(&self) -> f64

Returns this duration in seconds f64. For high fidelity comparisons, it is recommended to keep using the Duration structure.

source

pub fn to_unit(&self, unit: Unit) -> f64

source

pub fn abs(&self) -> Self

Returns the absolute value of this duration

source

pub const fn signum(&self) -> i8

Returns the sign of this duration

  • 0 if the number is zero
  • 1 if the number is positive
  • -1 if the number is negative
source

pub fn decompose(&self) -> (i8, u64, u64, u64, u64, u64, u64, u64)

Decomposes a Duration in its sign, days, hours, minutes, seconds, ms, us, ns

source

pub fn floor(&self, duration: Self) -> Self

Floors this duration to the closest duration from the bottom

Example
use hifitime::{Duration, TimeUnits};

let two_hours_three_min = 2.hours() + 3.minutes();
assert_eq!(two_hours_three_min.floor(1.hours()), 2.hours());
assert_eq!(two_hours_three_min.floor(30.minutes()), 2.hours());
// This is zero because we floor by a duration longer than the current duration, rounding it down
assert_eq!(two_hours_three_min.floor(4.hours()), 0.hours());
assert_eq!(two_hours_three_min.floor(1.seconds()), two_hours_three_min);
assert_eq!(two_hours_three_min.floor(1.hours() + 1.minutes()), 2.hours() + 2.minutes());
assert_eq!(two_hours_three_min.floor(1.hours() + 5.minutes()), 1.hours() + 5.minutes());
source

pub fn ceil(&self, duration: Self) -> Self

Ceils this duration to the closest provided duration

This simply floors then adds the requested duration

Example
use hifitime::{Duration, TimeUnits};

let two_hours_three_min = 2.hours() + 3.minutes();
assert_eq!(two_hours_three_min.ceil(1.hours()), 3.hours());
assert_eq!(two_hours_three_min.ceil(30.minutes()), 2.hours() + 30.minutes());
assert_eq!(two_hours_three_min.ceil(4.hours()), 4.hours());
assert_eq!(two_hours_three_min.ceil(1.seconds()), two_hours_three_min + 1.seconds());
assert_eq!(two_hours_three_min.ceil(1.hours() + 5.minutes()), 2.hours() + 10.minutes());
source

pub fn round(&self, duration: Self) -> Self

Rounds this duration to the closest provided duration

This performs both a ceil and floor and returns the value which is the closest to current one.

Example
use hifitime::{Duration, TimeUnits};

let two_hours_three_min = 2.hours() + 3.minutes();
assert_eq!(two_hours_three_min.round(1.hours()), 2.hours());
assert_eq!(two_hours_three_min.round(30.minutes()), 2.hours());
assert_eq!(two_hours_three_min.round(4.hours()), 4.hours());
assert_eq!(two_hours_three_min.round(1.seconds()), two_hours_three_min);
assert_eq!(two_hours_three_min.round(1.hours() + 5.minutes()), 2.hours() + 10.minutes());
source

pub fn approx(&self) -> Self

Rounds this duration to the largest units represented in this duration.

This is useful to provide an approximate human duration. Under the hood, this function uses round, so the “tipping point” of the rounding is half way to the next increment of the greatest unit. As shown below, one example is that 35 hours and 59 minutes rounds to 1 day, but 36 hours and 1 minute rounds to 2 days because 2 days is closer to 36h 1 min than 36h 1 min is to 1 day.

Example
use hifitime::{Duration, TimeUnits};

assert_eq!((2.hours() + 3.minutes()).approx(), 2.hours());
assert_eq!((24.hours() + 3.minutes()).approx(), 1.days());
assert_eq!((35.hours() + 59.minutes()).approx(), 1.days());
assert_eq!((36.hours() + 1.minutes()).approx(), 2.days());
assert_eq!((47.hours() + 3.minutes()).approx(), 2.days());
assert_eq!((49.hours() + 3.minutes()).approx(), 2.days());
source

pub fn min(&self, other: Self) -> Self

Returns the minimum of the two durations.

use hifitime::TimeUnits;

let d0 = 20.seconds();
let d1 = 21.seconds();

assert_eq!(d0, d1.min(d0));
assert_eq!(d0, d0.min(d1));

Note: this uses a pointer to self which will be copied immediately because Python requires a pointer.

source

pub fn max(&self, other: Self) -> Self

Returns the maximum of the two durations.

use hifitime::TimeUnits;

let d0 = 20.seconds();
let d1 = 21.seconds();

assert_eq!(d1, d1.max(d0));
assert_eq!(d1, d0.max(d1));

Note: this uses a pointer to self which will be copied immediately because Python requires a pointer.

source

pub const fn is_negative(&self) -> bool

Returns whether this is a negative or positive duration.

source

pub const ZERO: Self = _

A duration of exactly zero nanoseconds

source

pub const MAX: Self = _

Maximum duration that can be represented

source

pub const MIN: Self = _

Minimum duration that can be represented

source

pub const EPSILON: Self = _

Smallest duration that can be represented

source

pub const MIN_POSITIVE: Self = Self::EPSILON

Minimum positive duration is one nanoseconds

source

pub const MIN_NEGATIVE: Self = _

Minimum negative duration is minus one nanosecond

source§

impl Duration

source

pub fn in_seconds(&self) -> f64

👎Deprecated since 3.5.0: Prefer to_seconds()
source

pub fn in_unit(&self, unit: Unit) -> f64

👎Deprecated since 3.5.0: Prefer to_unit()

Returns the value of this duration in the requested unit.

Trait Implementations§

source§

impl Add<Duration> for Epoch

§

type Output = Epoch

The resulting type after applying the + operator.
source§

fn add(self, duration: Duration) -> Self

Performs the + operation. Read more
source§

impl Add<Unit> for Duration

§

type Output = Duration

The resulting type after applying the + operator.
source§

fn add(self, rhs: Unit) -> Self

Performs the + operation. Read more
source§

impl Add for Duration

source§

fn add(self, rhs: Self) -> Duration

Addition of Durations

Durations are centered on zero duration. Of the tuple, only the centuries may be negative, the nanoseconds are always positive and represent the nanoseconds into the current centuries.

Examples
  • Duration { centuries: 0, nanoseconds: 1 } is a positive duration of zero centuries and one nanosecond.
  • Duration { centuries: -1, nanoseconds: 1 } is a negative duration representing “one century before zero minus one nanosecond”
§

type Output = Duration

The resulting type after applying the + operator.
source§

impl AddAssign<Duration> for Epoch

source§

fn add_assign(&mut self, duration: Duration)

Performs the += operation. Read more
source§

impl AddAssign<Unit> for Duration

source§

fn add_assign(&mut self, rhs: Unit)

Performs the += operation. Read more
source§

impl AddAssign for Duration

source§

fn add_assign(&mut self, rhs: Duration)

Performs the += operation. Read more
source§

impl Clone for Duration

source§

fn clone(&self) -> Duration

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Duration

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for Duration

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<'de> Deserialize<'de> for Duration

source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl Display for Duration

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Div<f64> for Duration

§

type Output = Duration

The resulting type after applying the / operator.
source§

fn div(self, q: f64) -> Self::Output

Performs the / operation. Read more
source§

impl Div<i64> for Duration

§

type Output = Duration

The resulting type after applying the / operator.
source§

fn div(self, q: i64) -> Self::Output

Performs the / operation. Read more
source§

impl From<Duration> for Duration

source§

fn from(hf_duration: Duration) -> Self

Converts a duration into an std::time::Duration

Limitations
  1. If the duration is negative, this will return a std::time::Duration::ZERO.
  2. If the duration larger than the MAX duration, this will return std::time::Duration::MAX
source§

impl From<Duration> for Duration

source§

fn from(std_duration: Duration) -> Self

Converts a duration into an std::time::Duration

Limitations
  1. If the duration is negative, this will return a std::time::Duration::ZERO.
  2. If the duration larger than the MAX duration, this will return std::time::Duration::MAX
source§

impl FromStr for Duration

source§

fn from_str(s_in: &str) -> Result<Self, Self::Err>

Attempts to convert a simple string to a Duration. Does not yet support complicated durations.

Identifiers:

  • d, days, day
  • h, hours, hour
  • min, mins, minute
  • s, second, seconds
  • ms, millisecond, milliseconds
  • us, microsecond, microseconds
  • ns, nanosecond, nanoseconds
  • + or - indicates a timezone offset
Example
use hifitime::{Duration, Unit};
use std::str::FromStr;

assert_eq!(Duration::from_str("1 d").unwrap(), Unit::Day * 1);
assert_eq!(Duration::from_str("10.598 days").unwrap(), Unit::Day * 10.598);
assert_eq!(Duration::from_str("10.598 min").unwrap(), Unit::Minute * 10.598);
assert_eq!(Duration::from_str("10.598 us").unwrap(), Unit::Microsecond * 10.598);
assert_eq!(Duration::from_str("10.598 seconds").unwrap(), Unit::Second * 10.598);
assert_eq!(Duration::from_str("10.598 nanosecond").unwrap(), Unit::Nanosecond * 10.598);
assert_eq!(Duration::from_str("5 h 256 ms 1 ns").unwrap(), 5 * Unit::Hour + 256 * Unit::Millisecond + Unit::Nanosecond);
assert_eq!(Duration::from_str("-01:15:30").unwrap(), -(1 * Unit::Hour + 15 * Unit::Minute + 30 * Unit::Second));
assert_eq!(Duration::from_str("+3615").unwrap(), 36 * Unit::Hour + 15 * Unit::Minute);
§

type Err = Errors

The associated error which can be returned from parsing.
source§

impl Hash for Duration

source§

fn hash<H: Hasher>(&self, hasher: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl LowerExp for Duration

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter.
source§

impl Mul<Duration> for f64

§

type Output = Duration

The resulting type after applying the * operator.
source§

fn mul(self, q: Self::Output) -> Self::Output

Performs the * operation. Read more
source§

impl Mul<Duration> for i64

§

type Output = Duration

The resulting type after applying the * operator.
source§

fn mul(self, q: Self::Output) -> Self::Output

Performs the * operation. Read more
source§

impl Mul<f64> for Duration

§

type Output = Duration

The resulting type after applying the * operator.
source§

fn mul(self, q: f64) -> Self::Output

Performs the * operation. Read more
source§

impl Mul<i64> for Duration

§

type Output = Duration

The resulting type after applying the * operator.
source§

fn mul(self, q: i64) -> Self::Output

Performs the * operation. Read more
source§

impl Neg for Duration

§

type Output = Duration

The resulting type after applying the - operator.
source§

fn neg(self) -> Self::Output

Performs the unary - operation. Read more
source§

impl Ord for Duration

source§

fn cmp(&self, other: &Duration) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
source§

impl PartialEq<Unit> for Duration

source§

fn eq(&self, unit: &Unit) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialEq for Duration

source§

fn eq(&self, other: &Self) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<Unit> for Duration

source§

fn partial_cmp(&self, unit: &Unit) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl PartialOrd for Duration

source§

fn partial_cmp(&self, other: &Duration) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl Serialize for Duration

source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl Sub<Duration> for Epoch

§

type Output = Epoch

The resulting type after applying the - operator.
source§

fn sub(self, duration: Duration) -> Self

Performs the - operation. Read more
source§

impl Sub<Unit> for Duration

§

type Output = Duration

The resulting type after applying the - operator.
source§

fn sub(self, rhs: Unit) -> Duration

Performs the - operation. Read more
source§

impl Sub for Duration

source§

fn sub(self, rhs: Self) -> Self

Subtraction

This operation is a notch confusing with negative durations. As described in the Duration structure, a Duration of (-1, NANOSECONDS_PER_CENTURY-1) is closer to zero than (-1, 0).

Algorithm
A > B, and both are positive

If A > B, then A.centuries is subtracted by B.centuries, and A.nanoseconds is subtracted by B.nanoseconds. If an overflow occurs, e.g. A.nanoseconds < B.nanoseconds, the number of nanoseconds is increased by the number of nanoseconds per century, and the number of centuries is decreased by one.

use hifitime::{Duration, NANOSECONDS_PER_CENTURY};

let a = Duration::from_parts(1, 1);
let b = Duration::from_parts(0, 10);
let c = Duration::from_parts(0, NANOSECONDS_PER_CENTURY - 9);
assert_eq!(a - b, c);
A < B, and both are positive

In this case, the resulting duration will be negative. The number of centuries is a signed integer, so it is set to the difference of A.centuries - B.centuries. The number of nanoseconds however must be wrapped by the number of nanoseconds per century. For example:, let A = (0, 1) and B = (1, 10), then the resulting duration will be (-2, NANOSECONDS_PER_CENTURY - (10 - 1)). In this case, the centuries are set to -2 because B is two centuries into the future (the number of centuries into the future is zero-indexed).

use hifitime::{Duration, NANOSECONDS_PER_CENTURY};

let a = Duration::from_parts(0, 1);
let b = Duration::from_parts(1, 10);
let c = Duration::from_parts(-2, NANOSECONDS_PER_CENTURY - 9);
assert_eq!(a - b, c);
A > B, both are negative

In this case, we try to stick to normal arithmatics: (-9 - -10) = (-9 + 10) = +1. In this case, we can simply add the components of the duration together. For example, let A = (-1, NANOSECONDS_PER_CENTURY - 2), and B = (-1, NANOSECONDS_PER_CENTURY - 1). Respectively, A is two nanoseconds before Duration::ZERO and B is one nanosecond before Duration::ZERO. Then, A-B should be one nanoseconds before zero, i.e. (-1, NANOSECONDS_PER_CENTURY - 1). This is because we subtract “negative one nanosecond” from a “negative minus two nanoseconds”, which corresponds to adding the opposite, and the opposite of “negative one nanosecond” is “positive one nanosecond”.

use hifitime::{Duration, NANOSECONDS_PER_CENTURY};

let a = Duration::from_parts(-1, NANOSECONDS_PER_CENTURY - 9);
let b = Duration::from_parts(-1, NANOSECONDS_PER_CENTURY - 10);
let c = Duration::from_parts(0, 1);
assert_eq!(a - b, c);
A < B, both are negative

Just like in the prior case, we try to stick to normal arithmatics: (-10 - -9) = (-10 + 9) = -1.

use hifitime::{Duration, NANOSECONDS_PER_CENTURY};

let a = Duration::from_parts(-1, NANOSECONDS_PER_CENTURY - 10);
let b = Duration::from_parts(-1, NANOSECONDS_PER_CENTURY - 9);
let c = Duration::from_parts(-1, NANOSECONDS_PER_CENTURY - 1);
assert_eq!(a - b, c);
MIN is the minimum

One cannot subtract anything from the MIN.

use hifitime::Duration;

let one_ns = Duration::from_parts(0, 1);
assert_eq!(Duration::MIN - one_ns, Duration::MIN);
§

type Output = Duration

The resulting type after applying the - operator.
source§

impl SubAssign<Duration> for Epoch

source§

fn sub_assign(&mut self, duration: Duration)

Performs the -= operation. Read more
source§

impl SubAssign<Unit> for Duration

source§

fn sub_assign(&mut self, rhs: Unit)

Performs the -= operation. Read more
source§

impl SubAssign for Duration

source§

fn sub_assign(&mut self, rhs: Self)

Performs the -= operation. Read more
source§

impl Copy for Duration

source§

impl Eq for Duration

source§

impl StructuralEq for Duration

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,