Also implement scalar addition for BigInt
This commit is contained in:
parent
1e26bdde81
commit
80feea2722
|
@ -362,6 +362,26 @@ impl Add<BigInt> for BigInt {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
forward_all_scalar_binop_to_val_val_commutative!(impl Add<BigDigit> for BigInt, add);
|
||||||
|
|
||||||
|
impl Add<BigDigit> 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 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
|
// we compare both sign and magnitude. So we duplicate this body for every
|
||||||
// val/ref combination, deferring that decision to BigUint's own forwarding.
|
// val/ref combination, deferring that decision to BigUint's own forwarding.
|
||||||
|
|
|
@ -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]
|
#[test]
|
||||||
fn test_sub() {
|
fn test_sub() {
|
||||||
for elm in SUM_TRIPLES.iter() {
|
for elm in SUM_TRIPLES.iter() {
|
||||||
|
|
Loading…
Reference in New Issue