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