Sub topic 10
Unpin and PhantomPinned
This chapter assumes you know what Pin<P> promises and why a self-referential future must not move. It also assumes you are comfortable with auto traits and marker traits. Here you will learn which types the "will not move" promise applies to, how that is decided, and how to opt a type in.
Pin only matters for some types
The previous chapter showed that Pin<P> wraps a pointer and promises that the value behind it will not move. Most Rust types do not care about that promise. A u32, a String or a Vec<i32> can be moved to a new address and nothing breaks, because none of them hold a pointer into themselves.
Rust expresses this with the marker trait Unpin. T: Unpin means "it is safe to move T even when it sits behind a Pin". For an Unpin type, Pin imposes no restriction. For a type that is not Unpin, written !Unpin, the pin guarantee is enforced.
Unpin is an auto trait
Unpin is an auto trait, like Send and Sync. The compiler implements it for a type when every field of that type is Unpin. You never write impl Unpin for MyStruct in normal code.
- Primitives,
String,Vec<T>,Option<T>and references such as&Tand&mut TareUnpin. Box<T>isUnpinfor anyT, even a!Unpinone. Moving the box moves only the pointer, and the heap value stays where it is.- Structs and enums are
Unpinif all their fields are. - Futures produced by
async fnandasyncblocks are!Unpin. They may hold references across an.await, which makes them self-referential. The hand-writtenCountDownfuture from the earlier chapter isUnpinbecause its only field is au32.
What Unpin unlocks
The safe methods of Pin depend on Unpin:
| Operation | Requires `T: Unpin`? | Why |
|---|---|---|
| `Pin::new(ptr)` | Yes | Safe only if moving the target is harmless |
| `Pin::into_inner(pin)` | Yes | Hands the pointer back, so the target could move |
| `pin.get_mut()` | Yes | Returns `&mut T`, which allows `mem::swap` |
| `DerefMut` on `Pin<&mut T>` | Yes | Same reason as `get_mut` |
| `Deref` on `Pin<&T>` | No | A shared reference cannot move the value |
| `Box::pin(value)`, `pin!(value)` | No | The value is placed where it can no longer move |
| `get_unchecked_mut()` | No, but `unsafe` | You promise not to move the value |
The rule is that safe code may get a &mut T only when moving T is harmless. A &mut T lets you call std::mem::replace or std::mem::swap, which move the value. For !Unpin types, safe code never receives that &mut T.
Seeing the difference
This program runs as written. It checks Unpin at compile time and uses the safe Pin API on an Unpin type.
use std::marker::PhantomPinned;
use std::pin::Pin;
fn assert_unpin<T: Unpin>() {}
struct Plain {
count: u32,
name: String,
}
struct Marked {
count: u32,
_pin: PhantomPinned,
}
fn main() {
assert_unpin::<Plain>();
assert_unpin::<Box<Marked>>(); // Box is Unpin even around !Unpin data
// assert_unpin::<Marked>(); // error: `PhantomPinned` cannot be unpinned
let mut plain = Plain { count: 1, name: String::from("a") };
let mut pinned = Pin::new(&mut plain); // allowed: Plain is Unpin
pinned.count += 1; // DerefMut works because Plain is Unpin
let other = Plain { count: 10, name: String::from("b") };
std::mem::replace(pinned.get_mut(), other); // moving is fine here
println!("{} {}", plain.count, plain.name);
}The program prints 10 b. The two Unpin assertions on Plain and Box<Marked> compile. Uncommenting the assertion on Marked makes the build fail. The pin was a formality for Plain, so the replacement was legal.
PhantomPinned: opting out
Sometimes a type has no !Unpin field of its own but must not move, because it stores a raw pointer into itself. The compiler cannot see that intent, so it would infer Unpin. std::marker::PhantomPinned solves this. It is a zero-sized type that is !Unpin. Adding it as a field makes the whole struct !Unpin, through the auto-trait rule, and costs no memory.
Marked above does exactly this. Its only data is a u32, yet Marked is !Unpin, so Pin::new(&mut marked) no longer compiles.
Here is how you work with such a type. Mutation needs unsafe, and the unsafe code carries the promise not to move the value.
use std::marker::PhantomPinned;
use std::pin::Pin;
struct Marked {
count: u32,
_pin: PhantomPinned,
}
fn main() {
let mut pinned: Pin<Box<Marked>> = Box::pin(Marked {
count: 1,
_pin: PhantomPinned,
});
// Reading goes through Deref, which has no Unpin requirement.
println!("{}", pinned.count);
// Mutating a field needs unsafe: we promise not to move the whole value.
unsafe {
pinned.as_mut().get_unchecked_mut().count = 2;
}
println!("{}", pinned.count);
}The program prints 1 and then 2. Changing count in place is fine. Calling std::mem::swap on the &mut Marked would be the violation. The compiler cannot catch that, so the safety proof is yours. The SelfRef type from this tutorial's earlier example works the same way. It stores a raw pointer in ptr, and PhantomPinned is what makes the pin real.
Choosing between Unpin and !Unpin
Prefer Unpin. It is the default, and it keeps the safe API available to your users. Add PhantomPinned only when you write unsafe code that depends on the address staying fixed.
Common errors
- "
{async block}cannot be unpinned" or "PhantomPinnedcannot be unpinned". You calledPin::new,get_mutor a function bounded byUnpinon a!Unpinvalue. Pin it withBox::pin(fut)orstd::pin::pin!(fut)instead. A function that demandsUnpinis also satisfied byBox::pin(fut), becausePin<Box<F>>isUnpin. - Using
Pin::new(&mut fut)on anasyncblock. This fails for the same reason. Usepin!, as theblock_onexample did. - Writing
impl Unpin for T {}to silence an error. This compiles withoutunsafe, but it removes the guarantee. Safe code can then move your self-referential value and cause undefined behavior. - Expecting
PhantomPinnedto protect you on its own. It only withholds the safe&mutaccess. Moving the value before it is pinned, for example by returning it from a function and then pinning it, still breaks any pointer you set earlier. That is whySelfRef::newpins first and sets the pointer after.
Exercise
Why does Pin::new(&mut x) compile when x is a String, but fail when x is a struct that contains a PhantomPinned field? What should you call instead for the second case?
Show answer
String is Unpin, so moving it after pinning is harmless and Pin::new is safe. A struct with a PhantomPinned field is !Unpin through the auto-trait rule, so Pin::new would let safe code move a value that may be self-referential, and the compiler rejects it. Pin the value with Box::pin(value) or std::pin::pin!(value), which place it where it cannot move. Then mutate fields only through unsafe { pinned.as_mut().get_unchecked_mut() }, without moving the whole value.
Exercise
Is Box<T> Unpin when T is !Unpin? Why does this matter for Box::pin?
Show answer
Yes. Box<T> is Unpin for every T, because moving the box moves only the pointer and the heap data stays at its address. This is why Pin<Box<F>> is Unpin even when F is an async block. You can pass it to APIs that require Unpin futures.