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