about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorVitaly _Vi Shukela <vi0oss@gmail.com>2019-02-12 10:56:26 +0300
committerVitaly _Vi Shukela <vi0oss@gmail.com>2019-02-13 00:49:48 +0300
commit7b2a08cf494563c1867200cd994193d1855719f2 (patch)
tree93963dd51503fbecbb07109416acb2968b6fe420 /src/libstd
parentba2853b6d3a197cdbec5543be2592ca430b49af6 (diff)
downloadrust-7b2a08cf494563c1867200cd994193d1855719f2.tar.gz
rust-7b2a08cf494563c1867200cd994193d1855719f2.zip
Add Instant::checked_duration_since, address #58402.
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/lib.rs1
-rw-r--r--src/libstd/time.rs30
2 files changed, 31 insertions, 0 deletions
diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs
index 8ecba3ecd68..38fc0bb80d0 100644
--- a/src/libstd/lib.rs
+++ b/src/libstd/lib.rs
@@ -295,6 +295,7 @@
 #![feature(non_exhaustive)]
 #![feature(alloc_layout_extra)]
 #![feature(maybe_uninit)]
+#![feature(checked_duration_since)]
 #![cfg_attr(all(target_vendor = "fortanix", target_env = "sgx"),
             feature(global_asm, range_contains, slice_index_methods,
                     decl_macro, coerce_unsized, sgx_platform, ptr_wrapping_offset_from))]
diff --git a/src/libstd/time.rs b/src/libstd/time.rs
index 23924559fcc..973edb5479e 100644
--- a/src/libstd/time.rs
+++ b/src/libstd/time.rs
@@ -218,6 +218,30 @@ impl Instant {
         self.0.sub_instant(&earlier.0)
     }
 
+    /// Returns the amount of time elapsed from another instant to this one,
+    /// or None if that instant is earlier than this one.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// 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.checked_duration_since(now));
+    /// println!("{:?}", now.checked_duration_since(new_now)); // None
+    /// ```
+    #[unstable(feature = "checked_duration_since", issue = "58402")]
+    pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
+        if self >= &earlier {
+            Some(self.0.sub_instant(&earlier.0))
+        } else {
+            None
+        }
+    }
+
     /// Returns the amount of time elapsed since this instant was created.
     ///
     /// # Panics
@@ -627,6 +651,12 @@ mod tests {
     }
 
     #[test]
+    fn checked_instant_duration_nopanic() {
+        let a = Instant::now();
+        (a - Duration::new(1, 0)).checked_duration_since(a);
+    }
+
+    #[test]
     fn system_time_math() {
         let a = SystemTime::now();
         let b = SystemTime::now();