Skip to content

Commit

Permalink
replace & with && in {integer}::checked_div
Browse files Browse the repository at this point in the history
Using short-circuit operators makes it easier to perform some kinds of
source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86 assembly is the same
between the old and new versions:

```
xor eax, eax
test esi, esi
je .LBB0_1
cmp edi, -2147483648
jne .LBB0_4
cmp esi, -1
jne .LBB0_4
ret
.LBB0_1:
ret
.LBB0_4:
mov eax, edi
cdq
idiv esi
mov edx, eax
mov eax, 1
ret
```
  • Loading branch information
pietroalbini committed Oct 27, 2021
1 parent a5a8bb0 commit 81130fe
Showing 1 changed file with 1 addition and 2 deletions.
3 changes: 1 addition & 2 deletions library/core/src/num/int_macros.rs
Expand Up @@ -608,8 +608,7 @@ macro_rules! int_impl {
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
// Using `&` helps LLVM see that it is the same check made in division.
if unlikely!(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
if unlikely!(rhs == 0 || ((self == Self::MIN) && (rhs == -1))) {
None
} else {
// SAFETY: div by zero and by INT_MIN have been checked above
Expand Down

0 comments on commit 81130fe

Please sign in to comment.