2 use std::cell::RefCell;
6 callbacks: Vec<Rc<RefCell<FnMut(i32)>>>,
10 pub fn new() -> Self {
11 Callbacks { callbacks: Vec::new() } /*@*/
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); /*@*/
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
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.
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.
47 use std::cell::RefCell;
53 let c = Rc::new(RefCell::new(Callbacks::new()));
54 c.borrow_mut().register(|val| println!("Callback called: {}", val) );
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`.
61 c.borrow_mut().register(move |val| c2.borrow().call(val+val) );