Implement unsigned_signed_diff · patricklam/verify-rust-std@5fc66dd (original) (raw)

Original file line number Diff line number Diff line change
@@ -726,6 +726,67 @@ macro_rules! uint_impl {
726 726 }
727 727 }
728 728
729 + #[doc = concat!(
730 +"Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`",
731 + stringify!($SignedT), "`], returning `None` if overflow occurred."
732 +)]
733 +///
734 + /// # Examples
735 + ///
736 + /// Basic usage:
737 + ///
738 + /// ```
739 + /// #![feature(unsigned_signed_diff)]
740 + #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_signed_diff(2), Some(8));")]
741 + #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_signed_diff(10), Some(-8));")]
742 + #[doc = concat!(
743 +"assert_eq!(",
744 + stringify!($SelfT),
745 +"::MAX.checked_signed_diff(",
746 + stringify!($SignedT),
747 +"::MAX as ",
748 + stringify!($SelfT),
749 +"), None);"
750 +)]
751 + #[doc = concat!(
752 +"assert_eq!((",
753 + stringify!($SignedT),
754 +"::MAX as ",
755 + stringify!($SelfT),
756 +").checked_signed_diff(",
757 + stringify!($SelfT),
758 +"::MAX), Some(",
759 + stringify!($SignedT),
760 +"::MIN));"
761 +)]
762 + #[doc = concat!(
763 +"assert_eq!((",
764 + stringify!($SignedT),
765 +"::MAX as ",
766 + stringify!($SelfT),
767 +" + 1).checked_signed_diff(0), None);"
768 +)]
769 + #[doc = concat!(
770 +"assert_eq!(",
771 + stringify!($SelfT),
772 +"::MAX.checked_signed_diff(",
773 + stringify!($SelfT),
774 +"::MAX), Some(0));"
775 +)]
776 +/// ```
777 + #[unstable(feature = "unsigned_signed_diff", issue = "126041")]
778 + #[inline]
779 +pub const fn checked_signed_diff(self, rhs: Self) -> Option<$SignedT> {
780 +let res = self.wrapping_sub(rhs) as $SignedT;
781 +let overflow = (self >= rhs) == (res < 0);
782 +
783 +if !overflow {
784 +Some(res)
785 +} else {
786 +None
787 +}
788 +}
789 +
729 790 /// Checked integer multiplication. Computes `self * rhs`, returning
730 791 /// `None` if overflow occurred.
731 792 ///