tweaking here and there, plans for the future
[rust-101.git] / src / part05.rs
1 // Rust-101, Part 05: Clone
2 // ========================
3
4 // ## Big Numbers
5 // In the course of the next few parts, we are going to build a data-structure for computations with
6 // *big* numbers. We would like to not have an upper bound to how large these numbers can get, with
7 // the memory of the machine being the only limit.
8 // 
9 // We start by deciding how to represent such big numbers. One possibility here is
10 // to use a vector "digits" of the big number. This is like "1337" being a vector of four digits (1, 3, 3, 7),
11 // except that we will use `u64` as type of our digits. Now we just have to decide
12 // the order in which we store numbers. I decided that we will store the least significant
13 // digit first. This means that "1337" would actually become (7, 3, 3, 1).<br/>
14 // Finally, we declare that there must not be any trailing zeros (corresponding to
15 // useless leading zeros in our usual way of writing numbers). This is to ensure that
16 // the same number can only be stored in one way.
17
18 // To write this down in Rust, we use a `struct`, which is a lot like structs in C:
19 // Just a bunch of named fields. Every field can be private to the current module (which is the default),
20 // or public (which is indicated by a `pub` in front of the name). For the sake of the tutorial, we make
21 // `data` public - otherwise, the next parts of this course could not work on `BigInt`s. Of course, in a
22 // real program, one would make the field private to ensure that the invariant (no trailing zeros) is maintained.
23 pub struct BigInt {
24     pub data: Vec<u64>,
25 }
26
27 // Now that we fixed the data representation, we can start implementing methods on it.
28 impl BigInt {
29     // Let's start with a constructor, creating a `BigInt` from an ordinary integer.
30     // To create an instance of a struct, we write its name followed by a list of
31     // fields and initial values assigned to them.
32     pub fn new(x: u64) -> Self {
33         if x == 0 {
34             BigInt { data: vec![] }
35         } else {
36             BigInt { data: vec![x] }
37         }
38     }
39
40     // It can often be useful to encode the invariant of a data-structure in code, so here
41     // is a check that detects useless trailing zeros.
42     pub fn test_invariant(&self) -> bool {
43         if self.data.len() == 0 {
44             true
45         } else {
46             self.data[self.data.len() - 1] != 0
47         }
48     }
49
50     // We can convert any vector of digits into a number, by removing trailing zeros. The `mut`
51     // declaration for `v` here is just like the one in `let mut ...`, it says that we will locally
52     // change the vector `v`. In this case, we need to make that annotation to be able to call `pop`
53     // on `v`.
54     pub fn from_vec(mut v: Vec<u64>) -> Self {
55         while v.len() > 0 && v[v.len()-1] == 0 {
56             v.pop();
57         }
58         BigInt { data: v }
59     }
60 }
61
62 // **Exercise 05.1**: Write a function on `BigInt` that returns the number of digits. Write another one
63 // that increments the number by 1.
64 // 
65 // *Hint*: To take `self` as a mutable borrow, write `fn inc1(&mut self)`.
66
67 // ## Cloning
68 // If you have a close look at the type of `BigInt::from_vec`, you will notice that it
69 // consumes the vector `v`. The caller hence loses access. There is however something
70 // we can do if we don't want that to happen: We can explicitly `clone` the vector,
71 // which means that a full (or *deep*) copy will be performed. Technically,
72 // `clone` takes a borrowed vector, and returns a fully owned one.
73 fn clone_demo() {
74     let v = vec![0,1 << 16];
75     let b1 = BigInt::from_vec((&v).clone());
76     let b2 = BigInt::from_vec(v);
77 }
78 // Rust has special treatment for methods that borrow its `self` argument (like `clone`, or
79 // like `test_invariant` above): It is not necessary to explicitly borrow the receiver of the
80 // method. Hence you could replace `(&v).clone()` by `v.clone()` above. Just try it!
81
82 // To be clonable is a property of a type, and as such, naturally expressed with a trait.
83 // In fact, Rust already comes with a trait `Clone` for exactly this purpose. We can hence
84 // make our `BigInt` clonable as well.
85 impl Clone for BigInt {
86     fn clone(&self) -> Self {
87         BigInt { data: self.data.clone() }
88     }
89 }
90 // Making a type clonable is such a common exercise that Rust can even help you doing it:
91 // If you add `#[derive(Clone)]` right in front of the definition of `BigInt`, Rust will
92 // generate an implementation of `Clone` that simply clones all the fields. Try it!
93 // These `#[...]` annotations at types (and functions, modules, crates) are called *attributes*.
94 // We will see some more examples of attributes later.
95
96 // We can also make the type `SomethingOrNothing<T>` implement `Clone`. However, that
97 // can only work if `T` is `Clone`! So we have to add this bound to `T` when we introduce
98 // the type variable.
99 use part02::{SomethingOrNothing,Something,Nothing};
100 impl<T: Clone> Clone for SomethingOrNothing<T> {
101     fn clone(&self) -> Self {
102         match *self {
103             Nothing => Nothing,
104             // In the second arm of the match, we need to talk about the value `v`
105             // that's stored in `self`. However, if we would write the pattern as
106             // `Something(v)`, that would indicate that we *own* `v` in the code
107             // after the arrow. That can't work though, we have to leave `v` owned by
108             // whoever called us - after all, we don't even own `self`, we just borrowed it.
109             // By writing `Something(ref v)`, we borrow `v` for the duration of the match
110             // arm. That's good enough for cloning it.
111             Something(ref v) => Something(v.clone()),
112         }
113     }
114 }
115 // Again, Rust will generate this implementation automatically if you add
116 // `#[derive(Clone)]` right before the definition of `SomethingOrNothing`.
117
118 // ## Mutation + aliasing considered harmful (part 2)
119 // Now that we know how to borrow a part of an `enum` (like `v` above), there's another example for why we
120 // have to rule out mutation in the presence of aliasing. First, we define an `enum` that can hold either
121 // a number, or a string.
122 enum Variant {
123     Number(i32),
124     Text(String),
125 }
126 // Now consider the following piece of code. Like above, `n` will be a borrow of a part of `var`,
127 // and since we wrote `ref mut`, they will be mutable borrows. In other words, right after the match, `ptr`
128 // points to the number that's stored in `var`, where `var` is a `Number`. Remember that `_` means
129 // "we don't care".
130 fn work_on_variant(mut var: Variant, text: String) {
131     let mut ptr: &mut i32;
132     match var {
133         Variant::Number(ref mut n) => ptr = n,
134         Variant::Text(_) => return,
135     }
136     /* var = Variant::Text(text); */
137     *ptr = 1337;
138 }
139 // Now, imagine what would happen if we were permitted to also mutate `var`. We could, for example,
140 // make it a `Text`. However, `ptr` still points to the old location! Hence `ptr` now points somewhere
141 // into the representation of a `String`. By changing `ptr`, we manipulate the string in completely
142 // unpredictable ways, and anything could happen if we were to use it again! (Technically, the first field
143 // of a `String` is a pointer to its character data, so by overwriting that pointer with an integer,
144 // we make it a completely invalid address. When the destructor of `var` runs, it would try to deallocate
145 // that address, and Rust would eat your laundry - or whatever.)
146 // 
147 // I hope this example clarifies why Rust has to rule out mutation in the presence of aliasing *in general*,
148 // not just for the specific case of a buffer being reallocated, and old pointers becoming hence invalid.
149
150 // [index](main.html) | [previous](part04.html) | [next](part06.html)