mod.rs - source
Description: Source of the Rust file `library/core/src/async_iter/mod.rs`.

#
core/async_iter/
mod.rs

    1//! Composable asynchronous iteration.
    2//!
    3//! If you've found yourself with an asynchronous collection of some kind,
    4//! and needed to perform an operation on the elements of said collection,
    5//! you'll quickly run into 'async iterators'. Async Iterators are heavily used in
    6//! idiomatic asynchronous Rust code, so it's worth becoming familiar with them.
    7//!
    8//! Before explaining more, let's talk about how this module is structured:
    9//!
    10//! # Organization
    11//!
    12//! This module is largely organized by type:
    13//!
    14//! * [Traits] are the core portion: these traits define what kind of async iterators
    15//!   exist and what you can do with them. The methods of these traits are worth
    16//!   putting some extra study time into.
    17//! * Functions provide some helpful ways to create some basic async iterators.
    18//! * Structs are often the return types of the various methods on this
    19//!   module's traits. You'll usually want to look at the method that creates
    20//!   the `struct`, rather than the `struct` itself. For more detail about why,
    21//!   see '[Implementing Async Iterator](#implementing-async-iterator)'.
    22//!
    23//! [Traits]: #traits
    24//!
    25//! That's it! Let's dig into async iterators.
    26//!
    27//! # Async Iterators
    28//!
    29//! The heart and soul of this module is the [`AsyncIterator`] trait. The core of
    30//! [`AsyncIterator`] looks like this:
    31//!
    32//! ```
    33//! # use core::task::{Context, Poll};
    34//! # use core::pin::Pin;
    35//! trait AsyncIterator {
    36//!     type Item;
    37//!     fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>;
    38//! }
    39//! ```
    40//!
    41//! Unlike `Iterator`, `AsyncIterator` makes a distinction between the [`poll_next`]
    42//! method which is used when implementing an `AsyncIterator`, and a (to-be-implemented)
    43//! `next` method which is used when consuming an async iterator. Consumers of `AsyncIterator`
    44//! only need to consider `next`, which when called, returns a future which
    45//! yields `Option<AsyncIterator::Item>`.
    46//!
    47//! The future returned by `next` will yield `Some(Item)` as long as there are
    48//! elements, and once they've all been exhausted, will yield `None` to indicate
    49//! that iteration is finished. If we're waiting on something asynchronous to
    50//! resolve, the future will wait until the async iterator is ready to yield again.
    51//!
    52//! Individual async iterators may choose to resume iteration, and so calling `next`
    53//! again may or may not eventually yield `Some(Item)` again at some point.
    54//!
    55//! [`AsyncIterator`]'s full definition includes a number of other methods as well,
    56//! but they are default methods, built on top of [`poll_next`], and so you get
    57//! them for free.
    58//!
    59//! [`Poll`]: super::task::Poll
    60//! [`poll_next`]: AsyncIterator::poll_next
    61//!
    62//! # Implementing Async Iterator
    63//!
    64//! Creating an async iterator of your own involves two steps: creating a `struct` to
    65//! hold the async iterator's state, and then implementing [`AsyncIterator`] for that
    66//! `struct`.
    67//!
    68//! Let's make an async iterator named `Counter` which counts from `1` to `5`:
    69//!
    70//! ```no_run
    71//! #![feature(async_iterator)]
    72//! # use core::async_iter::AsyncIterator;
    73//! # use core::task::{Context, Poll};
    74//! # use core::pin::Pin;
    75//!
    76//! // First, the struct:
    77//!
    78//! /// An async iterator which counts from one to five
    79//! struct Counter {
    80//!     count: usize,
    81//! }
    82//!
    83//! // we want our count to start at one, so let's add a new() method to help.
    84//! // This isn't strictly necessary, but is convenient. Note that we start
    85//! // `count` at zero, we'll see why in `poll_next()`'s implementation below.
    86//! impl Counter {
    87//!     fn new() -> Counter {
    88//!         Counter { count: 0 }
    89//!     }
    90//! }
    91//!
    92//! // Then, we implement `AsyncIterator` for our `Counter`:
    93//!
    94//! impl AsyncIterator for Counter {
    95//!     // we will be counting with usize
    96//!     type Item = usize;
    97//!
    98//!     // poll_next() is the only required method
    99//!     fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
    100//!         // Increment our count. This is why we started at zero.
    101//!         self.count += 1;
    102//!
    103//!         // Check to see if we've finished counting or not.
    104//!         if self.count < 6 {
    105//!             Poll::Ready(Some(self.count))
    106//!         } else {
    107//!             Poll::Ready(None)
    108//!         }
    109//!     }
    110//! }
    111//! ```
    112//!
    113//! # Laziness
    114//!
    115//! Async iterators are *lazy*. This means that just creating an async iterator doesn't
    116//! _do_ a whole lot. Nothing really happens until you call `poll_next`. This is
    117//! sometimes a source of confusion when creating an async iterator solely for its side
    118//! effects. The compiler will warn us about this kind of behavior:
    119//!
    120//! ```text
    121//! warning: unused result that must be used: async iterators do nothing unless polled
    122//! ```
    123
    124mod async_iter;
    125mod from_iter;
    126
    127pub use async_iter::{AsyncIterator, IntoAsyncIterator};
    128pub use from_iter::{FromIter, from_iter};