浏览代码

Also implement scalar addition for BigInt

Sam Cappleman-Lynes 7 年之前
父节点
当前提交
80feea2722
共有 2 个文件被更改,包括 38 次插入0 次删除
  1. 20 0
      bigint/src/bigint.rs
  2. 18 0
      bigint/src/tests/bigint.rs

+ 20 - 0
bigint/src/bigint.rs

@@ -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 compare both sign and magnitude.  So we duplicate this body for every
 // val/ref combination, deferring that decision to BigUint's own forwarding.

+ 18 - 0
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() {