about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--src/libstd/time.rs28
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();