re-do deepaksirone's fix on the actual source file
[rust-101.git] / workspace / src / part05.rs
1 // Rust-101, Part 05: Clone
2 // ========================
3
4 // ## Big Numbers
5
6 pub struct BigInt {
7     pub data: Vec<u64>, // least significant digit first, no trailing zeros
8 }
9
10 // Now that we fixed the data representation, we can start implementing methods on it.
11 impl BigInt {
12     pub fn new(x: u64) -> Self {
13         if x == 0 {
14             unimplemented!()
15         } else {
16             unimplemented!()
17         }
18     }
19
20     pub fn test_invariant(&self) -> bool {
21         if self.data.len() == 0 {
22             true
23         } else {
24             unimplemented!()
25         }
26     }
27
28     // We can convert any vector of digits into a number, by removing trailing zeros. The `mut`
29     // declaration for `v` here is just like the one in `let mut ...`: We completely own `v`, but Rust
30     // still asks us to make our intention of modifying it explicit. This `mut` is *not* part of the
31     // type of `from_vec` - the caller has to give up ownership of `v` anyway, so they don't care anymore
32     // what you do to it.
33     // 
34     // **Exercise 05.1**: Implement this function.
35     // 
36     // *Hint*: You can use `pop` to remove the last element of a vector.
37     pub fn from_vec(mut v: Vec<u64>) -> Self {
38         unimplemented!()
39     }
40 }
41
42 // ## Cloning
43 fn clone_demo() {
44     let v = vec![0,1 << 16];
45     let b1 = BigInt::from_vec((&v).clone());
46     let b2 = BigInt::from_vec(v);
47 }
48
49 impl Clone for BigInt {
50     fn clone(&self) -> Self {
51         unimplemented!()
52     }
53 }
54
55 // We can also make the type `SomethingOrNothing<T>` implement `Clone`. 
56 use part02::{SomethingOrNothing,Something,Nothing};
57 impl<T: Clone> Clone for SomethingOrNothing<T> {
58     fn clone(&self) -> Self {
59         unimplemented!()
60     }
61 }
62
63 // **Exercise 05.2**: Write some more functions on `BigInt`. What about a function that returns the number of
64 // digits? The number of non-zero digits? The smallest/largest digit? Of course, these should all take `self` as a shared reference (i.e., in borrowed form).
65
66 // ## Mutation + aliasing considered harmful (part 2)
67 enum Variant {
68     Number(i32),
69     Text(String),
70 }
71 fn work_on_variant(mut var: Variant, text: String) {
72     let mut ptr: &mut i32;
73     match var {
74         Variant::Number(ref mut n) => ptr = n,
75         Variant::Text(_) => return,
76     }
77     /* var = Variant::Text(text); */                                /* BAD! */
78     *ptr = 1337;
79 }
80