part08.rs lines shortened
[rust-101.git] / src / part08.rs
1 // Rust-101, Part 08: Associated Types, Modules
2 // ============================================
3
4 use std::{cmp,ops};
5 use part05::BigInt;
6
7 //@ As our next goal, let us implement addition for our `BigInt`. The main issue here will be
8 //@ dealing with the overflow. First of all, we will have to detect when an overflow happens. This
9 //@ is stored in a so-called *carry* bit, and we have to carry this information on to the next pair
10 //@ of digits we add. The core primitive of addition therefore is to add two digits *and* a carry,
11 //@ and to return the sum digit and the next carry.
12
13 // So, let us write a function to "add with carry", and give it the appropriate type. Notice Rust's
14 // native support for pairs.
15 fn overflowing_add(a: u64, b: u64, carry: bool) -> (u64, bool) {
16
17     //@ Rust's stanza on integer overflows may be a bit surprising: In general, when we write `a +
18     //@ b`, an overflow is considered an *error*. If you compile your program in debug mode, Rust
19     //@ will actually check for that error and panic the program in case of overflows. For
20     //@ performance reasons, no such checks are currently inserted for release builds.
21     //@ The reason for this is that many serious security vulnerabilities have been caused by
22     //@ integer overflows, so just assuming "per default" that they are intended is dangerous.
23     //@ <br/>
24     //@ If you explicitly *do* want an overflow to happen, you can call the `wrapping_add` function
25     //@ (see the
26     //@ [documentation](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.wrapping_add),
27     //@ there are similar functions for other arithmetic operations). There are also similar
28     //@ functions `checked_add` etc. to enforce the overflow check.
29     let sum = a.wrapping_add(b);
30     // If an overflow happened, then the sum will be smaller than *both* summands. Without an
31     // overflow, of course, it will be at least as large as both of them. So, let's just pick one
32     // and check.
33     if sum >= a {
34         // The addition did not overflow. <br/>
35         // **Exercise 08.1**: Write the code to handle adding the carry in this case.
36         let sum_total = sum.wrapping_add(if carry { 1 } else { 0 });/*@@*/
37         let had_overflow = sum_total < sum;                         /*@@*/
38         (sum_total, had_overflow)                                   /*@@*/
39     } else {
40         // Otherwise, the addition *did* overflow. It is impossible for the addition of the carry
41         // to overflow again, as we are just adding 0 or 1.
42         (sum + if carry { 1 } else { 0 }, true)                     /*@*/
43     }
44 }
45
46 // `overflow_add` is a sufficiently intricate function that a test case is justified.
47 // This should also help you to check your solution of the exercise.
48 /*#[test]*/
49 fn test_overflowing_add() {
50     assert_eq!(overflowing_add(10, 100, false), (110, false));
51     assert_eq!(overflowing_add(10, 100, true), (111, false));
52     assert_eq!(overflowing_add(1 << 63, 1 << 63, false), (0, true));
53     assert_eq!(overflowing_add(1 << 63, 1 << 63, true), (1, true));
54     assert_eq!(overflowing_add(1 << 63, (1 << 63) -1 , true), (0, true));
55 }
56
57 // ## Associated Types
58 //@ Now we are equipped to write the addition function for `BigInt`. As you may have guessed, the
59 //@ `+` operator is tied to a trait (`std::ops::Add`), which we are going to implement for
60 //@ `BigInt`.
61 //@ 
62 //@ In general, addition need not be homogeneous: You could add things of different types, like
63 //@ vectors and points. So when implementing `Add` for a type, one has to specify the type of the
64 //@ other operand. In this case, it will also be `BigInt` (and we could have left it away, since
65 //@ that's the default).
66 impl ops::Add<BigInt> for BigInt {
67
68     //@ Besides static functions and methods, traits can contain *associated types*: This is a type
69     //@ chosen by every particular implementation of the trait. The methods of the trait can then
70     //@ refer to that type. In the case of addition, it is used to give the type of the result.
71     //@ (Also see the
72     //@[documentation of `Add`](https://doc.rust-lang.org/stable/std/ops/trait.Add.html).)
73     //@ 
74     //@ In general, you can consider the two `BigInt` given above (in the `impl` line) *input*
75     //@ types of trait search: When `a + b` is invoked with `a` having type `T` and `b` having type
76     //@ `U`, Rust tries to find an implementation of `Add` for `T` where the right-hand type is
77     //@ `U`. The associated types, on the other hand, are *output* types: For every combination of
78     //@ input types, there's a particular result type chosen by the corresponding implementation of
79     //@ `Add`.
80
81     // Here, we choose the result type to be again `BigInt`.
82     type Output = BigInt;
83
84     // Now we can write the actual function performing the addition.
85     fn add(self, rhs: BigInt) -> Self::Output {
86         // We know that the result will be *at least* as long as the longer of the two operands,
87         // so we can create a vector with sufficient capacity to avoid expensive reallocations.
88         let max_len = cmp::max(self.data.len(), rhs.data.len());
89         let mut result_vec:Vec<u64> = Vec::with_capacity(max_len);
90         let mut carry = false; /* the current carry bit */
91         for i in 0..max_len {
92             let lhs_val = if i < self.data.len() { self.data[i] } else { 0 };
93             let rhs_val = if i < rhs.data.len() { rhs.data[i] } else { 0 };
94             // Compute next digit and carry. Then, store the digit for the result, and the carry
95             // for later.
96             //@ Notice how we can obtain names for the two components of the pair that
97             //@ `overflowing_add` returns.
98             let (sum, new_carry) = overflowing_add(lhs_val, rhs_val, carry);    /*@*/
99             result_vec.push(sum);                                               /*@*/
100             carry = new_carry;                                                  /*@*/
101         }
102         // **Exercise 08.2**: Handle the final `carry`, and return the sum.
103         if carry {                                                              /*@@*/
104             result_vec.push(1);                                                 /*@@*/
105         }                                                                       /*@@*/
106         BigInt { data: result_vec }                                             /*@@*/
107     }
108 }
109
110 // ## Traits and reference types
111 //@ If you inspect the addition function above closely, you will notice that it actually consumes
112 //@ ownership of both operands to produce the result. This is, of course, in general not what we
113 //@ want. We'd rather like to be able to add two `&BigInt`.
114
115 // Writing this out becomes a bit tedious, because trait implementations (unlike functions) require
116 // full explicit annotation of lifetimes. Make sure you understand exactly what the following
117 // definition says. Notice that we can implement a trait for a reference type!
118 impl<'a, 'b> ops::Add<&'a BigInt> for &'b BigInt {
119     type Output = BigInt;
120     fn add(self, rhs: &'a BigInt) -> Self::Output {
121         // **Exercise 08.3**: Implement this function.
122         unimplemented!()
123     }
124 }
125
126 // **Exercise 08.4**: Implement the two missing combinations of arguments for `Add`. You should not
127 // have to duplicate the implementation.
128
129 // ## Modules
130 //@ As you learned, tests can be written right in the middle of your development in Rust. However,
131 //@ it is considered good style to bundle all tests together. This is particularly useful in cases
132 //@ where you wrote utility functions for the tests, that no other code should use.
133
134 // Rust calls a bunch of definitions that are grouped together a *module*. You can put the tests in
135 // a submodule as follows.
136 //@ The `cfg` attribute controls whether this module is even compiled: If we added some functions
137 //@ that are useful for testing, Rust would not bother compiling them when you just build your
138 //@ program for normal use. Other than that, tests work as usually.
139
140 #[cfg(test)]
141 mod tests {
142     use part05::BigInt;
143
144     /*#[test]*/
145     fn test_add() {
146         let b1 = BigInt::new(1 << 32);
147         let b2 = BigInt::from_vec(vec![0, 1]);
148
149         assert_eq!(&b1 + &b2, BigInt::from_vec(vec![1 << 32, 1]));
150         // **Exercise 08.5**: Add some more cases to this test.
151     }
152 }
153 //@ As already mentioned, outside of the module, only those items declared public with `pub` may be
154 //@ used. Submodules can access everything defined in their parents. Modules themselves are also
155 //@ hidden from the outside per default, and can be made public with `pub`. When you use an
156 //@ identifier (or, more general, a *path* like `mod1::submod::name`), it is interpreted as being
157 //@ relative to the current module. So, for example, to access `overflowing_add` from within
158 //@ `my_mod`, you would have to give a more explicit path by writing `super::overflowing_add`,
159 //@ which tells Rust to look in the parent module.
160 //@ 
161 //@ You can make names from other modules available locally with `use`. Per default, `use` works
162 //@ globally, so e.g. `use std;` imports the *global* name `std`. By adding `super::` or `self::`
163 //@ to the beginning of the path, you make it relative to the parent or current module,
164 //@ respectively. (You can also explicitly construct an absolute path by starting it with `::`,
165 //@ e.g., `::std::cmp::min`). You can say `pub use path;` to simultaneously *import* names and make
166 //@ them publicly available to others. Finally, you can import all public items of a module at once
167 //@ with `use module::*;`.
168 //@ 
169 //@ Modules can be put into separate files with the syntax `mod name;`. To explain this, let me
170 //@ take a small detour through the Rust compilation process. Cargo starts by invoking`rustc` on
171 //@ the file `src/lib.rs` or `src/main.rs`, depending on whether you compile an application or a
172 //@ library. When `rustc` encounters a `mod name;`, it looks for the files `name.rs` and
173 //@ `name/mod.rs` and goes on compiling there. (It is an error for both of them to exist.)
174 //@ You can think of the contents of the file being embedded at this place. However, only the file
175 //@ where compilation started, and files `name/mod.rs` can load modules from other files. This
176 //@ ensures that the directory structure mirrors the structure of the modules, with `mod.rs`,
177 //@ `lib.rs` and `main.rs` representing a directory or crate itself (similar to, e.g.,
178 //@ `__init__.py` in Python).
179
180 // **Exercise 08.6**: Write a subtraction function, and testcases for it. Decide for yourself how
181 // you want to handle negative results. For example, you may want to return an `Option`, to panic,
182 // or to return `0`.
183
184 //@ [index](main.html) | [previous](part07.html) | [raw source](workspace/src/part08.rs) |
185 //@ [next](part09.html)