Sub topic 13
Pin projection and the pin-project crate
This chapter assumes you know Pin<&mut T>, Unpin, and how poll takes self: Pin<&mut Self>. It also assumes you have written a simple Future by hand.
The problem: getting from the struct to its fields
A wrapper future holds another future in a field. Its poll receives Pin<&mut Self>, but it must call poll on the inner future, which needs Pin<&mut F>. Turning a pinned reference to a struct into pinned references to its fields is called pin projection.
If the wrapper is Unpin, you can call get_mut() and use ordinary &mut borrows. Most wrappers are not Unpin, because the inner future F might not be.
Doing it by hand
The manual version needs unsafe:
let this = unsafe { self.get_unchecked_mut() };
let inner = unsafe { Pin::new_unchecked(&mut this.inner) };Each unsafe block carries a promise:
- The struct never moves out of its pinned location. That includes moving through
mem::replaceorOption::takeon the pinned field. - The struct's
Dropimplementation never moves the pinned field. - The struct is
Unpinonly if the pinned field isUnpin.
One mistake breaks soundness, and the compiler cannot detect it.
Using pin-project
The pin-project crate generates a safe project() method and checks those rules for you. Add it to Cargo.toml:
[dependencies]
pin-project = "1"Mark each field that must stay pinned with #[pin]:
use pin_project::pin_project;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
#[pin_project]
struct CountPolls<F> {
#[pin]
inner: F,
polls: u32,
}
impl<F: Future> Future for CountPolls<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,
}
}
}self.project() returns a generated struct with the same field names. A #[pin] field becomes Pin<&mut F>, and every other field becomes a plain &mut. Here this.inner can be polled directly, and this.polls can be incremented like any u32.
What the crate enforces
- No
Dropimpl. The crate generates a check that rejects a manualDropon the struct. You can use#[pinned_drop]instead, which gives you a pinnedself. - Conditional
Unpin. The struct implementsUnpinonly when all#[pin]fields do. Unpinned fields do not affect this. - No moves out of pinned fields. A
#[pin]field is only reachable asPin<&mut F>, so you cannot callmem::replaceon it.
Exercise
In CountPolls, why is polls not marked #[pin], and what type does this.polls have after project()?
Show answer
polls is a u32 that is never polled and never borrowed by a self-reference, so it does not need a pinning guarantee. Without #[pin], project() gives it as a plain &mut u32, so *this.polls += 1 works. Only inner needs Pin<&mut F>, because Future::poll requires a pinned receiver.