Skip to content

Commit 3ff5879

Browse files
committed
core/time: Add Duration methods for zero
This patch adds two methods to `Duration`. The first, `Duration::zero`, provides a `const` constructor for getting an zero-length duration. This is also what `Default` provides (this was clarified in the docs), though `default` is not `const`. The second, `Duration::is_zero`, returns true if a `Duration` spans no time (i.e., because its components are all zero). Previously, the way to do this was either to compare both `as_secs` and `subsec_nanos` to 0, to compare against `Duration::new(0, 0)`, or to use the `u128` method `as_nanos`, none of which were particularly elegant.
1 parent 033013c commit 3ff5879

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

src/libcore/time.rs

+42-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ const MICROS_PER_SEC: u64 = 1_000_000;
3131
/// the number of nanoseconds.
3232
///
3333
/// `Duration`s implement many common traits, including [`Add`], [`Sub`], and other
34-
/// [`ops`] traits.
34+
/// [`ops`] traits. It implements `Default` by returning a zero-length `Duration`.
3535
///
3636
/// [`Add`]: ../../std/ops/trait.Add.html
3737
/// [`Sub`]: ../../std/ops/trait.Sub.html
@@ -223,6 +223,47 @@ impl Duration {
223223
}
224224
}
225225

226+
/// Creates a new `Duration` that spans no time.
227+
///
228+
/// # Examples
229+
///
230+
/// ```
231+
/// use std::time::Duration;
232+
///
233+
/// let duration = Duration::zero();
234+
/// assert!(duration.is_zero());
235+
///
236+
/// const IMMEDIATELY: Duration = Duration::zero();
237+
/// assert!(IMMEDIATELY.is_zero());
238+
/// ```
239+
#[unstable(feature = "duration_zero", issue = "none")]
240+
#[inline]
241+
pub const fn zero() -> Duration {
242+
Duration { secs: 0, nanos: 0 }
243+
}
244+
245+
/// Returns true if this `Duration` spans no time.
246+
///
247+
/// # Examples
248+
///
249+
/// ```
250+
/// use std::time::Duration;
251+
///
252+
/// assert!(Duration::zero().is_zero());
253+
/// assert!(Duration::new(0, 0).is_zero());
254+
/// assert!(Duration::from_nanos(0).is_zero());
255+
/// assert!(Duration::from_secs(0).is_zero());
256+
///
257+
/// assert!(!Duration::new(1, 1).is_zero());
258+
/// assert!(!Duration::from_nanos(1).is_zero());
259+
/// assert!(!Duration::from_secs(1).is_zero());
260+
/// ```
261+
#[unstable(feature = "duration_zero", issue = "none")]
262+
#[inline]
263+
pub const fn is_zero(&self) -> bool {
264+
self.secs == 0 && self.nanos == 0
265+
}
266+
226267
/// Returns the number of _whole_ seconds contained by this `Duration`.
227268
///
228269
/// The returned value does not include the fractional (nanosecond) part of the

0 commit comments

Comments
 (0)