]> git.lizzy.rs Git - rust.git/blobdiff - src/libstd/time.rs
Various minor/cosmetic improvements to code
[rust.git] / src / libstd / time.rs
index d124cf53dda5d3fe7a2f15eed54b86c367733c85..667810485ee39d004f5aade433e402c299677cab 100644 (file)
@@ -330,7 +330,7 @@ pub fn duration_since(&self, earlier: SystemTime)
     /// Returns the amount of time elapsed since this system time was created.
     ///
     /// This function may fail as the underlying system clock is susceptible to
-    /// drift and updates (e.g. the system clock could go backwards), so this
+    /// drift and updates (e.g., the system clock could go backwards), so this
     /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
     /// returned where the duration represents the amount of time elapsed from
     /// this time measurement to the current time.
@@ -357,6 +357,14 @@ pub fn duration_since(&self, earlier: SystemTime)
     pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
         SystemTime::now().duration_since(*self)
     }
+
+    /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
+    /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
+    /// otherwise.
+    #[unstable(feature = "time_checked_add", issue = "55940")]
+    pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
+        self.0.checked_add_duration(&duration).map(|t| SystemTime(t))
+    }
 }
 
 #[stable(feature = "time2", since = "1.8.0")]
@@ -481,7 +489,7 @@ macro_rules! assert_almost_eq {
             let (a, b) = ($a, $b);
             if a != b {
                 let (a, b) = if a > b {(a, b)} else {(b, a)};
-                assert!(a - Duration::new(0, 100) <= b,
+                assert!(a - Duration::new(0, 1000) <= b,
                         "{:?} is not almost equal to {:?}", a, b);
             }
         })
@@ -561,6 +569,19 @@ fn system_time_math() {
         let one_second_from_epoch2 = UNIX_EPOCH + Duration::new(0, 500_000_000)
             + Duration::new(0, 500_000_000);
         assert_eq!(one_second_from_epoch, one_second_from_epoch2);
+
+        // checked_add_duration will not panic on overflow
+        let mut maybe_t = Some(SystemTime::UNIX_EPOCH);
+        let max_duration = Duration::from_secs(u64::max_value());
+        // in case `SystemTime` can store `>= UNIX_EPOCH + max_duration`.
+        for _ in 0..2 {
+            maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
+        }
+        assert_eq!(maybe_t, None);
+
+        // checked_add_duration calculates the right time and will work for another year
+        let year = Duration::from_secs(60 * 60 * 24 * 365);
+        assert_eq!(a + year, a.checked_add(year).unwrap());
     }
 
     #[test]