part 09: iterator for BigInt
[rust-101.git] / src / part09.rs
1 // Rust-101, Part 09: Iterators (WIP)
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 particular traits again. In particular,
8 // an iterator is something that implements the `Iterator` trait. As you can see in [the documentation](http://doc.rust-lang.org/beta/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 borrowed the number for lifetime `'a`. <br/>
21 // `usize` here is the type of unsigned, pointer-sized numbers. It is typically the type of "lengths of things",
22 // 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.
23 struct Iter<'a> {
24     num: &'a BigInt,
25     idx: usize, // the index of the last number that was returned
26 }
27
28 // Now we are equipped to implement `Iterator` for `Iter`.
29 impl<'a> Iterator for Iter<'a> {
30     // We choose the type of things that we iterate over to be the type of digits, i.e., `u64`.
31     type Item = u64;
32
33     fn next(&mut self) -> Option<u64> {
34         // First, check whether there's any more digits to return.
35         if self.idx == 0 {
36             // We already returned all the digits.
37             None                                                    /*@*/
38         } else {
39             // Decrement, and return next digit.
40             self.idx = self.idx - 1;                                /*@*/
41             Some(self.num.data[self.idx])                           /*@*/
42         }
43     }
44 }
45
46 // All we need now is a function that creates such an iterator for a given `BigInt`.
47 impl BigInt {
48     // 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
49     // the case with functions returning borrowed data, you can elide the lifetime. The rules for adding the lifetimes are exactly the
50     // same. (See the last section of [part 06](part06.html).)
51     fn iter(&self) -> Iter {
52         Iter { num: self, idx: self.data.len() }                    /*@*/
53     }
54 }
55
56 // We are finally ready to iterate! Remember to edit `main.rs` to run this function.
57 pub fn main() {
58     let b = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
59     for digit in b.iter() {
60         println!("{}", digit);
61     }
62 }
63
64 //@ [index](main.html) | [previous](part08.html) | [next](main.html)