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 borrow of 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 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.
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 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.
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 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;
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 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`.
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.
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.
104 // Our final version of `Callbacks` puts the closure environment into a `RefCell`.
106 struct CallbacksMut {
107 callbacks: Vec<Rc<RefCell<FnMut(i32)>>>,
111 pub fn new() -> Self {
112 CallbacksMut { callbacks: Vec::new() }
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); /*@*/
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.
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 is not actually true. Several different `CallbacksMut` could share
131 //@ a callback (as they were created with `clone`), and calling one callback here could trigger calling
132 //@ all callbacks of the other `CallbacksMut`, which would end up calling the initial callback again. This issue is called *reentrancy*,
133 //@ and it can lead to subtle bugs. Here, it would mean that the closure runs twice, each time thinking it has the only
134 //@ mutable borrow of its environment - so it may end up dereferencing a dangling pointer. Ouch! Lucky enough,
135 //@ Rust detects this at run-time and panics once we try to borrow the same environment again. I hope this also makes it
136 //@ clear that there's absolutely no hope of Rust performing these checks statically, at compile-time: It would have to detect reentrancy!
137 let mut closure = callback.borrow_mut();
138 // Unfortunately, Rust's auto-dereference of pointers is not clever enough here. We thus have to explicitly
139 // dereference the smart pointer and obtain a mutable borrow of the content.
140 (&mut *closure)(val);
145 // Now we can repeat the demo from the previous part - but this time, our `CallbacksMut` type
147 fn demo_mut(c: &mut CallbacksMut) {
148 c.register(|val| println!("Callback 1: {}", val));
152 let mut count: usize = 0;
153 c.register(move |val| {
155 println!("Callback 2: {} ({}. time)", val, count);
158 c.call(1); c.clone().call(2);
161 // **Exercise 12.1**: Write some piece of code using only the available, public interface of `CallbacksMut` such that a reentrant call to a closure
162 // is happening, and the program aborts because the `RefCell` refuses to hand out a second mutable borrow of the closure's environment.
164 //@ [index](main.html) | [previous](part11.html) | [next](part13.html)