Sub topic 10
Unpin and PhantomPinned
This chapter assumes you know what Pin<P> promises (the value behind the pointer will not move) and why self-referential futures need that promise. Here we look at the escape hatch for types where moving is harmless, and at how to opt out of it.
Unpin: moving is safe
Unpin is a marker trait that says "pinning me changes nothing, so you may move me even through a Pin." It is an auto trait. The compiler implements it for a type when all of the type's fields are Unpin. That covers u32, String, Vec<T>, Box<T> for any T, references, and raw pointers.
For Unpin types, Pin imposes no restriction. You can wrap a value with the safe Pin::new, get &mut T back with Pin::get_mut, and write through DerefMut.
use std::pin::Pin;
fn main() {
let mut n = 5u32;
let mut pinned = Pin::new(&mut n);
*pinned = 6;
let r: &mut u32 = Pin::into_inner(pinned);
println!("{r}");
}This compiles because u32 is Unpin. The CountDown future from the earlier chapter works the same way. It holds only a u32, so self.0 -= 1 through Pin<&mut Self> is allowed.
PhantomPinned: opting out
A type with no self-references looks Unpin to the compiler, even if you use raw pointers to point into it. Raw pointers are Unpin, and the compiler does not know what you mean by them. To say "this type must not move once pinned," add a PhantomPinned field. It is a zero-sized marker that is !Unpin, and that property spreads to any struct containing it.
use std::marker::PhantomPinned;
use std::pin::Pin;
struct Guarded {
value: u32,
_pin: PhantomPinned,
}
fn main() {
let mut g: Pin<Box<Guarded>> = Box::pin(Guarded {
value: 1,
_pin: PhantomPinned,
});
println!("{}", g.value); // reading through Deref is fine
// g.value = 2; // error: DerefMut needs Guarded: Unpin
unsafe {
g.as_mut().get_unchecked_mut().value = 2;
}
println!("{}", g.value);
}Once Guarded is !Unpin, the safe ways to get a &mut Guarded out of the pin disappear. Only unsafe code can reach it, and that code takes on the duty not to move the value.
| Operation | Needs `T: Unpin`? |
|---|---|
| `Pin::new(&mut t)` | Yes |
| `Pin::into_inner`, `Pin::get_mut` | Yes |
| `DerefMut` on `Pin<&mut T>` | Yes |
| `Deref` (shared read access) | No |
| `Box::pin`, `pin!` | No |
| `get_unchecked_mut`, `Pin::new_unchecked` | No, but `unsafe` |
Common mistakes
- Assuming
Pin<Box<T>>is!UnpinwhenTis.Pin<P>isUnpinwheneverPis, andBox<T>is alwaysUnpin. Moving the box moves only the pointer, not the pinned heap value. - Expecting
Pin::newto work on anasyncblock. The compiler marks async blocks!Unpinbecause they may hold self-references across.await. UseBox::pinorpin!instead. - Writing a self-referential struct without
PhantomPinned. The compiler will treat it asUnpin, and safe code can then move it and leaveptrdangling.
Exercise
A generic function has the bound F: Future + Unpin and calls Pin::new(&mut fut).poll(cx). Why does passing the value of an async fn call directly fail to compile, and what are two ways to fix it?
Show answer
The future from an async fn is !Unpin, because it may be self-referential. Pin::new is only available for Unpin types, so the bound is not met. Fix it either by pinning the future on the heap with Box::pin(fut), which gives a Pin<Box<_>> that is Unpin, or by pinning it on the stack with pin!(fut) and polling through as_mut(). The second option means changing the function to take Pin<&mut F> instead of requiring Unpin.