1 // Rust-101, Part 12: Rc, Interior Mutability, Cell, RefCell
2 // =========================================================
5 use std::cell::{Cell, RefCell};
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?
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.
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 reference to the data again.
21 //@ Because of this read-only restriction, we cannot use `FnMut` here: We'd be unable to call the function with a mutable reference
22 //@ to it's environment! So we have to go with `Fn`. We wrap that in an `Rc`, and then Rust happily derives `Clone` for us.
25 callbacks: Vec<Rc<Fn(i32)>>,
29 pub fn new() -> Self {
30 Callbacks { callbacks: Vec::new() }
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)); /*@*/
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() {
47 fn demo(c: &mut Callbacks) {
48 c.register(|val| println!("Callback 1: {}", val));
49 c.call(0); c.clone().call(1);
53 let mut c = Callbacks::new();
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 reference* to the cell. The phenomenon of a type that permits mutation through
65 //@ shared references (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.
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) {
73 let count = Cell::new(0);
74 // Again, we have to move ownership of the `count` into the environment closure.
75 c.register(move |val| {
76 // In here, all we have is a shared reference 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;
81 println!("Callback 2: {} ({}. time)", val, new_count);
85 c.call(2); c.clone().call(3);
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 reference. However, it has to increment the reference count! Internally, `Rc` uses `Cell` for the count, such that it
90 //@ can be updated during `clone`.
92 //@ Putting it all together, the story around mutation and ownership through references looks as follows: There are *unique* references,
93 //@ which - because of their exclusivity - are always safe to mutate through. And there are *shared* references, where the compiler cannot
94 //@ generally promise that mutation is safe. However, if extra circumstances guarantee that mutation *is* safe, then it can happen even
95 //@ through a shared reference - as we saw with `Cell`.
98 //@ 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`
99 //@ to `Callbacks` such that clients don't have to worry about this. However, that won't end up working: Remember that `Cell` only works
100 //@ with types that are `Copy`, which the environment of a closure will never be. We need a variant of `Cell` that allows borrowing its
101 //@ contents, such that we can provide a `FnMut` with its environment. But if `Cell` would allow that, we could write down all those
102 //@ crashing C++ programs that we wanted to get rid of.
104 //@ 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
105 //@ want to give up the safety guarantee, we are going to need some code that actually checks at run-time that the borrowing rules
106 //@ are not violated. Such a check is provided by `RefCell<T>`: Unlike `Cell<T>`, this lets us borrow the contents, and it works for
107 //@ non-`Copy` `T`. But, as we will see, it incurs some run-time overhead.
109 // Our final version of `Callbacks` puts the closure environment into a `RefCell`.
111 struct CallbacksMut {
112 callbacks: Vec<Rc<RefCell<FnMut(i32)>>>,
116 pub fn new() -> Self {
117 CallbacksMut { callbacks: Vec::new() }
120 pub fn register<F: FnMut(i32)+'static>(&mut self, callback: F) {
121 let cell = Rc::new(RefCell::new(callback)); /*@*/
122 self.callbacks.push(cell); /*@*/
125 pub fn call(&mut self, val: i32) {
126 for callback in self.callbacks.iter() {
127 // We have to *explicitly* borrow the contents of a `RefCell` by calling `borrow` or `borrow_mut`.
128 //@ At run-time, the cell will keep track of the number of outstanding shared and mutable references,
129 //@ and panic if the rules are violated. <br />
130 //@ For this check to be performed, `closure` is a *guard*: Rather than a normal reference, `borrow_mut` returns
131 //@ a smart pointer ([`RefMut`](https://doc.rust-lang.org/stable/std/cell/struct.RefMut.html), in this case) that waits until is goes out of scope, and then
132 //@ appropriately updates the number of active references.
134 //@ Since `call` is the only place that borrows the environments of the closures, we should expect that
135 //@ the check will always succeed, as is actually entirely useless. However, this is not actually true. Several different `CallbacksMut` could share
136 //@ a callback (as they were created with `clone`), and calling one callback here could trigger calling
137 //@ all callbacks of the other `CallbacksMut`, which would end up calling the initial callback again. This issue of functions accidentally recursively calling
138 //@ themselves is called *reentrancy*, and it can lead to subtle bugs. Here, it would mean that the closure runs twice, each time thinking it has a
139 //@ unique, mutable reference to its environment - so it may end up dereferencing a dangling pointer. Ouch! Lucky enough,
140 //@ Rust detects this at run-time and panics once we try to borrow the same environment again. I hope this also makes it
141 //@ clear that there's absolutely no hope of Rust performing these checks statically, at compile-time: It would have to detect reentrancy!
142 let mut closure = callback.borrow_mut();
143 // Unfortunately, Rust's auto-dereference of pointers is not clever enough here. We thus have to explicitly
144 // dereference the smart pointer and obtain a mutable reference to the content.
145 (&mut *closure)(val);
150 // Now we can repeat the demo from the previous part - but this time, our `CallbacksMut` type
152 fn demo_mut(c: &mut CallbacksMut) {
153 c.register(|val| println!("Callback 1: {}", val));
157 let mut count: usize = 0;
158 c.register(move |val| {
160 println!("Callback 2: {} ({}. time)", val, count);
163 c.call(1); c.clone().call(2);
166 // **Exercise 12.1**: Write some piece of code using only the available, public interface of `CallbacksMut` such that a reentrant call to a closure
167 // is happening, and the program panics because the `RefCell` refuses to hand out a second mutable borrow of the closure's environment.
169 //@ [index](main.html) | [previous](part11.html) | [raw source](https://www.ralfj.de/git/rust-101.git/blob_plain/HEAD:/workspace/src/part12.rs) | [next](part13.html)