Sub topic 15
Pin and Unpin
This chapter assumes you know ownership and moves, traits and trait objects, and the Future trait with poll. It explains why poll takes Pin<&mut Self> and what Unpin means.
The problem: futures can point at themselves
The compiler turns an async fn into a state machine. If the function holds a reference to one of its own local variables across an .await, the state machine stores both the variable and a reference to it in the same struct. That makes the struct self-referential.
Moving such a struct breaks it. A move copies the bytes to a new address, but the internal reference still points at the old one. Safe Rust must not allow this, so futures need a way to promise they will stay in place once polling starts.
What Pin does
Pin<P> wraps a pointer type P, such as &mut T or Box<T>. It stops safe code from getting a &mut T to the pointed-to value, and without that reference you cannot move the value out with mem::swap or mem::replace. This is why poll has the signature fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>). The executor must pin a future before polling it.
Unpin: the opt-out
Unpin is an auto trait. It marks types that are safe to move even when pinned. Most types are Unpin, including integers, String, and Vec. For these types Pin does nothing, and you can freely get a &mut back out.
Futures generated from async blocks are !Unpin, because they may be self-referential. You can also opt out yourself by adding a std::marker::PhantomPinned field.
Pinning in practice
You usually meet Pin in two places. The first is storing different futures in one collection. Box::pin puts a future on the heap and pins it there:
use std::future::Future;
use std::pin::Pin;
async fn double(x: u32) -> u32 {
x * 2
}
#[tokio::main]
async fn main() {
let mut futures: Vec<Pin<Box<dyn Future<Output = u32>>>> = Vec::new();
futures.push(Box::pin(double(21)));
futures.push(Box::pin(async { 10 }));
for f in futures {
println!("{}", f.await);
}
}The second is polling a future by reference, as in a select! loop. Tokio's Sleep is !Unpin, so you pin it on the stack with std::pin::pin!:
use std::pin::pin;
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let mut work = pin!(sleep(Duration::from_millis(50)));
tokio::select! {
_ = &mut work => println!("work finished"),
_ = sleep(Duration::from_secs(1)) => println!("timed out"),
}
}Common errors
the trait bound ...: Unpin is not satisfied: you used a!Unpinfuture by&mutreference. Wrap it withpin!orBox::pin.the size for values of type dyn Future cannot be known: you stored a trait object without a pointer. UsePin<Box<dyn Future<Output = T>>>.- Moving a future after its first poll: safe code cannot do this once it is pinned, so the compiler rejects it.
Exercise
Why does Pin have no effect on a u32, but matters for the future from an async block?
Show answer
u32 is Unpin, so moving it is always safe and Pin lets you take &mut freely. An async block's future may contain references to its own fields, so it is !Unpin. Pin prevents it from being moved after polling starts, which keeps those internal references valid.