self.callbacks.push(cell); /*@*/
}
- pub fn call(&self, val: i32) {
+ pub fn call(&mut self, val: i32) {
for callback in self.callbacks.iter() {
// We have to *explicitly* borrow the contents of a `RefCell`.
//@ At run-time, the cell will keep track of the number of outstanding shared and mutable borrows,
let c = Rc::new(RefCell::new(Callbacks::new()));
c.borrow_mut().register(|val| println!("Callback called: {}", val) );
- // If we change the two "borrow" below to "borrow_mut", you can get a panic even with a "call" that requires a
- // mutable borrow. However, that panic is then triggered by our own, external `RefCell` (so it's kind of our fault),
- // rather than being triggered by the `RefCell` in the `Callbacks`.
{
let c2 = c.clone();
- c.borrow_mut().register(move |val| c2.borrow().call(val+val) );
+ c.borrow_mut().register(move |val| {
+ let mut guard = c2.borrow_mut();
+ println!("Callback called with {}, ready to go for nested call.", val);
+ guard.call(val+val)
+ } );
}
- c.borrow().call(42);
+ // 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,
+ // but rather the `RefCell` inside the `CallbacksMut`.
+ let mut c2: Callbacks = c.borrow().clone();
+ c2.call(42);
}
}
\ No newline at end of file
let mut min: Option<BigInt> = None;
// If `v` is a shared borrowed vector, then the default for iterating over it is to call `iter`, the iterator that borrows the elements.
for e in v {
- let e = e.clone(); /*@*/
+ let e = e.clone();
min = Some(match min { /*@*/
None => e, /*@*/
Some(n) => e.min_try1(n) /*@*/
//@ underlying data is transferred from where `e` borrows from to `min`. But that's not allowed, since
//@ we just borrowed `e`, so we cannot empty it! We can, however, call `clone` on it. Then we own
//@ the copy that was created, and hence we can store it in `min`. <br/>
-//@ Of course, making such a full copy is expensive, so we'd like to avoid it. We'll some to that in the next part.
+//@ Of course, making such a full copy is expensive, so we'd like to avoid it. We'll come to that in the next part.
// ## `Copy` types
//@ But before we go there, I should answer the second question I brought up above: Why did our old `vec_min` work?
pub fn vec_min<T: Minimum>(v: &Vec<T>) -> Option<&T> {
let mut min: Option<&T> = None;
for e in v {
- min = Some(match min { /*@*/
- None => e, /*@*/
- Some(n) => n.min(e) /*@*/
- }); /*@*/
+ min = Some(match min {
+ None => e,
+ Some(n) => n.min(e)
+ });
}
min
}
//@ 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!
+ //@ the check will always succeed. However, this is not actually true. Several different `CallbacksMut` could share
+ //@ a callback (as they were created with `clone`), and calling one callback here could trigger calling
+ //@ all callbacks of the other `CallbacksMut`, which would end up calling the initial callback again. This issue is called *reentrancy*,
+ //@ and it can lead to subtle bugs. Here, it would mean that the closure runs twice, each time thinking it has the only
+ //@ mutable borrow of its environment - so it may end up dereferencing a dangling pointer. Ouch! Lucky enough,
+ //@ Rust detects this at run-time and panics once we try to borrow the same environment again. 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.
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.
+// **Exercise 12.1**: Write some piece of code using only the available, public interface of `CallbacksMut` such that a reentrant call to a closure
+// is happening, and the program aborts because the `RefCell` refuses to hand out a second mutable borrow of the closure's environment.
//@ [index](main.html) | [previous](part11.html) | [next](part13.html)
let mut min: Option<BigInt> = None;
// If `v` is a shared borrowed vector, then the default for iterating over it is to call `iter`, the iterator that borrows the elements.
for e in v {
+ let e = e.clone();
unimplemented!()
}
min
pub fn vec_min<T: Minimum>(v: &Vec<T>) -> Option<&T> {
let mut min: Option<&T> = None;
for e in v {
- unimplemented!()
+ min = Some(match min {
+ None => e,
+ Some(n) => n.min(e)
+ });
}
min
}
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.
+// **Exercise 12.1**: Write some piece of code using only the available, public interface of `CallbacksMut` such that a reentrant call to a closure
+// is happening, and the program aborts because the `RefCell` refuses to hand out a second mutable borrow of the closure's environment.