split part 11 into two, and explain interior mutability and Cell and RefCell in the...
[rust-101.git] / solutions / src / callbacks.rs
1 use std::rc::Rc;
2 use std::cell::RefCell;
3
4 #[derive(Clone)]
5 pub struct Callbacks {
6     callbacks: Vec<Rc<RefCell<FnMut(i32)>>>,
7 }
8
9 impl Callbacks {
10     pub fn new() -> Self {
11         Callbacks { callbacks: Vec::new() }                      /*@*/
12     }
13
14     pub fn register<F: FnMut(i32)+'static>(&mut self, callback: F) {
15         let cell = Rc::new(RefCell::new(callback));
16         self.callbacks.push(cell);                                  /*@*/
17     }
18
19     pub fn call(&self, val: i32) {
20         for callback in self.callbacks.iter() {
21             // We have to *explicitly* borrow the contents of a `RefCell`.
22             //@ At run-time, the cell will keep track of the number of outstanding shared and mutable borrows,
23             //@ and panic if the rules are violated. Since this function is the only one that borrow the
24             //@ environments of the closures, and this function requires a *mutable* borrow of `self`, we know this cannot
25             //@ happen. <br />
26             //@ For this check to be performed, `closure` is a *guard*: Rather than a normal borrow, `borrow_mut` returns
27             //@ a smart pointer (`RefMut`, in this case) that waits until is goes out of scope, and then
28             //@ appropriately updates the number of active borrows.
29             //@ 
30             //@ The function would still typecheck with an immutable borrow of `self` (since we are
31             //@ relying on the interior mutability of `self`), but then it could happen that a callback
32             //@ will in turn trigger another round of callbacks, so that `call` would indirectly call itself.
33             //@ This is called reentrancy. It would imply that we borrow the closure a second time, and
34             //@ panic at run-time. I hope this also makes it clear that there's absolutely no hope of Rust
35             //@ performing these checks statically, at compile-time: It would have to detect reentrancy!
36             let mut closure = callback.borrow_mut();
37             // Unfortunately, Rust's auto-dereference of pointers is not clever enough here. We thus have to explicitly
38             // dereference the smart pointer and obtain a mutable borrow of the target.
39             (&mut *closure)(val);
40         }
41     }
42 }
43
44 #[cfg(test)]
45 mod tests {
46     use std::rc::Rc;
47     use std::cell::RefCell;
48     use super::*;
49
50     #[test]
51     #[should_panic]
52     fn test_reentrant() {
53         let c = Rc::new(RefCell::new(Callbacks::new()));
54         c.borrow_mut().register(|val| println!("Callback called: {}", val) );
55
56         // If we change the two "borrow" below to "borrow_mut", you can get a panic even with a "call" that requires a
57         // mutable borrow. However, that panic is then triggered by our own, external `RefCell` (so it's kind of our fault),
58         // rather than being triggered by the `RefCell` in the `Callbacks`.
59         {
60             let c2 = c.clone();
61             c.borrow_mut().register(move |val| c2.borrow().call(val+val) );
62         }
63
64         c.borrow().call(42);
65     }
66 }