Explorar o código

Scalar addition of BigDigit to BigUint

A BigDigit can be added to a BigUint - this is one of several
operations being implemented to allow scalar operations on BigInt and
BigUint across the board.
Sam Cappleman-Lynes %!s(int64=7) %!d(string=hai) anos
pai
achega
a2a28c682e
Modificáronse 2 ficheiros con 37 adicións e 0 borrados
  1. 17 0
      bigint/src/biguint.rs
  2. 20 0
      bigint/src/tests/biguint.rs

+ 17 - 0
bigint/src/biguint.rs

@@ -394,6 +394,23 @@ impl<'a> Add<&'a BigUint> for BigUint {
     }
 }
 
+impl Add<BigDigit> for BigUint {
+    type Output = BigUint;
+
+    #[inline]
+    fn add(mut self, other: BigDigit) -> BigUint {
+        if self.data.len() == 0 {
+            self.data.push(0);
+        }
+
+        let carry = __add2(&mut self.data, &[other]);
+        if carry != 0 {
+            self.data.push(carry);
+        }
+        self
+    }
+}
+
 forward_val_val_binop!(impl Sub for BigUint, sub);
 forward_ref_ref_binop!(impl Sub for BigUint, sub);
 

+ 20 - 0
bigint/src/tests/biguint.rs

@@ -690,6 +690,26 @@ fn test_add() {
     }
 }
 
+#[test]
+fn test_scalar_add() {
+  for elm in SUM_TRIPLES.iter() {
+      let (a_vec, b_vec, c_vec) = *elm;
+      let c = BigUint::from_slice(c_vec);
+
+      if a_vec.len() == 1 {
+          let a = a_vec[0];
+          let b = BigUint::from_slice(b_vec);
+          assert!(b + a == c);
+      }
+
+      if b_vec.len() == 1 {
+          let a = BigUint::from_slice(a_vec);
+          let b = b_vec[0];
+          assert!(a + b == c);
+        }
+    }
+}
+
 #[test]
 fn test_sub() {
     for elm in SUM_TRIPLES.iter() {