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(&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
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) );
58 c.borrow_mut().register(move |val| {
59 let mut guard = c2.borrow_mut();
60 println!("Callback called with {}, ready to go for nested call.", val);
65 // We do a clone, and call `call` on that one. This makes sure that it's not our `RefCell` that complains about two mutable borrows,
66 // but rather the `RefCell` inside the `CallbacksMut`.
67 let mut c2: Callbacks = c.borrow().clone();