X-Git-Url: https://git.ralfj.de/rust-101.git/blobdiff_plain/188b1ec1b8528e2326791feccc8077e15bd60182..55d7df9f941d9979b568d094930c5009731737cf:/src/part12.rs?ds=inline diff --git a/src/part12.rs b/src/part12.rs index c749865..d88a8a6 100644 --- a/src/part12.rs +++ b/src/part12.rs @@ -9,6 +9,7 @@ use std::cell::{Cell, RefCell}; //@ (There's not even an automatic derivation happening for the cases where it would be possible.) //@ This restriction propagates up to `Callbacks` itself. What could we do about this? +//@ ## `Rc` //@ The solution is to find some way of cloning `Callbacks` without cloning the environments. This can be achieved with //@ `Rc`, a *reference-counted* pointer. This is is another example of a smart pointer. You can `clone` an `Rc` as often //@ as you want, that doesn't affect the data it contains. It only creates more references to the same data. Once all the @@ -26,7 +27,7 @@ struct Callbacks { impl Callbacks { pub fn new() -> Self { - Callbacks { callbacks: Vec::new() } /*@*/ + Callbacks { callbacks: Vec::new() } } // Registration works just like last time, except that we are creating an `Rc` now. @@ -37,7 +38,7 @@ impl Callbacks { pub fn call(&self, val: i32) { // We only need a shared iterator here. Since `Rc` is a smart pointer, we can directly call the callback. for callback in self.callbacks.iter() { - callback(val); /*@*/ + callback(val); /*@*/ } } } @@ -63,7 +64,7 @@ pub fn main() { //@ `set`, which overrides the content, only needs a *shared borrow* of the cell. The phenomenon of a type that permits mutation through //@ shared borrows (i.e., mutation despite the possibility of aliasing) is called *interior mutability*. You can think //@ of `set` changing only the *contents* of the cell, not its *identity*. In contrast, the kind of mutation we saw so far was -//@ about replacing one piece of data by something else of the same type. This is called *exterior mutability*.
+//@ about replacing one piece of data by something else of the same type. This is called *inherited mutability*.
//@ Notice that it is impossible to *borrow* the contents of the cell, and that is actually the key to why this is safe. // So, let us put our counter in a `Cell`, and replicate the example from the previous part. @@ -108,11 +109,11 @@ struct CallbacksMut { impl CallbacksMut { pub fn new() -> Self { - CallbacksMut { callbacks: Vec::new() } /*@*/ + CallbacksMut { callbacks: Vec::new() } } pub fn register(&mut self, callback: F) { - let cell = Rc::new(RefCell::new(callback)); + let cell = Rc::new(RefCell::new(callback)); /*@*/ self.callbacks.push(cell); /*@*/ } @@ -126,12 +127,13 @@ impl CallbacksMut { //@ 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. @@ -156,8 +158,7 @@ fn demo_mut(c: &mut CallbacksMut) { 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) +//@ [index](main.html) | [previous](part11.html) | [raw source](https://www.ralfj.de/git/rust-101.git/blob_plain/HEAD:/workspace/src/part12.rs) | [next](part13.html)