Fixes as per review.
[rust-101.git] / src / part09.rs
1 // Rust-101, Part 09: Iterators
2 // ============================
3
4 use part05::BigInt;
5
6 //@ In the following, we will look into the iterator mechanism of Rust and make our `BigInt`
7 //@ compatible with the `for` loops. Of course, this is all about implementing certain traits
8 //@ again. In particular, an iterator is something that implements the `Iterator` trait. As you can
9 //@ see in the [documentation](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html), this
10 //@ trait mandates a single function `next` returning an `Option<Self::Item>`, where `Item` is an
11 //@ associated type chosen by the implementation. (There are many more methods provided for
12 //@ `Iterator`, but they all have default implementations, so we don't have to worry about them
13 //@ right now.)
14 //@ 
15 //@ For the case of `BigInt`, we want our iterator to iterate over the digits in normal, notational
16 //@ order: The most-significant digit comes first. So, we have to write down some type, and
17 //@ implement `Iterator` for it such that `next` returns the digits one-by-one. Clearly, the
18 //@ iterator must somehow be able to access the number it iterates over, and it must store its
19 //@ current location. However, it cannot *own* the `BigInt`, because then the number would be gone
20 //@ after iteration! That'd certainly be bad. The only alternative is for the iterator to *borrow*
21 //@ the number, so it takes a reference.
22
23 //@ In writing this down, we again have to be explicit about the lifetime of the reference: We
24 //@ can't just have an `Iter`, we must have an `Iter<'a>` that borrows the number for lifetime
25 //@ `'a`. This is our first example of a data-type that's polymorphic in a lifetime, as opposed to
26 //@ a type. <br/>
27 //@ `usize` here is the type of unsigned, pointer-sized numbers. It is typically the type of
28 //@ "lengths of things", in particular, it is the type of the length of a `Vec` and hence the right
29 //@ type to store an offset into the vector of digits.
30 pub struct Iter<'a> {
31     num: &'a BigInt,
32     idx: usize, // the index of the last number that was returned
33 }
34
35 // Now we are equipped to implement `Iterator` for `Iter`.
36 impl<'a> Iterator for Iter<'a> {
37     // We choose the type of things that we iterate over to be the type of digits, i.e., `u64`.
38     type Item = u64;
39
40     fn next(&mut self) -> Option<u64> {
41         // First, check whether there's any more digits to return.
42         if self.idx == 0 {
43             // We already returned all the digits, nothing to do.
44             None                                                    /*@*/
45         } else {
46             // Otherwise: Decrement, and return next digit.
47             self.idx = self.idx - 1;                                /*@*/
48             Some(self.num.data[self.idx])                           /*@*/
49         }
50     }
51 }
52
53 // All we need now is a function that creates such an iterator for a given `BigInt`.
54 impl BigInt {
55     //@ Notice that when we write the type of `iter`, we don't actually have to give the lifetime
56     //@ parameter of `Iter`. Just as it is the case with functions returning references, you can
57     //@ elide the lifetime. The rules for adding the lifetimes are exactly the same. (See the last
58     //@ section of [part 06](part06.html).)
59     fn iter(&self) -> Iter {
60         Iter { num: self, idx: self.data.len() }                    /*@*/
61     }
62 }
63
64 // We are finally ready to iterate! Remember to edit `main.rs` to run this function.
65 pub fn main() {
66     let b = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
67     for digit in b.iter() {
68         println!("{}", digit);
69     }
70 }
71
72 // Of course, we don't have to use `for` to apply the iterator. We can also explicitly call `next`.
73 fn print_digits_v1(b: &BigInt) {
74     let mut iter = b.iter();
75     //@ `loop` is the keyword for a loop without a condition: It runs endlessly, or until you break
76     //@ out of it with `break` or `return`.
77     loop {
78         // Each time we go through the loop, we analyze the next element presented by the iterator
79         // - until it stops.
80         match iter.next() {                                         /*@*/
81             None => break,                                          /*@*/
82             Some(digit) => println!("{}", digit)                    /*@*/
83         }                                                           /*@*/
84     }
85 }
86
87 //@ Now, it turns out that this combination of doing a loop and a pattern matching is fairly
88 //@ common, and Rust provides some convenient syntactic sugar for it.
89 fn print_digits_v2(b: &BigInt) {
90     let mut iter = b.iter();
91     //@ `while let` performs the given pattern matching on every round of the loop, and cancels the
92     //@ loop if the pattern doesn't match. There's also `if let`, which works similar, but of
93     //@ course without the loopy part.
94     while let Some(digit) = iter.next() {
95         println!("{}", digit)
96     }
97 }
98
99 // **Exercise 09.1**: Write a testcase for the iterator, making sure it yields the corrects numbers.
100 // 
101 // **Exercise 09.2**: Write a function `iter_ldf` that iterates over the digits with the
102 // least-significant digits coming first. Write a testcase for it.
103
104 // ## Iterator invalidation and lifetimes
105 //@ You may have been surprised that we had to explicitly annotate a lifetime when we wrote `Iter`.
106 //@ Of course, with lifetimes being present at every reference in Rust, this is only consistent.
107 //@ But do we at least gain something from this extra annotation burden? (Thankfully, this burden
108 //@ only occurs when we define *types*, and not when we define functions - which is typically much
109 //@ more common.)
110
111 //@ It turns out that the answer to this question is yes! This particular aspect of the concept of
112 //@ lifetimes helps Rust to eliminate the issue of *iterator invalidation*. Consider the following
113 //@ piece of code.
114 fn iter_invalidation_demo() {
115     let mut b = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
116     for digit in b.iter() {
117         println!("{}", digit);
118         /*b = b + BigInt::new(1);*/                                 /* BAD! */
119     }
120 }
121 //@ If you enable the bad line, Rust will reject the code. Why? The problem is that we are
122 //@ modifying the number while iterating over it. In other languages, this can have all sorts of
123 //@ effects from inconsistent data or throwing an exception (Java) to bad pointers being
124 //@ dereferenced (C++). Rust, however, is able to detect this situation.
125 //@ When you call `iter`, you have to borrow `b` for some lifetime `'a`, and you obtain `Iter<'a>`.
126 //@ This is an iterator that's only valid for lifetime `'a`. Gladly, we have this annotation
127 //@ available to make such a statement. Rust enforces that `'a` spans every call to `next`, which
128 //@ means it has to span the loop.
129 //@ Thus `b` is borrowed for the duration of the loop, and we cannot mutate it. This is yet another
130 //@ example for how the combination of mutation and aliasing leads to undesired effects (not
131 //@ necessarily crashes, think of Java), which Rust successfully prevents.
132
133 // ## Iterator conversion trait
134 //@ If you closely compare the `for` loop in `main` above, with the one in `part06::vec_min`, you
135 //@ will notice that we were able to write `for e in v` earlier, but now we have to call `iter`.
136 //@ Why is that? Well, the `for` sugar is not actually tied to `Iterator`. Instead, it demands an
137 //@ implementation of
138 //@ [`IntoIterator`](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html).
139 //@ That's a trait of types that provide a *conversion* function into some kind of iterator. These
140 //@ conversion traits are a frequent pattern in Rust: Rather than demanding that something is an
141 //@ iterator, or a string, or whatever; one demands that something can be converted to an
142 //@ iterator/string/whatever. This provides convenience similar to overloading of functions: The
143 //@ function can be called with lots of different types.
144 //@ By implementing such traits for your types, you can even make your own types work smoothly with
145 //@ existing library functions. As usually for Rust, this abstraction comes at zero cost: If your
146 //@ data is already of the right type, the conversion function will not do anything and trivially
147 //@ be optimized away.
148
149 //@ If you have a look at the documentation of `IntoIterator`, you will notice that the function
150 //@ `into_iter` it provides actually consumes its argument. So we implement the trait for
151 //@ *references to* numbers, such that the number is not lost after the iteration.
152 impl<'a> IntoIterator for &'a BigInt {
153     type Item = u64;
154     type IntoIter = Iter<'a>;
155     fn into_iter(self) -> Iter<'a> {
156         self.iter()
157     }
158 }
159 // With this in place, you can now replace `b.iter()` in `main` by `&b`. Go ahead and try it! <br/>
160 //@ Wait, `&b`? Why that? Well, we implemented `IntoIterator` for `&BigInt`. If we are in a place
161 //@ where `b` is already borrowed, we can just do `for digit in b`. If however, we own `b`, we have
162 //@ to create a reference to it. Alternatively, we could implement `IntoIterator` for `BigInt` -
163 //@ which, as already mentioned, would mean that `b` is actually consumed by the iteration, and
164 //@ gone.
165 //@ This can easily happen, for example, with a `Vec`: Both `Vec` and `&Vec` (and `&mut Vec`)
166 //@ implement `IntoIterator`, so if you do `for e in v`, and `v` has type `Vec`, then you will
167 //@ obtain ownership of the elements during the iteration - and destroy the vector in the process.
168 //@ We actually did that in `part01::vec_min`, but we did not care. You can write `for e in &v` or
169 //@ `for e in v.iter()` to avoid this.
170
171 //@ [index](main.html) | [previous](part08.html) | [raw source](workspace/src/part09.rs) |
172 //@ [next](part10.html)