+//@ 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
+//@ want to give up the safety guarantee, we are going to need some code that actually checks at run-time that the borrowing rules
+//@ are not violated. Such a check is provided by `RefCell<T>`: Unlike `Cell<T>`, this lets us borrow the contents, and it works for
+//@ non-`Copy` `T`. But, as we will see, it incurs some run-time overhead.
+
+// Our final version of `Callbacks` puts the closure environment into a `RefCell`.
+#[derive(Clone)]
+struct CallbacksMut {
+ callbacks: Vec<Rc<RefCell<FnMut(i32)>>>,
+}
+
+impl CallbacksMut {
+ pub fn new() -> Self {
+ CallbacksMut { callbacks: Vec::new() }
+ }
+
+ pub fn register<F: FnMut(i32)+'static>(&mut self, callback: F) {
+ let cell = Rc::new(RefCell::new(callback)); /*@*/
+ self.callbacks.push(cell); /*@*/
+ }
+
+ pub fn call(&mut self, val: i32) {
+ for callback in self.callbacks.iter() {
+ // We have to *explicitly* borrow the contents of a `RefCell` by calling `borrow` or `borrow_mut`.
+ //@ At run-time, the cell will keep track of the number of outstanding shared and mutable borrows,
+ //@ and panic if the rules are violated. <br />
+ //@ For this check to be performed, `closure` is a *guard*: Rather than a normal borrow, `borrow_mut` returns
+ //@ a smart pointer (`RefMut`, in this case) that waits until is goes out of scope, and then
+ //@ appropriately updates the number of active borrows.
+ //@
+ //@ Since `call` is the only place that borrows the environments of the closures, we should expect that
+ //@ the check will always succeed. However, this function would still typecheck with an immutable borrow of `self` (since we are
+ //@ relying on the interior mutability of `RefCell`). Under this condition, it could happen that a callback
+ //@ will in turn trigger another round of callbacks, so that `call` would indirectly call itself.
+ //@ This is called reentrancy. It would imply that we borrow the closure a second time, and
+ //@ panic at run-time. I hope this also makes it clear that there's absolutely no hope of Rust
+ //@ performing these checks statically, at compile-time: It would have to detect reentrancy!
+ let mut closure = callback.borrow_mut();
+ // Unfortunately, Rust's auto-dereference of pointers is not clever enough here. We thus have to explicitly
+ // dereference the smart pointer and obtain a mutable borrow of the content.
+ (&mut *closure)(val);
+ }
+ }
+}
+
+// Now we can repeat the demo from the previous part - but this time, our `CallbacksMut` type
+// can be cloned.
+fn demo_mut(c: &mut CallbacksMut) {
+ c.register(|val| println!("Callback 1: {}", val));
+ c.call(0);
+
+ {
+ let mut count: usize = 0;
+ c.register(move |val| {
+ count = count+1;
+ println!("Callback 2: {} ({}. time)", val, count);
+ } );
+ }
+ c.call(1); c.clone().call(2);
+}
+
+// **Exercise 12.1**: Change the type of `call` to ask only for a shared borrow. Then write some piece of code using only the available, public
+// interface of `CallbacksMut` such that a reentrant call to `call` is happening, and the program aborts because the `RefCell` refuses to hand
+// out a second mutable borrow to its content.