From 7e0b9a8bd0452a027582f26cd139fa92fba618f7 Mon Sep 17 00:00:00 2001 From: Iago-lito Date: Thu, 15 Apr 2021 12:30:13 +0200 Subject: [PATCH] NonZero saturating_mul. --- library/core/src/num/nonzero.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index d48299c0715..7a1b4d6c719 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -679,6 +679,36 @@ pub const fn checked_mul(self, other: $Ty) -> Option<$Ty> { None } } + + /// Multiply two non-zero integers together. + #[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")] + /// + /// # Examples + /// + /// ``` + /// #![feature(nonzero_ops)] + /// # #![feature(try_trait)] + #[doc = concat!("# use std::num::", stringify!($Ty), ";")] + /// + /// # fn main() -> Result<(), std::option::NoneError> { + #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")] + #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")] + #[doc = concat!("let max = ", stringify!($Ty), "::new(", + stringify!($Int), "::MAX)?;")] + /// + /// assert_eq!(four, two.saturating_mul(two)); + /// assert_eq!(max, four.saturating_mul(max)); + /// # Ok(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_ops", issue = "84186")] + #[inline] + pub const fn saturating_mul(self, other: $Ty) -> $Ty { + // SAFETY: saturating_mul returns u*::MAX on overflow + // and `other` is also non-null + // so the result cannot be zero. + unsafe { $Ty::new_unchecked(self.get().saturating_mul(other.get())) } + } } )+ } -- 2.44.0