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