diff options
| author | Vitaly _Vi Shukela <vi0oss@gmail.com> | 2019-02-13 15:08:44 +0300 |
|---|---|---|
| committer | Vitaly _Vi Shukela <vi0oss@gmail.com> | 2019-02-13 15:08:44 +0300 |
| commit | 91f67fd1a75d7cc1b1ac5fc957ff30f16d01232e (patch) | |
| tree | cedeaff78528159658ce633a34bdb1cd3ab0dd28 /src/libstd | |
| parent | d15c35800032e58c17ef1da3577dacc01ef82bb1 (diff) | |
| download | rust-91f67fd1a75d7cc1b1ac5fc957ff30f16d01232e.tar.gz rust-91f67fd1a75d7cc1b1ac5fc957ff30f16d01232e.zip | |
Add Instant::saturating_duration_since
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/time.rs | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/src/libstd/time.rs b/src/libstd/time.rs index eefb84f697f..db2630e88d0 100644 --- a/src/libstd/time.rs +++ b/src/libstd/time.rs @@ -243,6 +243,27 @@ impl Instant { } } + /// Returns the amount of time elapsed from another instant to this one, + /// or zero duration if that instant is earlier than this one. + /// + /// # Examples + /// + /// ```no_run + /// #![feature(checked_duration_since)] + /// use std::time::{Duration, Instant}; + /// use std::thread::sleep; + /// + /// let now = Instant::now(); + /// sleep(Duration::new(1, 0)); + /// let new_now = Instant::now(); + /// println!("{:?}", new_now.saturating_duration_since(now)); + /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns + /// ``` + #[unstable(feature = "checked_duration_since", issue = "58402")] + pub fn saturating_duration_since(&self, earlier: Instant) -> Duration { + self.checked_duration_since(earlier).unwrap_or(Duration::new(0, 0)) + } + /// Returns the amount of time elapsed since this instant was created. /// /// # Panics @@ -659,6 +680,13 @@ mod tests { } #[test] + fn saturating_instant_duration_nopanic() { + let a = Instant::now(); + let ret = (a - Duration::new(1, 0)).saturating_duration_since(a); + assert_eq!(ret, Duration::new(0,0)); + } + + #[test] fn system_time_math() { let a = SystemTime::now(); let b = SystemTime::now(); |
