about summary refs log tree commit diff
diff options
context:
space:
mode:
authorIago-lito <iago-lito@etak>2021-04-15 12:32:48 +0200
committerIago-lito <iago-lito@etak>2021-06-09 17:28:34 +0200
commit7b37800b45e6cf5d06caf2ee21066797516ff43c (patch)
tree6dbf35295e98046adef946e4969765c161a391dc
parent6979bb40f8dd1a67e7508779873e7525441de0ce (diff)
downloadrust-7b37800b45e6cf5d06caf2ee21066797516ff43c.tar.gz
rust-7b37800b45e6cf5d06caf2ee21066797516ff43c.zip
NonZero checked_pow.
-rw-r--r--library/core/src/num/nonzero.rs33
1 files changed, 33 insertions, 0 deletions
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
+                    }
+                }
             }
         )+
     }