Rollup merge of #126042 - davidzeng0:master, r=Amanieu · model-checking/verify-rust-std@75a178f (original) (raw)

Original file line number Diff line number Diff line change
@@ -765,6 +765,67 @@ macro_rules! uint_impl {
765 765 }
766 766 }
767 767
768 + #[doc = concat!(
769 +"Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`",
770 + stringify!($SignedT), "`], returning `None` if overflow occurred."
771 +)]
772 +///
773 + /// # Examples
774 + ///
775 + /// Basic usage:
776 + ///
777 + /// ```
778 + /// #![feature(unsigned_signed_diff)]
779 + #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_signed_diff(2), Some(8));")]
780 + #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_signed_diff(10), Some(-8));")]
781 + #[doc = concat!(
782 +"assert_eq!(",
783 + stringify!($SelfT),
784 +"::MAX.checked_signed_diff(",
785 + stringify!($SignedT),
786 +"::MAX as ",
787 + stringify!($SelfT),
788 +"), None);"
789 +)]
790 + #[doc = concat!(
791 +"assert_eq!((",
792 + stringify!($SignedT),
793 +"::MAX as ",
794 + stringify!($SelfT),
795 +").checked_signed_diff(",
796 + stringify!($SelfT),
797 +"::MAX), Some(",
798 + stringify!($SignedT),
799 +"::MIN));"
800 +)]
801 + #[doc = concat!(
802 +"assert_eq!((",
803 + stringify!($SignedT),
804 +"::MAX as ",
805 + stringify!($SelfT),
806 +" + 1).checked_signed_diff(0), None);"
807 +)]
808 + #[doc = concat!(
809 +"assert_eq!(",
810 + stringify!($SelfT),
811 +"::MAX.checked_signed_diff(",
812 + stringify!($SelfT),
813 +"::MAX), Some(0));"
814 +)]
815 +/// ```
816 + #[unstable(feature = "unsigned_signed_diff", issue = "126041")]
817 + #[inline]
818 +pub const fn checked_signed_diff(self, rhs: Self) -> Option<$SignedT> {
819 +let res = self.wrapping_sub(rhs) as $SignedT;
820 +let overflow = (self >= rhs) == (res < 0);
821 +
822 +if !overflow {
823 +Some(res)
824 +} else {
825 +None
826 +}
827 +}
828 +
768 829 /// Checked integer multiplication. Computes `self * rhs`, returning
769 830 /// `None` if overflow occurred.
770 831 ///