From 6bb3acab74f9cf4bf3d3b81f0805416cd7b3ee20 Mon Sep 17 00:00:00 2001 From: Michael Watzko Date: Thu, 19 Aug 2021 11:06:08 +0200 Subject: [PATCH] Add doctests to and fix saturating_div for signed integer types --- library/core/src/num/int_macros.rs | 31 +++++++++++++++++++++--------- library/std/src/lib.rs | 1 + 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/library/core/src/num/int_macros.rs b/library/core/src/num/int_macros.rs index f5966a53ed2..7c36f4cdd20 100644 --- a/library/core/src/num/int_macros.rs +++ b/library/core/src/num/int_macros.rs @@ -926,21 +926,34 @@ pub const fn saturating_mul(self, rhs: Self) -> Self { /// Basic usage: /// /// ``` + /// #![feature(saturating_div)] + /// + #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")] + #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_div(-1), ", stringify!($SelfT), "::MIN + 1);")] + #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_div(-1), ", stringify!($SelfT), "::MAX);")] /// /// ``` - #[unstable(feature = "saturating_int_impl", issue = "87920")] - #[rustc_const_unstable(feature = "saturating_int_impl", issue = "87920")] + /// + /// ```should_panic + /// #![feature(saturating_div)] + /// + #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")] + /// + /// ``` + #[unstable(feature = "saturating_div", issue = "87920")] + #[rustc_const_unstable(feature = "saturating_div", issue = "87920")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] pub const fn saturating_div(self, rhs: Self) -> Self { - match self.checked_div(rhs) { - Some(x) => x, - None => if (self < 0) == (rhs < 0) { - Self::MAX - } else { - Self::MIN - } + let (result, overflowed) = self.overflowing_div(rhs); + + if !overflowed { + result + } else if (self < 0) == (rhs < 0) { + Self::MAX + } else { + Self::MIN } } diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 818ca7df3e3..676ca5dea5d 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -308,6 +308,7 @@ #![feature(ptr_internals)] #![feature(rustc_attrs)] #![feature(rustc_private)] +#![feature(saturating_div)] #![feature(saturating_int_impl)] #![feature(slice_concat_ext)] #![feature(slice_internals)] -- 2.44.0