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