start doing the course-part of BigInt
[rust-101.git] / src / part05.rs
1 // Rust-101, Part 05: Copy, Clone
2 // ==============================
3
4 use std::cmp;
5 use std::ops;
6
7 // In the course of the next few parts, we are going to build a data-structure for
8 // computations with *bug* numbers. We would like to not have an upper bound
9 // to how large these numbers can get, with the memory of the machine being the
10 // only limit.
11 // 
12 // We start by deciding how to represent such big numbers. One possibility here is
13 // to use a vector of "small" numbers, which we will then consider the "digits"
14 // of the big number. This is like "1337" being a vector of 4 small numbers (1, 3, 3, 7),
15 // except that we will use `u64` as type of our base numbers. Now we just have to decide
16 // the order in which we store numbers. I decided that we will store the least significant
17 // digit first. This means that "1337" would actually become (7, 3, 3, 1).<br/>
18 // Finally, we declare that there must not be any trailing zeros (corresponding to
19 // useless leading zeros in our usual way of writing numbers). This is to ensure that
20 // the same number can only be stored in one way.
21
22 // To write this down in Rust, we use a `struct`, which is a lot like structs in C:
23 // Just a collection of a bunch of named fields. Every field can be private to the current module
24 // (which is the default), or public (which would be indicated by a `pub` in front of the name).
25 // For the sake of the tutorial, we make `dat` public - otherwise, the next parts of this
26 // course could not work on `BigInt`s. Of course, in a real program, one would make the field
27 // private to ensure that the invariant (no trailing zeros) is maintained.
28 pub struct BigInt {
29     pub data: Vec<u64>,
30 }
31
32 // Now that we fixed the data representation, we can start implementing methods on it.
33 impl BigInt {
34     // Let's start with a constructor, creating a `BigInt` from an ordinary integer.
35     // To create an instance of a struct, we write its name followed by a list of
36     // fields and initial values assigned to them.
37     pub fn new(x: u64) -> Self {
38         if x == 0 {
39             BigInt { data: vec![] }
40         } else {
41             BigInt { data: vec![x] }
42         }
43     }
44
45     // It can often be useful to encode the invariant of a data-structure in code, so here
46     // is a check that detects useless trailing zeros.
47     pub fn test_invariant(&self) -> bool {
48         if self.data.len() == 0 {
49             true
50         } else {
51             self.data[self.data.len() - 1] != 0
52         }
53     }
54
55     // We can convert any vector of digits into a number, by removing trailing zeros. The `mut`
56     // declaration for `v` here is just like the one in `let mut ...`, it says that we will locally
57     // change the vector `v`. In this case, we need to make that annotation to be able to call `pop`
58     // on `v`.
59     pub fn from_vec(mut v: Vec<u64>) -> Self {
60         while v.len() > 0 && v[v.len()-1] == 0 {
61             v.pop();
62         }
63         BigInt { data: v }
64     }
65 }
66
67 // If you have a close look at the type of `BigInt::from_vec`, you will notice that it
68 // consumes the vector `v`. The caller hence loses access. There is however something
69 // we can do if we don't want that to happen: We can explicitly `clone` the vector,
70 // which means that a full (or *deep*) copy will be performed. Technically,
71 // `clone` takes a borrowed vector, and returns a fully owned one.
72 fn clone_demo() {
73     let v = vec![0,1 << 16];
74     let b1 = BigInt::from_vec(v.clone());
75     let b2 = BigInt::from_vec(v);
76 }
77
78 // To be clonable is a property of a type, and as such, naturally expressed with a trait.
79 // In fact, Rust already comes with a trait `Clone` for exactly this purpose. We can hence
80 // make our `BigInt` clonable as well.
81 impl Clone for BigInt {
82     fn clone(&self) -> Self {
83         BigInt { data: self.data.clone() }
84     }
85 }
86 // Making a type clonable is such a common exercise that Rust can even help you doing it:
87 // If you add `#[derive(Clone)]' right in front of the definition of `BigInt`, Rust will
88 // generate an implementation of `clone` that simply clones all the fields. Try it!
89 // 
90 // To put this in perspective, `clone` in Rust corresponds to what people usually manually do in
91 // the copy constructor of a C++ class: It creates new, independent instance containing the
92 // same values. Contrary to that, if you pass something to a function normally (like the
93 // second call to `from_vec` in `clone_demo`), only a *shallow* copy is created: The fields
94 // are copied, but pointers are simply duplicated. This corresponds to the default copy
95 // constructor in C++. Rust assumes that after such a copy, the old value is useless
96 // (as the new one uses the same pointers), and hence considers the data semantically
97 // moved to the copy. That's another explanation of why Rust does not let you access
98 // a vector anymore after you passed ownership to some function.
99
100 // With `BigInt` being about numbers, we should be able to write a version of `vec_min`
101 // that computes the minimum of a list of `BigInt`. We start by writing `min` for
102 // `BigInt`. Now our assumption of having no trailing zeros comes in handy!
103 impl BigInt {
104     fn min(self, other: Self) -> Self {
105         // Just to be sure, we first check that both operands actually satisfy our invariant.
106         // `debug_assert!` is a macro that checks that its argument (must be of type `bool`)
107         // is `true`, and panics otherwise. It gets removed in release builds, which you do with
108         // `cargo build --release`.
109         // 
110         // If you carefully check the type of `BigInt::test_invariant`, you may be surprised that
111         // we can call the function this way. Doesn't it take `self` in borrowed form? Indeed,
112         // the explicit way to do that would be to call `(&other).test_invariant()`. However, the
113         // `self` argument of a method is treated specially by Rust, and borrowing happens automatically here.
114         debug_assert!(self.test_invariant() && other.test_invariant());
115         // If the lengths of the two numbers differ, we already know which is larger.
116         if self.data.len() < other.data.len() {
117             self
118         } else if self.data.len() > other.data.len() {
119             other
120         } else {
121             // **Exercise**: Fill in this code.
122             panic!("Not yet implemented.");
123         }
124     }
125 }
126
127 fn vec_min(v: &Vec<BigInt>) -> Option<BigInt> {
128     let mut min: Option<BigInt> = None;
129     for e in v {
130         // In the loop, `e` now has type `&i32`, so we have to dereference it.
131         min = Some(match min {
132             None => e.clone(),
133             Some(n) => e.clone().min(n)
134         });
135     }
136     min
137 }