about summary refs log tree commit diff
path: root/library/core/src
diff options
context:
space:
mode:
authorStuart Cook <Zalathar@users.noreply.github.com>2025-08-30 20:29:08 +1000
committerGitHub <noreply@github.com>2025-08-30 20:29:08 +1000
commitf655e6a863c0bd3ffd74468939b3819001624f4d (patch)
treeacef1a03320b28652754613b1f31b065b2669aed /library/core/src
parentdfbba07012ac533ad4dd1f770347cfd547b7eb8c (diff)
parent8134a10ec76e7c357d207ea83b215a15af63519c (diff)
Rollup merge of #145969 - actuallylost:duration-from-nanos-128, r=tgross35
Add Duration::from_nanos_u128

Feature Gate: `#![feature(duration_from_nanos_u128)]`
ACP: https://github.com/rust-lang/libs-team/issues/567
Tracking issue: https://github.com/rust-lang/rust/issues/139201
Recreated from https://github.com/rust-lang/rust/pull/139243
Diffstat (limited to 'library/core/src')
-rw-r--r--library/core/src/time.rs36
1 files changed, 36 insertions, 0 deletions
diff --git a/library/core/src/time.rs b/library/core/src/time.rs
index f37e47f132d..d205bc376f1 100644
--- a/library/core/src/time.rs
+++ b/library/core/src/time.rs
@@ -308,6 +308,42 @@ impl Duration {
         Duration { secs, nanos: subsec_nanos }
     }
 
+    /// Creates a new `Duration` from the specified number of nanoseconds.
+    ///
+    /// # Panics
+    ///
+    /// Panics if the given number of nanoseconds is greater than [`Duration::MAX`].
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(duration_from_nanos_u128)]
+    /// use std::time::Duration;
+    ///
+    /// let nanos = 10_u128.pow(24) + 321;
+    /// let duration = Duration::from_nanos_u128(nanos);
+    ///
+    /// assert_eq!(10_u64.pow(15), duration.as_secs());
+    /// assert_eq!(321, duration.subsec_nanos());
+    /// ```
+    #[unstable(feature = "duration_from_nanos_u128", issue = "139201")]
+    // This is necessary because of const `try_from`, but can be removed if a trait-free impl is used instead
+    #[rustc_const_unstable(feature = "duration_from_nanos_u128", issue = "139201")]
+    #[must_use]
+    #[inline]
+    #[track_caller]
+    pub const fn from_nanos_u128(nanos: u128) -> Duration {
+        const NANOS_PER_SEC: u128 = self::NANOS_PER_SEC as u128;
+        let Ok(secs) = u64::try_from(nanos / NANOS_PER_SEC) else {
+            panic!("overflow in `Duration::from_nanos_u128`");
+        };
+        let subsec_nanos = (nanos % NANOS_PER_SEC) as u32;
+        // SAFETY: x % 1_000_000_000 < 1_000_000_000 also, subsec_nanos >= 0 since u128 >=0 and u32 >=0
+        let subsec_nanos = unsafe { Nanoseconds::new_unchecked(subsec_nanos) };
+
+        Duration { secs: secs as u64, nanos: subsec_nanos }
+    }
+
     /// Creates a new `Duration` from the specified number of weeks.
     ///
     /// # Panics