+ // We know that the result will be *at least* as long as the longer of the two operands,
+ // so we can create a vector with sufficient capacity to avoid expensive reallocations.
+ let max_len = cmp::max(self.data.len(), rhs.data.len());
+ let mut result_vec:Vec<u64> = Vec::with_capacity(max_len);
+ let mut carry = false; /* the current carry bit */
+ for i in 0..max_len {
+ let lhs_val = if i < self.data.len() { self.data[i] } else { 0 };
+ let rhs_val = if i < rhs.data.len() { rhs.data[i] } else { 0 };
+ // Compute next digit and carry. Then, store the digit for the result, and the carry
+ // for later.
+ //@ Notice how we can obtain names for the two components of the pair that
+ //@ `overflowing_add` returns.
+ let (sum, new_carry) = overflowing_add(lhs_val, rhs_val, carry); /*@*/
+ result_vec.push(sum); /*@*/
+ carry = new_carry; /*@*/
+ }
+ // **Exercise 08.2**: Handle the final `carry`, and return the sum.
+ if carry { /*@@*/
+ result_vec.push(1); /*@@*/
+ } /*@@*/
+ BigInt { data: result_vec } /*@@*/
+ }
+}
+
+// ## Traits and reference types
+//@ If you inspect the addition function above closely, you will notice that it actually consumes
+//@ ownership of both operands to produce the result. This is, of course, in general not what we
+//@ want. We'd rather like to be able to add two `&BigInt`.
+
+// Writing this out becomes a bit tedious, because trait implementations (unlike functions) require
+// full explicit annotation of lifetimes. Make sure you understand exactly what the following
+// definition says. Notice that we can implement a trait for a reference type!
+impl<'a, 'b> ops::Add<&'a BigInt> for &'b BigInt {
+ type Output = BigInt;
+ fn add(self, rhs: &'a BigInt) -> Self::Output {
+ // **Exercise 08.3**: Implement this function.
+ unimplemented!()
+ }
+}
+
+// **Exercise 08.4**: Implement the two missing combinations of arguments for `Add`. You should not
+// have to duplicate the implementation.
+
+// ## Modules
+//@ As you learned, tests can be written right in the middle of your development in Rust. However,
+//@ it is considered good style to bundle all tests together. This is particularly useful in cases
+//@ where you wrote utility functions for the tests, that no other code should use.
+
+// Rust calls a bunch of definitions that are grouped together a *module*. You can put the tests in
+// a submodule as follows.
+//@ The `cfg` attribute controls whether this module is even compiled: If we added some functions
+//@ that are useful for testing, Rust would not bother compiling them when you just build your
+//@ program for normal use. Other than that, tests work as usually.
+
+#[cfg(test)]
+mod tests {
+ use part05::BigInt;
+
+ /*#[test]*/
+ fn test_add() {
+ let b1 = BigInt::new(1 << 32);
+ let b2 = BigInt::from_vec(vec![0, 1]);
+
+ assert_eq!(&b1 + &b2, BigInt::from_vec(vec![1 << 32, 1]));
+ // **Exercise 08.5**: Add some more cases to this test.