|
|
@ -82,7 +82,7 @@ implement Send and Sync. Let's call it a `Carton`.
|
|
|
|
We start by writing code to take a value allocated on the stack and transfer it
|
|
|
|
We start by writing code to take a value allocated on the stack and transfer it
|
|
|
|
to the heap.
|
|
|
|
to the heap.
|
|
|
|
|
|
|
|
|
|
|
|
```rust
|
|
|
|
```rust,ignore
|
|
|
|
use std::mem::size_of;
|
|
|
|
use std::mem::size_of;
|
|
|
|
use std::ptr::NonNull;
|
|
|
|
use std::ptr::NonNull;
|
|
|
|
|
|
|
|
|
|
|
@ -114,7 +114,7 @@ to access it. [`Box`][box-doc] implements [`Deref`][deref-doc] and
|
|
|
|
[`DerefMut`][deref-mut-doc] so that you can access the inner value. Let's do
|
|
|
|
[`DerefMut`][deref-mut-doc] so that you can access the inner value. Let's do
|
|
|
|
that.
|
|
|
|
that.
|
|
|
|
|
|
|
|
|
|
|
|
```rust
|
|
|
|
```rust,ignore
|
|
|
|
use std::ops::{Deref, DerefMut};
|
|
|
|
use std::ops::{Deref, DerefMut};
|
|
|
|
|
|
|
|
|
|
|
|
impl<T> Deref for Carton<T> {
|
|
|
|
impl<T> Deref for Carton<T> {
|
|
|
@ -153,7 +153,7 @@ safely be Send unless it shares mutable state with something else without
|
|
|
|
enforcing exclusive access to it. Each `Carton` has a unique pointer, so
|
|
|
|
enforcing exclusive access to it. Each `Carton` has a unique pointer, so
|
|
|
|
we're good.
|
|
|
|
we're good.
|
|
|
|
|
|
|
|
|
|
|
|
```rust
|
|
|
|
```rust,ignore
|
|
|
|
// Safety: No one besides us has the raw pointer, so we can safely transfer the
|
|
|
|
// Safety: No one besides us has the raw pointer, so we can safely transfer the
|
|
|
|
// Carton to another thread.
|
|
|
|
// Carton to another thread.
|
|
|
|
unsafe impl<T> Send for Carton<T> {}
|
|
|
|
unsafe impl<T> Send for Carton<T> {}
|
|
|
@ -166,7 +166,7 @@ write to the pointer, and the borrow checker enforces that mutable
|
|
|
|
references must be exclusive, there are no soundness issues making `Carton`
|
|
|
|
references must be exclusive, there are no soundness issues making `Carton`
|
|
|
|
sync either.
|
|
|
|
sync either.
|
|
|
|
|
|
|
|
|
|
|
|
```rust
|
|
|
|
```rust,ignore
|
|
|
|
// Safety: Our implementation of DerefMut requires writers to mutably borrow the
|
|
|
|
// Safety: Our implementation of DerefMut requires writers to mutably borrow the
|
|
|
|
// Carton, so the borrow checker will only let us have references to the Carton
|
|
|
|
// Carton, so the borrow checker will only let us have references to the Carton
|
|
|
|
// on multiple threads if no one has a mutable reference to the Carton.
|
|
|
|
// on multiple threads if no one has a mutable reference to the Carton.
|
|
|
|