|
1 | 1 | #![stable(feature = "duration_core", since = "1.25.0")]
|
2 |
| - |
3 | 2 | //! Temporal quantification.
|
4 | 3 | //!
|
5 | 4 | //! # Examples:
|
@@ -308,6 +307,39 @@ impl Duration {
|
308 | 307 | Duration { secs, nanos: subsec_nanos }
|
309 | 308 | }
|
310 | 309 |
|
| 310 | + /// Creates a new Duration from the specified number of nanoseconds. |
| 311 | + /// |
| 312 | + /// # Panics |
| 313 | + /// |
| 314 | + /// Panics if the given number of nanoseconds is greater than what Duration can handle, |
| 315 | + /// which is `(u64::MAX * NANOS_PER_SEC) + NANOS_PER_SEC - 1` |
| 316 | + /// Use this function if you need to specify time greater than what can fit in u64 |
| 317 | + /// (around 584 years). |
| 318 | + /// |
| 319 | + /// # Examples |
| 320 | + /// |
| 321 | + /// ``` |
| 322 | + /// #![feature(duration_from_nanos_u128)] |
| 323 | + /// use std::time::Duration; |
| 324 | + /// let time_in_nanos = 2u128.pow(64); |
| 325 | + /// let duration = Duration::from_nanos_u128(time_in_nanos); |
| 326 | + /// ``` |
| 327 | + #[unstable(feature = "duration_from_nanos_u128", issue = "139201")] |
| 328 | + #[must_use] |
| 329 | + #[inline] |
| 330 | + pub const fn from_nanos_u128(nanos: u128) -> Duration { |
| 331 | + const NANOS_PER_SEC: u128 = self::NANOS_PER_SEC as u128; |
| 332 | + let secs: u128 = nanos / NANOS_PER_SEC; |
| 333 | + if secs > u64::MAX as u128 { |
| 334 | + panic!("overflow in duration in Duration::from_nanos_u128"); |
| 335 | + } |
| 336 | + let subsec_nanos = (nanos % NANOS_PER_SEC) as u32; |
| 337 | + // SAFETY: x % 1_000_000_000 < 1_000_000_000 also, subsec_nanos >= 0 since u128 >=0 and u32 >=0 |
| 338 | + let subsec_nanos = unsafe { Nanoseconds::new_unchecked(subsec_nanos) }; |
| 339 | + |
| 340 | + Duration { secs: secs as u64, nanos: subsec_nanos } |
| 341 | + } |
| 342 | + |
311 | 343 | /// Creates a new `Duration` from the specified number of weeks.
|
312 | 344 | ///
|
313 | 345 | /// # Panics
|
|
0 commit comments