Skip to content

Commit

Permalink
Rollup merge of rust-lang#57375 - stjepang:duration-constants, r=josh…
Browse files Browse the repository at this point in the history
…triplett

Add duration constants

Add constants `SECOND`, `MILLISECOND`, `MICROSECOND`, and `NANOSECOND` to `core::time`.

This will make working with durations more ergonomic. Compare:

```rust
// Convenient, but deprecated function.
thread::sleep_ms(2000);

// The current canonical way to sleep for two seconds.
thread::sleep(Duration::from_secs(2));

// Sleeping using one of the new constants.
thread::sleep(2 * SECOND);
```
  • Loading branch information
pietroalbini authored Jan 7, 2019
2 parents 5cfc845 + 8c902b6 commit bc38143
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/libcore/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,22 @@ const MILLIS_PER_SEC: u64 = 1_000;
const MICROS_PER_SEC: u64 = 1_000_000;
const MAX_NANOS_F64: f64 = ((u64::MAX as u128 + 1)*(NANOS_PER_SEC as u128)) as f64;

/// The duration of one second.
#[unstable(feature = "duration_constants", issue = "57391")]
pub const SECOND: Duration = Duration::from_secs(1);

/// The duration of one millisecond.
#[unstable(feature = "duration_constants", issue = "57391")]
pub const MILLISECOND: Duration = Duration::from_millis(1);

/// The duration of one microsecond.
#[unstable(feature = "duration_constants", issue = "57391")]
pub const MICROSECOND: Duration = Duration::from_micros(1);

/// The duration of one nanosecond.
#[unstable(feature = "duration_constants", issue = "57391")]
pub const NANOSECOND: Duration = Duration::from_nanos(1);

/// A `Duration` type to represent a span of time, typically used for system
/// timeouts.
///
Expand Down
1 change: 1 addition & 0 deletions src/libstd/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@
#![feature(const_cstr_unchecked)]
#![feature(core_intrinsics)]
#![feature(dropck_eyepatch)]
#![feature(duration_constants)]
#![feature(exact_size_is_empty)]
#![feature(external_doc)]
#![feature(fixed_size_array)]
Expand Down
3 changes: 3 additions & 0 deletions src/libstd/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ use sys_common::FromInner;
#[stable(feature = "time", since = "1.3.0")]
pub use core::time::Duration;

#[unstable(feature = "duration_constants", issue = "57391")]
pub use core::time::{SECOND, MILLISECOND, MICROSECOND, NANOSECOND};

/// A measurement of a monotonically nondecreasing clock.
/// Opaque and useful only with `Duration`.
///
Expand Down

0 comments on commit bc38143

Please sign in to comment.