about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMatthias Krüger <matthias.krueger@famsik.de>2024-03-14 20:00:20 +0100
committerGitHub <noreply@github.com>2024-03-14 20:00:20 +0100
commit5d41186446ac907121b5e73f73cfe6eba50fd522 (patch)
tree4cb32cfb50ee6916559b26f2d59d38539cfceef7
parentb200108bc5a43d790455037252295a6b0affff0e (diff)
parentf2ec0d3d26dc31c84274b853cc04ce25371c8d3d (diff)
downloadrust-5d41186446ac907121b5e73f73cfe6eba50fd522.tar.gz
rust-5d41186446ac907121b5e73f73cfe6eba50fd522.zip
Rollup merge of #122479 - GrigorenkoPV:duration_millis_float, r=scottmcm
Implement `Duration::as_millis_{f64,f32}`

Implementation of #122451.

Linked const-unstability to #72440, so the post there should probably be updated to mentions the 2 new methods when/if this PR is merged.
-rw-r--r--library/core/src/time.rs42
1 files changed, 42 insertions, 0 deletions
diff --git a/library/core/src/time.rs b/library/core/src/time.rs
index b533f539938..78494b866b1 100644
--- a/library/core/src/time.rs
+++ b/library/core/src/time.rs
@@ -856,6 +856,48 @@ impl Duration {
         (self.secs as f32) + (self.nanos.0 as f32) / (NANOS_PER_SEC as f32)
     }
 
+    /// Returns the number of milliseconds contained by this `Duration` as `f64`.
+    ///
+    /// The returned value does include the fractional (nanosecond) part of the duration.
+    ///
+    /// # Examples
+    /// ```
+    /// #![feature(duration_millis_float)]
+    /// use std::time::Duration;
+    ///
+    /// let dur = Duration::new(2, 345_678_000);
+    /// assert_eq!(dur.as_millis_f64(), 2345.678);
+    /// ```
+    #[unstable(feature = "duration_millis_float", issue = "122451")]
+    #[must_use]
+    #[inline]
+    #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
+    pub const fn as_millis_f64(&self) -> f64 {
+        (self.secs as f64) * (MILLIS_PER_SEC as f64)
+            + (self.nanos.0 as f64) / (NANOS_PER_MILLI as f64)
+    }
+
+    /// Returns the number of milliseconds contained by this `Duration` as `f32`.
+    ///
+    /// The returned value does include the fractional (nanosecond) part of the duration.
+    ///
+    /// # Examples
+    /// ```
+    /// #![feature(duration_millis_float)]
+    /// use std::time::Duration;
+    ///
+    /// let dur = Duration::new(2, 345_678_000);
+    /// assert_eq!(dur.as_millis_f32(), 2345.678);
+    /// ```
+    #[unstable(feature = "duration_millis_float", issue = "122451")]
+    #[must_use]
+    #[inline]
+    #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
+    pub const fn as_millis_f32(&self) -> f32 {
+        (self.secs as f32) * (MILLIS_PER_SEC as f32)
+            + (self.nanos.0 as f32) / (NANOS_PER_MILLI as f32)
+    }
+
     /// Creates a new `Duration` from the specified number of seconds represented
     /// as `f64`.
     ///