1 // Rust-101, Part 08: Associated Types, Modules
2 // ============================================
8 // So, let us write a function to "add with carry", and give it the appropriate type. Notice Rust's native support for pairs.
9 fn overflowing_add(a: u64, b: u64, carry: bool) -> (u64, bool) {
10 let sum = u64::wrapping_add(a, b);
11 // If an overflow happened, then the sum will be smaller than *both* summands. Without an overflow, of course, it will be
12 // at least as large as both of them. So, let's just pick one and check.
14 // The addition did not overflow. <br/>
15 // **Exercise 08.1**: Write the code to handle adding the carry in this case.
16 let sum_total = u64::wrapping_add(sum, if carry { 1 } else { 0 }); /*@@*/
17 let had_overflow = sum_total < sum; /*@@*/
18 (sum_total, had_overflow) /*@@*/
20 // Otherwise, the addition *did* overflow. It is impossible for the addition of the carry
21 // to overflow again, as we are just adding 0 or 1.
26 // `overflow_add` is a sufficiently intricate function that a test case is justified.
27 // This should also help you to check your solution of the exercise.
29 fn test_overflowing_add() {
30 assert_eq!(overflowing_add(10, 100, false), (110, false));
31 assert_eq!(overflowing_add(10, 100, true), (111, false));
32 assert_eq!(overflowing_add(1 << 63, 1 << 63, false), (0, true));
33 assert_eq!(overflowing_add(1 << 63, 1 << 63, true), (1, true));
34 assert_eq!(overflowing_add(1 << 63, (1 << 63) -1 , true), (0, true));
37 // ## Associated Types
38 impl ops::Add<BigInt> for BigInt {
40 // Here, we choose the result type to be again `BigInt`.
43 // Now we can write the actual function performing the addition.
44 fn add(self, rhs: BigInt) -> Self::Output {
45 // We know that the result will be *at least* as long as the longer of the two operands,
46 // so we can create a vector with sufficient capacity to avoid expensive reallocations.
47 let max_len = cmp::max(self.data.len(), rhs.data.len());
48 let mut result_vec:Vec<u64> = Vec::with_capacity(max_len);
49 let mut carry = false; /* the current carry bit */
51 let lhs_val = if i < self.data.len() { self.data[i] } else { 0 };
52 let rhs_val = if i < rhs.data.len() { rhs.data[i] } else { 0 };
53 // Compute next digit and carry. Then, store the digit for the result, and the carry for later.
56 // **Exercise 08.2**: Handle the final `carry`, and return the sum.
58 result_vec.push(1); /*@@*/
60 BigInt { data: result_vec } /*@@*/
64 // ## Traits and borrowed types
66 // Writing this out becomes a bit tedious, because trait implementations (unlike functions) require full explicit annotation
67 // of lifetimes. Make sure you understand exactly what the following definition says. Notice that we can implement a trait for
69 impl<'a, 'b> ops::Add<&'a BigInt> for &'b BigInt {
71 fn add(self, rhs: &'a BigInt) -> Self::Output {
72 // **Exercise 08.3**: Implement this function.
77 // **Exercise 08.4**: Implement the two missing combinations of arguments for `Add`. You should not have to duplicate the implementation.
81 // Rust calls a bunch of definitions that are grouped together a *module*. You can put the tests in a submodule as follows.
86 let b1 = BigInt::new(1 << 32);
87 let b2 = BigInt::from_vec(vec![0, 1]);
89 assert_eq!(&b1 + &b2, BigInt::from_vec(vec![1 << 32, 1]));
90 // **Exercise 08.5**: Add some more cases to this test.
94 // **Exercise 08.6**: Write a subtraction function, and testcases for it. Decide for yourself how you want to handle negative results.
95 // For example, you may want to return an `Option`, to panic, or to return `0`.