Skip to content

Commit 270f75b

Browse files
Rollup merge of #158314 - yilin0518:fix-unchecked_div_exact, r=jhpratt
Fix incorrect unsafe debug assertion in unchecked_div_exact This PR fixes a bug in the `assert_unsafe_precondition!` check for the unstable `unchecked_div_exact` method in signed integers (`int_macros.rs`). ### What is the problem? Currently, the precondition check for signed integers asserts that `rhs > 0`. This causes a panic in debug builds when performing a perfectly valid exact division with a negative divisor (e.g., `-10i32 / -2i32`). The following code snippet will panic in debug mode, but successfully build within release mode: ```rust #![feature(exact_div)] fn main() { let lhs: i32 = -10; let rhs: i32 = -2; unsafe { let result = lhs.unchecked_div_exact(rhs); } } ``` Furthermore, this erroneous `rhs > 0` check renders the overflow prevention logic `(lhs != <$SelfT>::MIN || rhs != -1)` completely unreachable (dead code), since `rhs` could never be `-1` if it is strictly greater than `0`. It appears that it should be `rhs != 0`. ### What does this PR do? - Changes `rhs > 0` to `rhs != 0` in `library/core/src/num/int_macros.rs` to allow valid negative divisors. Tracking issue: #139911
2 parents 31eaed4 + bf86b32 commit 270f75b

1 file changed

Lines changed: 1 addition & 1 deletion

File tree

library/core/src/num/int_macros.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1181,7 +1181,7 @@ macro_rules! int_impl {
11811181
(
11821182
lhs: $SelfT = self,
11831183
rhs: $SelfT = rhs,
1184-
) => rhs > 0 && lhs % rhs == 0 && (lhs != <$SelfT>::MIN || rhs != -1),
1184+
) => rhs != 0 && lhs % rhs == 0 && (lhs != <$SelfT>::MIN || rhs != -1),
11851185
);
11861186
// SAFETY: Same precondition
11871187
unsafe { intrinsics::exact_div(self, rhs) }

0 commit comments

Comments
 (0)