From 80feea2722a76bf8d400e9bbd394914a4d1a200a Mon Sep 17 00:00:00 2001 From: Sam Cappleman-Lynes Date: Thu, 29 Jun 2017 14:07:44 +0100 Subject: [PATCH] Also implement scalar addition for BigInt --- bigint/src/bigint.rs | 20 ++++++++++++++++++++ bigint/src/tests/bigint.rs | 18 ++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/bigint/src/bigint.rs b/bigint/src/bigint.rs index 93f4ae7..dba6a7a 100644 --- a/bigint/src/bigint.rs +++ b/bigint/src/bigint.rs @@ -362,6 +362,26 @@ impl Add for BigInt { } } +forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add); + +impl Add for BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: BigDigit) -> BigInt { + match self.sign { + NoSign => From::from(other), + Plus => BigInt::from_biguint(Plus, self.data + other), + Minus => + match self.data.cmp(&From::from(other)) { + Equal => Zero::zero(), + Less => BigInt::from_biguint(Plus, other - self.data), + Greater => BigInt::from_biguint(Minus, self.data - other), + } + } + } +} + // We want to forward to BigUint::sub, but it's not clear how that will go until // we compare both sign and magnitude. So we duplicate this body for every // val/ref combination, deferring that decision to BigUint's own forwarding. diff --git a/bigint/src/tests/bigint.rs b/bigint/src/tests/bigint.rs index 9e83373..4cdf616 100644 --- a/bigint/src/tests/bigint.rs +++ b/bigint/src/tests/bigint.rs @@ -552,6 +552,24 @@ fn test_add() { } } +#[test] +fn test_scalar_add() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let (nb, nc) = (-&b, -&c); + + if a_vec.len() == 1 { + let a = a_vec[0]; + assert_op!(a + b == c); + assert_op!(b + a == c); + assert_op!(a + nc == nb); + assert_op!(nc + a == nb); + } + } +} + #[test] fn test_sub() { for elm in SUM_TRIPLES.iter() {