From 7b37800b45e6cf5d06caf2ee21066797516ff43c Mon Sep 17 00:00:00 2001 From: Iago-lito Date: Thu, 15 Apr 2021 12:32:48 +0200 Subject: [PATCH] NonZero checked_pow. --- library/core/src/num/nonzero.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index fdb874bc723..ceb2e461387 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -737,6 +737,39 @@ macro_rules! nonzero_unsigned_signed_operations { // SAFETY: The caller ensures there is no overflow. unsafe { $Ty::new_unchecked(self.get().unchecked_mul(other.get())) } } + + /// Raise non-zero value to an integer power. + /// Return [`None`] 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 three = ", stringify!($Ty), "::new(3)?;")] + #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")] + #[doc = concat!("let half_max = ", stringify!($Ty), "::new(", + stringify!($Int), "::MAX / 2)?;")] + /// + /// assert_eq!(Some(twenty_seven), three.checked_pow(3)); + /// assert_eq!(None, half_max.checked_pow(3)); + /// # Ok(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_ops", issue = "84186")] + #[inline] + pub const fn checked_pow(self, other: u32) -> Option<$Ty> { + if let Some(result) = self.get().checked_pow(other) { + // SAFETY: checked_pow returns None on overflow + // so the result cannot be zero. + Some(unsafe { $Ty::new_unchecked(result) }) + } else { + None + } + } } )+ }