@@ -641,6 +641,64 @@ nonzero_signed_operations! {
641
641
NonZeroIsize(isize) -> NonZeroUsize(usize);
642
642
}
643
643
644
+ // A bunch of methods for both signed and unsigned nonzero types.
645
+ macro_rules! nonzero_unsigned_signed_operations {
646
+ ( $( $Ty: ident($Int: ty); )+ ) => {
647
+ $(
648
+ impl $Ty {
649
+ /// Multiply two non-zero integers together.
650
+ /// Return [`None`] on overflow.
651
+ ///
652
+ /// # Examples
653
+ ///
654
+ /// ```
655
+ /// #![feature(nonzero_ops)]
656
+ /// # #![feature(try_trait)]
657
+ #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
658
+ ///
659
+ /// # fn main() -> Result<(), std::option::NoneError> {
660
+ #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
661
+ #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
662
+ #[doc = concat!("let max = ", stringify!($Ty), "::new(",
663
+ stringify!($Int), "::MAX)?;")]
664
+ ///
665
+ /// assert_eq!(Some(four), two.checked_mul(two));
666
+ /// assert_eq!(None, max.checked_mul(two));
667
+ /// # Ok(())
668
+ /// # }
669
+ /// ```
670
+ #[unstable(feature = "nonzero_ops", issue = "84186")]
671
+ #[inline]
672
+ pub const fn checked_mul(self, other: $Ty) -> Option<$Ty> {
673
+ if let Some(result) = self.get().checked_mul(other.get()) {
674
+ // SAFETY: checked_mul returns None on overflow
675
+ // and `other` is also non-null
676
+ // so the result cannot be zero.
677
+ Some(unsafe { $Ty::new_unchecked(result) })
678
+ } else {
679
+ None
680
+ }
681
+ }
682
+ }
683
+ )+
684
+ }
685
+ }
686
+
687
+ nonzero_unsigned_signed_operations! {
688
+ NonZeroU8(u8);
689
+ NonZeroU16(u16);
690
+ NonZeroU32(u32);
691
+ NonZeroU64(u64);
692
+ NonZeroU128(u128);
693
+ NonZeroUsize(usize);
694
+ NonZeroI8(i8);
695
+ NonZeroI16(i16);
696
+ NonZeroI32(i32);
697
+ NonZeroI64(i64);
698
+ NonZeroI128(i128);
699
+ NonZeroIsize(isize);
700
+ }
701
+
644
702
macro_rules! nonzero_unsigned_is_power_of_two {
645
703
( $( $Ty: ident )+ ) => {
646
704
$(
0 commit comments