]> git.lizzy.rs Git - rust.git/commitdiff
NonZero saturating_mul.
authorIago-lito <iago-lito@etak>
Thu, 15 Apr 2021 10:30:13 +0000 (12:30 +0200)
committerIago-lito <iago-lito@etak>
Wed, 9 Jun 2021 15:28:33 +0000 (17:28 +0200)
library/core/src/num/nonzero.rs

index d48299c0715d9350d7945f14f28cdc7c5ebf112c..7a1b4d6c719bed83987f50ebe7a6ab65df4d3fd3 100644 (file)
@@ -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())) }
+                }
             }
         )+
     }