>catasync-iterators-in-rust.md

Async Iterators in Rust

date

Rust’s synchronous iterators have been stable since 1.0; asynchronous iteration is still being worked out. On nightly, the standard library’s AsyncIterator trait exists, though its method is poll_next rather than an async fn next(). On stable, ecosystem crates such as futures::Stream fill the gap, and the shape the standard trait will finally take is still being argued over.

The synchronous trait

The point of comparison is Iterator:

pub trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}

It has served Rust well. next returns Option<Item>, with None signalling termination, and the mutable reference guarantees exclusive access for the duration of iteration.

The asynchronous traits

The nightly AsyncIterator trait is not, as one might expect, Iterator with an async in front of next. It is a polling interface:

#![feature(async_iterator)]

pub trait AsyncIterator {
    type Item;

    fn poll_next(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Self::Item>>;
}

In substance it is the ecosystem’s futures::Stream, which stable code uses:

use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

pub trait Stream {
    type Item;

    fn poll_next(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Self::Item>>;
}

This is the lower level, at which the implementation of async functions shows through. The Pin<&mut Self> parameter answers a constraint peculiar to async code. Rust permits values to be moved by default, but async code often produces self-referential structures, in which a future holds references to its own fields, and moving such a structure would invalidate those references. Pin guarantees that the stream will not be moved once polling has begun; it is a zero-cost abstraction, and the compiler uses it to enforce safety at compile time.

Since the two traits have the same shape, I implement futures::Stream below; it is what stable code uses today, and implementing it by hand makes the execution model visible.

A delayed range

As an example, consider a stream that yields a range of numbers with a delay before each:

use std::time::Duration;
use tokio::time::{sleep, Sleep};

struct DelayedRange {
    current: u32,
    end: u32,
    duration: Duration,
    delay: Pin<Box<Sleep>>,
}

impl DelayedRange {
    fn new(start: u32, end: u32, duration: Duration) -> Self {
        Self {
            current: start,
            end,
            duration,
            delay: Box::pin(sleep(duration)),
        }
    }
}

impl Stream for DelayedRange {
    type Item = u32;

    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Self::Item>> {
        // Check if we've finished
        if self.current >= self.end {
            return Poll::Ready(None);
        }

        // Poll the delay future
        match self.delay.as_mut().poll(cx) {
            Poll::Ready(_) => {
                let value = self.current;
                self.current += 1;

                // Reset the delay for next iteration
                let duration = self.duration;
                self.delay = Box::pin(sleep(duration));

                Poll::Ready(Some(value))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

Async functions in traits have been stable since Rust 1.75 (December 2023), so a trait whose next is itself an async fn can be written on stable Rust. It is not the standard library’s trait, but against it the same range is considerably shorter:

use std::time::Duration;
use tokio::time::sleep;

trait AsyncIter {
    type Item;
    async fn next(&mut self) -> Option<Self::Item>;
}

struct DelayedRangeAsync {
    current: u32,
    end: u32,
    duration: Duration,
}

impl DelayedRangeAsync {
    fn new(start: u32, end: u32, duration: Duration) -> Self {
        Self {
            current: start,
            end,
            duration,
        }
    }
}

impl AsyncIter for DelayedRangeAsync {
    type Item = u32;

    async fn next(&mut self) -> Option<Self::Item> {
        if self.current >= self.end {
            return None;
        }

        sleep(self.duration).await;
        let value = self.current;
        self.current += 1;
        Some(value)
    }
}

Pinning, manual state management and polling all disappear. What remains reads like async iteration in other languages, though whether the standard trait should take this form is a question the Rust project has not settled.

Where things stand

The nightly trait remains unstable while its design is discussed, chiefly whether to keep poll_next or to move to an async fn next. Stable code relies on the ecosystem: the async-stream crate provides macros for writing streams, and futures supplies combinators (map, filter, fold) that parallel those on Iterator.

Async functions in traits are already stable, so that obstacle is gone; AsyncIterator nonetheless remains on nightly. The polling interface of futures::Stream will keep its uses whatever form the standard trait takes, both for understanding the execution model and for performance-critical code that needs fine-grained control over the async state machine.

Syntax

  • AsyncIterator is the standard library’s unstable trait.
  • futures::Stream is its stable counterpart in the ecosystem.
  • async fn next writes iteration as an ordinary async method.
  • poll_next exposes the polling mechanism beneath it.
  • Pin<&mut T> enforces immovability during polling.