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

core/time: Add Duration methods for zero #72790

Merged
merged 3 commits into from
Jun 21, 2020
Merged
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
43 changes: 42 additions & 1 deletion src/libcore/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const MICROS_PER_SEC: u64 = 1_000_000;
/// the number of nanoseconds.
///
/// `Duration`s implement many common traits, including [`Add`], [`Sub`], and other
/// [`ops`] traits.
/// [`ops`] traits. It implements `Default` by returning a zero-length `Duration`.
///
/// [`Add`]: ../../std/ops/trait.Add.html
/// [`Sub`]: ../../std/ops/trait.Sub.html
Expand Down Expand Up @@ -138,6 +138,24 @@ impl Duration {
Duration { secs, nanos }
}

/// Creates a new `Duration` that spans no time.
///
/// # Examples
///
/// ```
/// #![feature(duration_zero)]
/// use std::time::Duration;
///
/// let duration = Duration::zero();
/// assert!(duration.is_zero());
/// assert_eq!(duration.as_nanos(), 0);
/// ```
#[unstable(feature = "duration_zero", issue = "73544")]
#[inline]
pub const fn zero() -> Duration {
Duration { secs: 0, nanos: 0 }
}

/// Creates a new `Duration` from the specified number of whole seconds.
///
/// # Examples
Expand Down Expand Up @@ -223,6 +241,29 @@ impl Duration {
}
}

/// Returns true if this `Duration` spans no time.
///
/// # Examples
///
/// ```
/// #![feature(duration_zero)]
/// use std::time::Duration;
///
/// assert!(Duration::zero().is_zero());
/// assert!(Duration::new(0, 0).is_zero());
/// assert!(Duration::from_nanos(0).is_zero());
/// assert!(Duration::from_secs(0).is_zero());
///
/// assert!(!Duration::new(1, 1).is_zero());
/// assert!(!Duration::from_nanos(1).is_zero());
/// assert!(!Duration::from_secs(1).is_zero());
/// ```
#[unstable(feature = "duration_zero", issue = "73544")]
#[inline]
pub const fn is_zero(&self) -> bool {
self.secs == 0 && self.nanos == 0
}

/// Returns the number of _whole_ seconds contained by this `Duration`.
///
/// The returned value does not include the fractional (nanosecond) part of the
Expand Down