Sub topic 16
Pin and Unpin
This chapter assumes you know ownership, borrowing, traits and trait objects, and the basics of Future and poll from earlier chapters. It explains why poll takes Pin<&mut Self> instead of &mut Self, what Unpin means, and the errors you meet when you poll futures by hand.
Why futures need pinning
A value in Rust can normally be moved. Moving copies its bytes to a new memory address, and the old location is no longer valid. For most types this is harmless.
It becomes a problem for self-referential values, which hold a pointer into themselves. Async functions create them easily:
async fn example() {
let buf = [0u8; 64];
let slice = &buf[..];
tokio::task::yield_now().await;
println!("{}", slice.len());
}The generated future stores buf and slice as fields of the same struct, and slice points at buf. The .await suspends the future, so both fields must survive between polls. If the future were moved after the first poll, slice would still point at the old address, and the program would read invalid memory.
Safe Rust cannot express a struct that borrows from its own field. The compiler generates such futures anyway, so it needs a way to promise that they stay put once polling starts. Pin is that promise.
What Pin does
Pin<P> wraps a pointer type P, such as &mut T, Box<T>, or Rc<T>. It restricts what safe code can do with the pointee. While the value is pinned, you cannot get a plain &mut T from it, so you cannot call mem::swap or mem::replace on it. The value stays at one address until it is dropped.
That is why the signature is:
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;The executor can poll the future many times, and each call has the same guarantee: the future has not moved since the last poll.
Pin does not stop a value from being moved before it is pinned. A future that has never been polled has no internal borrows yet, so it is safe to move. Pinning is what you do just before the first poll.
Unpin: the opt-out
Most types do not care about their address. u32, String, Vec<T> and most structs you write have no self-references. These types implement the auto trait Unpin, which means "pinning me gives no extra guarantee, so moving me is fine."
For an Unpin type, Pin<&mut T> is as flexible as &mut T:
Pin::new(&mut value)is a safe function, available only whenT: Unpin.Pin::get_mutreturns the&mut T, again only whenT: Unpin.
Compiler-generated futures from async fn and async blocks are !Unpin (not Unpin). That is the case where pinning matters. The hand-written YieldOnce future from the earlier chapter contains only a bool, so it is Unpin. That is why self.yielded = true worked through mut self: Pin<&mut Self>: Pin<&mut T> implements DerefMut when T: Unpin.
| Type | Unpin? | Safe way to pin |
|---|---|---|
| `u32`, `String`, `Vec<T>` | Yes | `Pin::new(&mut x)` |
| `YieldOnce` (only a `bool`) | Yes | `Pin::new(&mut x)` |
| Future from `async fn` or `async {}` | No | `Box::pin(f)` or `pin!(f)` |
| `Pin<Box<dyn Future>>` | Yes | Already pinned. The box itself can move |
Pinning in practice
You rarely write Pin by hand. .await pins the future for you inside the async function. You meet it directly in three places.
Boxing with Box::pin
Box::pin(fut) moves the future onto the heap and returns Pin<Box<F>>. The heap address does not change when the box moves, so the future is safe. This is how you store futures of different types in one collection or write a recursive async function:
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;
use tokio::time::sleep;
fn countdown(n: u32) -> Pin<Box<dyn Future<Output = u32> + Send>> {
Box::pin(async move {
if n == 0 {
return 0;
}
sleep(Duration::from_millis(10)).await;
1 + countdown(n - 1).await
})
}
#[tokio::main]
async fn main() {
println!("{}", countdown(3).await);
}Without the box, the compiler would reject the recursion because the future's size would be infinite. The box gives it a fixed size, and the Pin makes the boxed future safe to poll.
Pinning on the stack with pin!
The std::pin::pin! macro pins a value to the current stack frame with no allocation. It returns a Pin<&mut T>. You need it when a function such as select! loop code polls the same future repeatedly by reference:
use std::pin::pin;
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let work = pin!(sleep(Duration::from_millis(50)));
tokio::select! {
_ = work => println!("work finished"),
_ = sleep(Duration::from_secs(1)) => println!("deadline"),
}
}pin! is in the standard library since Rust 1.68. tokio::pin! does the same thing.
Polling a future by hand
When you implement Future for a wrapper type, you must forward poll to the inner future. If the inner future is Unpin, Pin::new is enough:
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct Logged<F> {
inner: F,
}
impl<F: Future + Unpin> Future for Logged<F> {
type Output = F::Output;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<F::Output> {
println!("polling");
Pin::new(&mut self.inner).poll(cx)
}
}The F: Unpin bound is the limitation. To wrap any future, including async blocks, you need pin projection: turning Pin<&mut Logged<F>> into Pin<&mut F>. Doing that soundly requires unsafe, so use the pin-project or pin-project-lite crate, which generate the projection for you.
Common errors
The most frequent error looks like this:
error[E0277]: `{async block}` cannot be unpinned
= note: consider using the `pin!` macro
consider using `Box::pin` if you need to access the pinned value outside of the current scopeIt means an API required Unpin and you gave it an async future. Fix it with Box::pin(fut) when the future must outlive the scope, or pin!(fut) when it stays local.
Other situations that cause trouble:
- Calling
.poll()on a future that is not pinned. The method needsPin<&mut Self>, so you must pin first. - Selecting over
&mut futin a loop. The reference is only usable if the future isUnpin, so pin it withpin!first. - Putting
!Unpinfutures in aVec. UseVec<Pin<Box<dyn Future<Output = T>>>>.
What Pin does not do
- It does not allocate.
Box::pinallocates, butPinitself is only a wrapper. - It does not make a value immovable in all cases.
Unpintypes can still be moved freely. - It does not stop
Drop. A pinned value must still have its destructor run before its memory is reused, which is part of the pinning contract.
How the pieces fit
Exercise
A function takes fut: impl Future<Output = ()> + Unpin and you pass it the value of async { println!("hi") }. The compiler reports that the async block cannot be unpinned. Show two ways to fix the call and say when you would choose each.
Show answer
Wrap the future before passing it. Option 1: takes(Box::pin(async { println!("hi") })). This works because Pin<Box<F>> is Unpin, so it satisfies the bound. It allocates, but the pinned future can be returned or stored beyond the current scope. Option 2: takes(pin!(async { println!("hi") })), with use std::pin::pin;. This pins on the stack with no allocation, but the result is a Pin<&mut F> that borrows the local frame, so it cannot outlive the function. Choose Box::pin when the future must be stored or returned, and pin! when it is used locally and you want to avoid an allocation.
Exercise
Why is Pin::new(&mut x) safe for a u32 but not available for a future produced by an async fn?
Show answer
Pin::new requires T: Unpin. A u32 has no self-references, so it is Unpin and moving it is always fine. A future from an async fn may hold references into its own fields across an .await, so the compiler marks it !Unpin. Allowing Pin::new on it would let safe code take &mut and move it with mem::swap, which would leave those internal references dangling.