Handle signs and carry overflow addition for multiplication
All checks were successful
timw4mail/rusty-numbers/pipeline/head This commit looks good

This commit is contained in:
Timothy Warren 2020-04-02 17:01:55 -04:00
parent faa1f548a0
commit b8ab76bbf6

View File

@ -260,19 +260,14 @@ impl Mul for BigInt {
if overflowed {
todo!()
} else {
match res.checked_add(carry) {
Some(res) => {
out.inner.push(res);
carry = 0;
}
None => {
// Well, we have to deal with overflow again
todo!();
}
}
let (res, overflowed) = res.overflowing_add(carry);
out.inner.push(res);
carry = if overflowed { 1 } else { 0 };
}
}
out.sign = Self::get_sign(self, rhs, FracOp::Other);
out.shrink_to_fit();
out
@ -568,6 +563,33 @@ mod tests {
assert_eq!(product.inner[0], 65536usize * 4);
}
#[test]
fn test_mul_signs() {
let a = BigInt::from(2);
let b = BigInt::from(-2);
let product = a * b;
assert_eq!(product.inner[0], 4usize);
assert_eq!(product.sign, Negative);
let a = -BigInt::from(2);
let b = BigInt::from(2);
let product = a * b;
assert_eq!(product.inner[0], 4usize);
assert_eq!(product.sign, Negative);
let a = BigInt::from(-2);
let b = BigInt::from(-2);
let product = a * b;
assert_eq!(product.inner[0], 4usize);
assert_eq!(product.sign, Positive);
let a = BigInt::from(2);
let b = BigInt::from(2);
let product = a * b;
assert_eq!(product.inner[0], 4usize);
assert_eq!(product.sign, Positive);
}
#[test]
#[should_panic]
fn test_mul_overflow() {