More comments in solution for cyclic Callbacks
[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(&mut 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         // We want to create a `Callbacks` instance containing a closure referencing this very `Callbacks` instance.
54         // To create this cycle, we need to put the `Callbacks` into a `RefCell`.
55         let c = Rc::new(RefCell::new(Callbacks::new()));
56         c.borrow_mut().register(|val| println!("Callback called: {}", val) );
57
58         // This adds the cyclic closure, which refers to the `Callbacks` though `c2`.
59         let c2 = c.clone();
60         c.borrow_mut().register(move |val| {
61             // This `borrow_mut` won't fail because we are careful below to close the `RefCell`
62             // before triggering the cycle. You can see that this is the case because the log message
63             // below is printed.
64             let mut guard = c2.borrow_mut();
65             println!("Callback called with {}, ready to go for nested call.", val);
66             guard.call(val+val)
67         } );
68
69         // We do a clone of the `Callbacks` to ensure that the `RefCell` we created for the cycle is closed.
70         // This makes sure that it's not our `borrow_mut` above that complains about two mutable borrows,
71         // but rather the one inside `Callbacks::call`.
72         let mut c2: Callbacks = c.borrow().clone();
73         drop(c); // This is not strictly necessary. It demonstrates that we are not holding any reference to the `RefCell` any more.
74         c2.call(42);
75     }
76 }