Skip to content

Commit cbfe665

Browse files
bors[bot]cuviper
andauthored
Merge #200
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>
2 parents d1e4498 + 5dcf2a1 commit cbfe665

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

src/biguint/division.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@ fn div_half(rem: BigDigit, digit: BigDigit, divisor: BigDigit) -> (BigDigit, Big
4141

4242
#[inline]
4343
pub(super) fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit) {
44+
if b == 0 {
45+
panic!("attempt to divide by zero")
46+
}
47+
4448
let mut rem = 0;
4549

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

6367
#[inline]
6468
fn rem_digit(a: &BigUint, b: BigDigit) -> BigDigit {
69+
if b == 0 {
70+
panic!("attempt to divide by zero")
71+
}
72+
6573
let mut rem = 0;
6674

6775
if b <= big_digit::HALF {

tests/bigint_scalar.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
use num_bigint::BigInt;
22
use num_bigint::Sign::Plus;
3-
use num_traits::{Signed, ToPrimitive, Zero};
3+
use num_traits::{One, Signed, ToPrimitive, Zero};
44

55
use std::ops::Neg;
6+
use std::panic::catch_unwind;
67

78
mod consts;
89
use crate::consts::*;
@@ -146,3 +147,11 @@ fn test_scalar_div_rem() {
146147
}
147148
}
148149
}
150+
151+
#[test]
152+
fn test_scalar_div_rem_zero() {
153+
catch_unwind(|| BigInt::zero() / 0u32).unwrap_err();
154+
catch_unwind(|| BigInt::zero() % 0u32).unwrap_err();
155+
catch_unwind(|| BigInt::one() / 0u32).unwrap_err();
156+
catch_unwind(|| BigInt::one() % 0u32).unwrap_err();
157+
}

tests/biguint_scalar.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
use num_bigint::BigUint;
2-
use num_traits::{ToPrimitive, Zero};
2+
use num_traits::{One, ToPrimitive, Zero};
3+
4+
use std::panic::catch_unwind;
35

46
mod consts;
57
use crate::consts::*;
@@ -111,3 +113,11 @@ fn test_scalar_div_rem() {
111113
}
112114
}
113115
}
116+
117+
#[test]
118+
fn test_scalar_div_rem_zero() {
119+
catch_unwind(|| BigUint::zero() / 0u32).unwrap_err();
120+
catch_unwind(|| BigUint::zero() % 0u32).unwrap_err();
121+
catch_unwind(|| BigUint::one() / 0u32).unwrap_err();
122+
catch_unwind(|| BigUint::one() % 0u32).unwrap_err();
123+
}

0 commit comments

Comments
 (0)