Skip to content

Commit

Permalink
Merge #200
Browse files Browse the repository at this point in the history
200: Fix scalar divide-by-zero panics r=cuviper a=cuviper

There was a gap where `BigUint::zero() / 0u32` wouldn't actually trigger
an expected panic, since there were no digits, so it just returned 0.

Co-authored-by: Josh Stone <cuviper@gmail.com>
  • Loading branch information
bors[bot] and cuviper committed Mar 14, 2021
2 parents d1e4498 + 5dcf2a1 commit cbfe665
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
8 changes: 8 additions & 0 deletions src/biguint/division.rs
Expand Up @@ -41,6 +41,10 @@ fn div_half(rem: BigDigit, digit: BigDigit, divisor: BigDigit) -> (BigDigit, Big

#[inline]
pub(super) fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit) {
if b == 0 {
panic!("attempt to divide by zero")
}

let mut rem = 0;

if b <= big_digit::HALF {
Expand All @@ -62,6 +66,10 @@ pub(super) fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit)

#[inline]
fn rem_digit(a: &BigUint, b: BigDigit) -> BigDigit {
if b == 0 {
panic!("attempt to divide by zero")
}

let mut rem = 0;

if b <= big_digit::HALF {
Expand Down
11 changes: 10 additions & 1 deletion tests/bigint_scalar.rs
@@ -1,8 +1,9 @@
use num_bigint::BigInt;
use num_bigint::Sign::Plus;
use num_traits::{Signed, ToPrimitive, Zero};
use num_traits::{One, Signed, ToPrimitive, Zero};

use std::ops::Neg;
use std::panic::catch_unwind;

mod consts;
use crate::consts::*;
Expand Down Expand Up @@ -146,3 +147,11 @@ fn test_scalar_div_rem() {
}
}
}

#[test]
fn test_scalar_div_rem_zero() {
catch_unwind(|| BigInt::zero() / 0u32).unwrap_err();
catch_unwind(|| BigInt::zero() % 0u32).unwrap_err();
catch_unwind(|| BigInt::one() / 0u32).unwrap_err();
catch_unwind(|| BigInt::one() % 0u32).unwrap_err();
}
12 changes: 11 additions & 1 deletion tests/biguint_scalar.rs
@@ -1,5 +1,7 @@
use num_bigint::BigUint;
use num_traits::{ToPrimitive, Zero};
use num_traits::{One, ToPrimitive, Zero};

use std::panic::catch_unwind;

mod consts;
use crate::consts::*;
Expand Down Expand Up @@ -111,3 +113,11 @@ fn test_scalar_div_rem() {
}
}
}

#[test]
fn test_scalar_div_rem_zero() {
catch_unwind(|| BigUint::zero() / 0u32).unwrap_err();
catch_unwind(|| BigUint::zero() % 0u32).unwrap_err();
catch_unwind(|| BigUint::one() / 0u32).unwrap_err();
catch_unwind(|| BigUint::one() % 0u32).unwrap_err();
}

0 comments on commit cbfe665

Please sign in to comment.