re-do deepaksirone's fix on the actual source file
[rust-101.git] / workspace / src / part09.rs
1 // Rust-101, Part 09: Iterators
2 // ============================
3
4 use part05::BigInt;
5
6
7 pub struct Iter<'a> {
8     num: &'a BigInt,
9     idx: usize, // the index of the last number that was returned
10 }
11
12 // Now we are equipped to implement `Iterator` for `Iter`.
13 impl<'a> Iterator for Iter<'a> {
14     // We choose the type of things that we iterate over to be the type of digits, i.e., `u64`.
15     type Item = u64;
16
17     fn next(&mut self) -> Option<u64> {
18         // First, check whether there's any more digits to return.
19         if self.idx == 0 {
20             // We already returned all the digits, nothing to do.
21             unimplemented!()
22         } else {
23             // Otherwise: Decrement, and return next digit.
24             unimplemented!()
25         }
26     }
27 }
28
29 // All we need now is a function that creates such an iterator for a given `BigInt`.
30 impl BigInt {
31     fn iter(&self) -> Iter {
32         unimplemented!()
33     }
34 }
35
36 // We are finally ready to iterate! Remember to edit `main.rs` to run this function.
37 pub fn main() {
38     let b = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
39     for digit in b.iter() {
40         println!("{}", digit);
41     }
42 }
43
44 // Of course, we don't have to use `for` to apply the iterator. We can also explicitly call `next`.
45 fn print_digits_v1(b: &BigInt) {
46     let mut iter = b.iter();
47     loop {
48         // Each time we go through the loop, we analyze the next element presented by the iterator - until it stops.
49         unimplemented!()
50     }
51 }
52
53 fn print_digits_v2(b: &BigInt) {
54     let mut iter = b.iter();
55     while let Some(digit) = iter.next() {
56         println!("{}", digit)
57     }
58 }
59
60 // **Exercise 09.1**: Write a testcase for the iterator, making sure it yields the corrects numbers.
61 // 
62 // **Exercise 09.2**: Write a function `iter_ldf` that iterators over the digits with the least-significant
63 // digits coming first. Write a testcase for it.
64
65 // ## Iterator invalidation and lifetimes
66
67 fn iter_invalidation_demo() {
68     let mut b = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
69     for digit in b.iter() {
70         println!("{}", digit);
71         /*b = b + BigInt::new(1);*/                                 /* BAD! */
72     }
73 }
74
75 // ## Iterator conversion trait
76
77 impl<'a> IntoIterator for &'a BigInt {
78     type Item = u64;
79     type IntoIter = Iter<'a>;
80     fn into_iter(self) -> Iter<'a> {
81         self.iter()
82     }
83 }
84 // With this in place, you can now replace `b.iter()` in `main` by `&b`. Go ahead and try it! <br/>
85