exterior mutability -> inherited mutability, another useful link, warn about transmute
[rust-101.git] / src / part12.rs
1 // Rust-101, Part 12: Rc, Interior Mutability, Cell, RefCell
2 // =========================================================
3
4 use std::rc::Rc;
5 use std::cell::{Cell, RefCell};
6
7 //@ Our generic callback mechanism is already working quite nicely. However, there's one point we may want to fix:
8 //@ `Callbacks` does not implement `Clone`. The problem is that closures (or rather, their environment) can never be cloned.
9 //@ (There's not even an automatic derivation happening for the cases where it would be possible.)
10 //@ This restriction propagates up to `Callbacks` itself. What could we do about this?
11
12 //@ ## `Rc`
13 //@ The solution is to find some way of cloning `Callbacks` without cloning the environments. This can be achieved with
14 //@ `Rc<T>`, a *reference-counted* pointer. This is is another example of a smart pointer. You can `clone` an `Rc` as often
15 //@ as you want, that doesn't affect the data it contains. It only creates more references to the same data. Once all the
16 //@ references are gone, the data is deleted.
17 //@ 
18 //@ Wait a moment, you may say here. Multiple references to the same data? That's aliasing! Indeed:
19 //@ Once data is stored in an `Rc`, it is read-only and you can only ever get a shared borrow of the data again.
20
21 //@ Because of this read-only restriction, we cannot use `FnMut` here: We'd be unable to call the function with a mutable borrow
22 //@ of it's environment! So we have to go with `Fn`. We wrap that in an `Rc`, and then Rust happily derives `Clone` for us.
23 #[derive(Clone)]
24 struct Callbacks {
25     callbacks: Vec<Rc<Fn(i32)>>,
26 }
27
28 impl Callbacks {
29     pub fn new() -> Self {
30         Callbacks { callbacks: Vec::new() }
31     }
32
33     // Registration works just like last time, except that we are creating an `Rc` now.
34     pub fn register<F: Fn(i32)+'static>(&mut self, callback: F) {
35         self.callbacks.push(Rc::new(callback));                     /*@*/
36     }
37
38     pub fn call(&self, val: i32) {
39         // We only need a shared iterator here. Since `Rc` is a smart pointer, we can directly call the callback.
40         for callback in self.callbacks.iter() {
41             callback(val);                                          /*@*/
42         }
43     }
44 }
45
46 // Time for a demo!
47 fn demo(c: &mut Callbacks) {
48     c.register(|val| println!("Callback 1: {}", val));
49     c.call(0); c.clone().call(1);
50 }
51
52 pub fn main() {
53     let mut c = Callbacks::new();
54     demo(&mut c);
55 }
56
57 // ## Interior Mutability
58 //@ Of course, the counting example from last time does not work anymore: It needs to mutate the environment, which a `Fn`
59 //@ cannot do. The strict borrowing Rules of Rust are getting into our way. However, when it comes to mutating a mere number
60 //@ (`usize`), there's not really any chance of problems coming up. Everybody can read and write that variable just as they want.
61 //@ So it would be rather sad if we were not able to write this program. Lucky enough, Rust's standard library provides a
62 //@ solution in the form of `Cell<T>`. This type represents a memory cell of some type `T`, providing the two basic operations
63 //@ `get` and `set`. `get` returns a *copy* of the content of the cell, so all this works only if `T` is `Copy`.
64 //@ `set`, which overrides the content, only needs a *shared borrow* of the cell. The phenomenon of a type that permits mutation through
65 //@ shared borrows (i.e., mutation despite the possibility of aliasing) is called *interior mutability*. You can think
66 //@ of `set` changing only the *contents* of the cell, not its *identity*. In contrast, the kind of mutation we saw so far was
67 //@ about replacing one piece of data by something else of the same type. This is called *inherited mutability*. <br/>
68 //@ Notice that it is impossible to *borrow* the contents of the cell, and that is actually the key to why this is safe.
69
70 // So, let us put our counter in a `Cell`, and replicate the example from the previous part.
71 fn demo_cell(c: &mut Callbacks) {
72     {
73         let count = Cell::new(0);
74         // Again, we have to move ownership if the `count` into the environment closure.
75         c.register(move |val| {
76             // In here, all we have is a shared borrow of our environment. But that's good enough for the `get` and `set` of the cell!
77             //@ At run-time, the `Cell` will be almost entirely compiled away, so this becomes pretty much equivalent to the version
78             //@ we wrote in the previous part.
79             let new_count = count.get()+1;
80             count.set(new_count);
81             println!("Callback 2: {} ({}. time)", val, new_count);
82         } );
83     }
84
85     c.call(2); c.clone().call(3);
86 }
87
88 //@ It is worth mentioning that `Rc` itself also has to make use of interior mutability: When you `clone` an `Rc`, all it has available
89 //@ is a shared borrow. However, it has to increment the reference count! Internally, `Rc` uses `Cell` for the count, such that it
90 //@ can be updated during `clone`.
91
92 // ## `RefCell`
93 //@ As the next step in the evolution of `Callbacks`, we could try to solve this problem of mutability once and for all, by adding `Cell`
94 //@ to `Callbacks` such that clients don't have to worry about this. However, that won't end up working: Remember that `Cell` only works
95 //@ with types that are `Copy`, which the environment of a closure will never be. We need a variant of `Cell` that allows borrowing its
96 //@ contents, such that we can provide a `FnMut` with its environment. But if `Cell` would allow that, we could write down all those
97 //@ crashing C++ programs that we wanted to get rid of.
98 //@ 
99 //@ This is the point where our program got too complex for Rust to guarantee at compile-time that nothing bad will happen. Since we don't
100 //@ want to give up the safety guarantee, we are going to need some code that actually checks at run-time that the borrowing rules
101 //@ are not violated. Such a check is provided by `RefCell<T>`: Unlike `Cell<T>`, this lets us borrow the contents, and it works for
102 //@ non-`Copy` `T`. But, as we will see, it incurs some run-time overhead.
103
104 // Our final version of `Callbacks` puts the closure environment into a `RefCell`.
105 #[derive(Clone)]
106 struct CallbacksMut {
107     callbacks: Vec<Rc<RefCell<FnMut(i32)>>>,
108 }
109
110 impl CallbacksMut {
111     pub fn new() -> Self {
112         CallbacksMut { callbacks: Vec::new() }
113     }
114
115     pub fn register<F: FnMut(i32)+'static>(&mut self, callback: F) {
116         let cell = Rc::new(RefCell::new(callback));                 /*@*/
117         self.callbacks.push(cell);                                  /*@*/
118     }
119
120     pub fn call(&mut self, val: i32) {
121         for callback in self.callbacks.iter() {
122             // We have to *explicitly* borrow the contents of a `RefCell` by calling `borrow` or `borrow_mut`.
123             //@ At run-time, the cell will keep track of the number of outstanding shared and mutable borrows,
124             //@ and panic if the rules are violated. <br />
125             //@ For this check to be performed, `closure` is a *guard*: Rather than a normal borrow, `borrow_mut` returns
126             //@ a smart pointer (`RefMut`, in this case) that waits until is goes out of scope, and then
127             //@ appropriately updates the number of active borrows.
128             //@ 
129             //@ Since `call` is the only place that borrows the environments of the closures, we should expect that
130             //@ the check will always succeed. However, this function would still typecheck with an immutable borrow of `self` (since we are
131             //@ relying on the interior mutability of `RefCell`). Under this condition, it could happen that a callback
132             //@ will in turn trigger another round of callbacks, so that `call` would indirectly call itself.
133             //@ This is called reentrancy. It would imply that we borrow the closure a second time, and
134             //@ panic at run-time. I hope this also makes it clear that there's absolutely no hope of Rust
135             //@ performing these checks statically, at compile-time: It would have to detect reentrancy!
136             let mut closure = callback.borrow_mut();
137             // Unfortunately, Rust's auto-dereference of pointers is not clever enough here. We thus have to explicitly
138             // dereference the smart pointer and obtain a mutable borrow of the content.
139             (&mut *closure)(val);
140         }
141     }
142 }
143
144 // Now we can repeat the demo from the previous part - but this time, our `CallbacksMut` type
145 // can be cloned.
146 fn demo_mut(c: &mut CallbacksMut) {
147     c.register(|val| println!("Callback 1: {}", val));
148     c.call(0);
149
150     {
151         let mut count: usize = 0;
152         c.register(move |val| {
153             count = count+1;
154             println!("Callback 2: {} ({}. time)", val, count);
155         } );
156     }
157     c.call(1); c.clone().call(2);
158 }
159
160 // **Exercise 12.1**: Change the type of `call` to ask only for a shared borrow. Then write some piece of code using only the available, public
161 // interface of `CallbacksMut` such that a reentrant call to `call` is happening, and the program aborts because the `RefCell` refuses to hand
162 // out a second mutable borrow to its content.
163
164 //@ [index](main.html) | [previous](part11.html) | [next](part13.html)