Sub topic 13
Pin projection and the pin-project crate
This chapter assumes you know the Future trait, Pin<&mut T>, and Unpin. It also assumes you have written a poll method by hand. Here you will see how a wrapper future polls the future inside it, and how to do that without unsafe in your own code.
The problem: reaching a field through a Pin
Wrapper futures are common. A timeout, a logger, or a map combinator each holds another future in a field and forwards poll to it. The wrapper's poll receives self: Pin<&mut Self>. The inner future's poll needs Pin<&mut F>. Writing Pin::new(&mut self.inner) fails whenever F is not Unpin, and async blocks are never Unpin.
Pin projection is the step that turns a Pin<&mut Wrapper> into pinned or plain references to each field. The word "projection" means narrowing a reference to the whole into a reference to one part.
Each field is either structurally pinned or not:
| Field kind | Projected type | May the field move? |
|---|---|---|
| Structurally pinned | `Pin<&mut Field>` | No. It stays at its address until dropped. |
| Not pinned | `&mut Field` | Yes. You can mutate it or swap it freely. |
Structural pinning means the pin on the wrapper extends to the field. If the wrapper cannot move, the field cannot move either. Use it for fields whose poll you call. Use plain fields for counters, flags, and anything else you only read or write.
Projection by hand
The standard library gives you unsafe building blocks. This example counts how many times the inner future was polled:
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct Counted<F> {
inner: F,
polls: u32,
}
impl<F: Future> Future for Counted<F> {
type Output = (F::Output, u32);
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
// SAFETY: we only use `this` to reach fields. We never move `inner`
// out of it, never replace it, and `Counted` has no Drop impl.
let this = unsafe { self.get_unchecked_mut() };
this.polls += 1;
// SAFETY: `inner` is structurally pinned. It stays in place for as
// long as `Counted` does, and we hand it out only as a pinned reference.
let inner = unsafe { Pin::new_unchecked(&mut this.inner) };
match inner.poll(cx) {
Poll::Ready(value) => Poll::Ready((value, this.polls)),
Poll::Pending => Poll::Pending,
}
}
}get_unchecked_mut gives you a plain &mut Counted<F>. That reference could be used to move the whole struct, so the call is unsafe. Pin::new_unchecked makes the opposite promise. You tell the compiler that the referent will not move again.
The rules that make it sound
Writing Pin::new_unchecked(&mut self.field) is only correct if all of these hold:
- The wrapper is
Unpinonly if the pinned field isUnpin. Do not write a manualimpl Unpin. The auto trait already behaves this way. - The wrapper's
Dropimplementation never moves the pinned field. - Nothing else in the wrapper's API moves the field out. That includes
mem::swap,mem::replace, andOption::takeon it. - The struct is not
#[repr(packed)], because packing can misalign and relocate fields.
You must check these rules by hand every time. A mistake compiles fine and shows up as undefined behavior, usually only for a self-referential inner future.
Projection with pin-project
The pin-project crate generates the projection code and checks the rules at compile time. Add it to Cargo.toml:
[dependencies]
pin-project = "1"Then mark the pinned field with #[pin]:
use pin_project::pin_project;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
#[pin_project]
struct Counted<F> {
#[pin]
inner: F,
polls: u32,
}
impl<F: Future> Future for Counted<F> {
type Output = (F::Output, u32);
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
*this.polls += 1;
match this.inner.poll(cx) {
Poll::Ready(value) => Poll::Ready((value, *this.polls)),
Poll::Pending => Poll::Pending,
}
}
}The project() method consumes Pin<&mut Counted<F>> and returns a generated struct. In it, this.inner has type Pin<&mut F> and this.polls has type &mut u32. There is no unsafe in your code.
The attribute also does the following:
- It adds an
Unpinimplementation that holds only when every#[pin]field isUnpin. - It rejects a normal
Dropimplementation. If you need cleanup, use#[pinned_drop], which gives youPin<&mut Self>instead of&mut self. - It refuses to compile on
#[repr(packed)].
The next program runs either version of Counted. It uses Waker::noop(), which needs Rust 1.85 or later:
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
fn main() {
let mut fut = pin!(Counted {
inner: std::future::ready(7),
polls: 0,
});
let mut cx = Context::from_waker(Waker::noop());
match fut.as_mut().poll(&mut cx) {
Poll::Ready((value, polls)) => println!("{value} after {polls} poll"),
Poll::Pending => unreachable!("ready() completes on the first poll"),
}
}This prints 7 after 1 poll.
Enums and the pin-project-lite alternative
Combinators such as Map often hold a future in one state and a result in another, which makes them enums. For an enum, name the projection type:
use pin_project::pin_project;
#[pin_project(project = StateProj)]
enum State<F, T> {
Running(#[pin] F),
Finished(T),
}Calling self.project() on Pin<&mut State<F, T>> returns a StateProj value. You can match on it, and Running yields a Pin<&mut F>. If you must replace the whole enum, for example from Running to Finished, use project_replace. The #[pin_project(project_replace)] form generates it, and it drops the old value in place without moving it.
The pin-project-lite crate offers the same projection through a declarative macro. It has no procedural-macro compile cost. Its syntax is more limited, and it also has no #[pinned_drop] attribute.
Common mistakes
- Marking every field
#[pin]. Pin only fields you need asPin<&mut T>, typically futures and streams. A#[pin]on a plainu32forces you to handlePin<&mut u32>for no benefit. - Forgetting
#[pin]on the inner future. The code then fails to compile becausethis.inneris&mut Fand you cannot callpollon it. Add the attribute. - Calling
project()twice. It consumes thePin<&mut Self>. Callself.as_mut().project()if you need to project again, for example inside a loop. - Moving a pinned field out in
Drop.pin-projectforbids a plainDropfor this reason.
Exercise
A wrapper has fields inner: F (a future) and name: String. You write #[pin_project] and mark only inner with #[pin]. What are the types of this.inner and this.name after let this = self.project();, and why can you still write this.name.push('x')?
Show answer
this.inner is Pin<&mut F> and this.name is &mut String. name is not structurally pinned, so projection hands out an ordinary mutable reference. Moving a String handle does not invalidate anything, so this.name.push('x') compiles and is sound.
Exercise
Why does #[pin_project] reject a normal impl Drop for Counted<F>, and what do you use instead?
Show answer
A normal Drop::drop takes &mut self, which is an ordinary mutable reference. Safe code in it could move the structurally pinned inner field out, which breaks the pin guarantee. Use #[pinned_drop] with an impl PinnedDrop whose drop takes Pin<&mut Self>, so you must project before touching pinned fields.