What does the compiler turn an async fn into, and what decides that future's size and Send?
Into an anonymous enum implementing Future, a state per .await holding the arguments and the locals live across it. Its size is the largest state, so a buffer kept across .await bloats it; it is Send if those values are, and !Unpin.
- Thinking every local of the function is stored, not only those live across an
.await - Assuming the future is boxed on the heap and therefore pointer-sized
- Believing an
async fnfuture isSendwhenever its output type is
- How would you shrink a future that holds a 64 KB buffer across an
.await? - Why does a recursive
async fnfail to compile withoutBox::pin(E0733)?
The compiler rewrites the body of an async fn into an anonymous type: an enum with a variant for the initial state, one for each .await point and one for completion. Each variant holds the arguments and the locals whose scope spans that point, even if they are not used after it. The variants share one block of memory, so the future's size equals its largest state, not the sum of all variables. The code below is built with rustc 1.99:
async fn tick() {}
async fn small() {
tick().await;
}
async fn big() {
let buf = [0u8; 1024];
tick().await; // buf is needed after .await and is stored in the state
println!("{}", buf[0]);
}
async fn short_lived() {
{
let buf = [0u8; 1024];
println!("{}", buf[0]);
} // buf is dropped before .await and does not enter the state
tick().await;
}
fn main() {
println!("{}", std::mem::size_of_val(&small())); // 2
println!("{}", std::mem::size_of_val(&big())); // 1026
println!("{}", std::mem::size_of_val(&short_lived())); // 2
}The auto traits follow from what the states hold: the future is Send if everything living across an .await is Send; a single Rc or MutexGuard in a state takes Send away. The output type plays no part. A generated future never implements Unpin — not even small(), which holds no references: the compiler assumes the state may refer to its own fields after the first poll and requires Pin to poll it. A large buffer held across .await is shrunk by moving it into a Box or narrowing its scope, as in short_lived.