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