diff options
| author | bors <bors@rust-lang.org> | 2023-11-21 13:09:49 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2023-11-21 13:09:49 +0000 |
| commit | e24e5af787f7015914cbf316063ed5821f370b71 (patch) | |
| tree | 65b4e2a8e3c1f5ba7e88f2fb62f9f34d964b91e9 /library/core/src | |
| parent | 7bd385dc371a85219c4261f0cb5ba7c83b7e0c5e (diff) | |
| parent | 0ac438c8d45b27e95eb0512598c26eee5d967ffe (diff) | |
| download | rust-e24e5af787f7015914cbf316063ed5821f370b71.tar.gz rust-e24e5af787f7015914cbf316063ed5821f370b71.zip | |
Auto merge of #117619 - elomatreb:add-duration-abs-diff, r=thomcc
Add `Duration::abs_diff` This adds a `Duration::abs_diff` method analogous to the existing one on the primitive integers. ACP: https://github.com/rust-lang/libs-team/issues/291 Tracking Issue: https://github.com/rust-lang/rust/issues/117618
Diffstat (limited to 'library/core/src')
| -rw-r--r-- | library/core/src/time.rs | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/library/core/src/time.rs b/library/core/src/time.rs index 6ef35d8414b..b677776443f 100644 --- a/library/core/src/time.rs +++ b/library/core/src/time.rs @@ -461,6 +461,27 @@ impl Duration { self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos.0 as u128 } + /// Computes the absolute difference between `self` and `other`. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(duration_abs_diff)] + /// use std::time::Duration; + /// + /// assert_eq!(Duration::new(100, 0).abs_diff(Duration::new(80, 0)), Duration::new(20, 0)); + /// assert_eq!(Duration::new(100, 400_000_000).abs_diff(Duration::new(110, 0)), Duration::new(9, 600_000_000)); + /// ``` + #[unstable(feature = "duration_abs_diff", issue = "117618")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline] + pub const fn abs_diff(self, other: Duration) -> Duration { + if let Some(res) = self.checked_sub(other) { res } else { other.checked_sub(self).unwrap() } + } + /// Checked `Duration` addition. Computes `self + other`, returning [`None`] /// if overflow occurred. /// |
