Skip to content

Commit

Permalink
Replace an assert! with debug_assert! in u256::shr
Browse files Browse the repository at this point in the history
The implementation came from the `compiler_builtins` port but this
should be weakened to match other integer types.
  • Loading branch information
tgross35 committed Feb 8, 2025
1 parent d202e8f commit 22c83fe
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/math/support/big.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,10 @@ impl ops::Shr<u32> for u256 {
type Output = Self;

fn shr(self, rhs: u32) -> Self::Output {
assert!(rhs < Self::BITS, "attempted to shift right with overflow");
debug_assert!(rhs < Self::BITS, "attempted to shift right with overflow");
if rhs >= Self::BITS {
return Self::ZERO;
}

if rhs == 0 {
return self;
Expand Down
19 changes: 19 additions & 0 deletions src/math/support/big/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,22 @@ fn shr_u128() {
}
assert!(errors.is_empty());
}

#[test]
#[should_panic]
#[cfg(debug_assertions)]
// FIXME(ppc): ppc64le seems to have issues with `should_panic` tests.
#[cfg(not(all(target_arch = "powerpc64", target_endian = "little")))]
fn shr_u256_overflow() {
// Like regular shr, panic on overflow with debug assertions
let _ = u256::MAX >> 256;
}

#[test]
#[cfg(not(debug_assertions))]
fn shr_u256_overflow() {
// No panic without debug assertions
assert_eq!(u256::MAX >> 256, u256::ZERO);
assert_eq!(u256::MAX >> 257, u256::ZERO);
assert_eq!(u256::MAX >> u32::MAX, u256::ZERO);
}

0 comments on commit 22c83fe

Please sign in to comment.