Skip to content

Commit 46b8495

Browse files
committed
Implement unsigned_signed_diff
1 parent c1dba09 commit 46b8495

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

library/core/src/num/uint_macros.rs

+61
Original file line numberDiff line numberDiff line change
@@ -726,6 +726,67 @@ macro_rules! uint_impl {
726726
}
727727
}
728728

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+
729790
/// Checked integer multiplication. Computes `self * rhs`, returning
730791
/// `None` if overflow occurred.
731792
///

0 commit comments

Comments
 (0)