From b8ab76bbf684b03446888fb8189da0c9a7ba00d5 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Thu, 2 Apr 2020 17:01:55 -0400 Subject: [PATCH] Handle signs and carry overflow addition for multiplication --- src/bigint.rs | 42 ++++++++++++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/src/bigint.rs b/src/bigint.rs index d43024b..0e4341d 100644 --- a/src/bigint.rs +++ b/src/bigint.rs @@ -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() {