Skip to content

Commit 75a178f

Browse files
authored
Rollup merge of rust-lang#126042 - davidzeng0:master, r=Amanieu
Implement `unsigned_signed_diff` <!-- If this PR is related to an unstable feature or an otherwise tracked effort, please link to the relevant tracking issue here. If you don't know of a related tracking issue or there are none, feel free to ignore this. This PR will get automatically assigned to a reviewer. In case you would like a specific user to review your work, you can assign it to them by using r​? <reviewer name> --> Implements rust-lang#126041
2 parents 1e118ae + 5fc66dd commit 75a178f

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

core/src/num/uint_macros.rs

+61
Original file line numberDiff line numberDiff line change
@@ -765,6 +765,67 @@ macro_rules! uint_impl {
765765
}
766766
}
767767

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

0 commit comments

Comments
 (0)