async_iter_ext/combinator/map.rs
1use std::{
2 fmt::{Debug, Formatter},
3 pin::Pin,
4 task::{Context, Poll},
5 vec::IntoIter,
6};
7
8use crate::iter::{
9 AsyncIterator,
10 sync_iter::{PollSyncIter, SyncIter},
11};
12
13/// An asynchronous iterator adapter that maps each item to a new value using an async function.
14///
15/// `AsyncMap` is similar to the standard `.map()` method on iterators, but it supports asynchronous closures
16/// by allowing the mapping function to return a `Future`. This makes it useful for scenarios where each item
17/// in an iterator needs to be processed using asynchronous logic.
18///
19/// This struct is created by the `.map_async()` method on `AsyncIterTools`.
20///
21/// # Type Parameters
22/// - `I`: The underlying async iterator.
23/// - `F`: The asynchronous mapping function, which produces a future for each item.
24#[must_use = "async iterator combinators are lazy and do nothing unless consumed"]
25pub struct AsyncMap<I, F> {
26 pub(crate) iter: I,
27 pub(crate) f: F,
28}
29
30/// Enables conversion of an `AsyncMap` into a synchronous `SyncIter` by polling the async iterator
31/// and collecting items into a vector. Implements the `PollSyncIter` trait, allowing integration with
32/// the `Future` implementation below.
33impl<B, I, F, Fut> PollSyncIter for AsyncMap<I, F>
34where
35 I: AsyncIterator + Unpin,
36 F: FnMut(I::Item) -> Fut + Unpin + Send,
37 Fut: Future<Output = B> + Send,
38{
39}
40
41/// Allows an `AsyncMap` to be `.await`ed directly, returning a synchronous iterator (`SyncIter`) over
42/// the collected results of the async mapping operation. This makes it possible to use `.await` on
43/// `AsyncMap` to collect all results at once in blocking contexts like `block_on`.
44impl<B, I, F, Fut> Future for AsyncMap<I, F>
45where
46 I: AsyncIterator + Unpin,
47 F: FnMut(I::Item) -> Fut + Unpin + Send,
48 Fut: Future<Output = B> + Send,
49{
50 type Output = SyncIter<IntoIter<B>>;
51
52 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
53 Self::poll_sync_iter(self, cx)
54 }
55}
56
57/// Implements the `AsyncIterator` trait for `AsyncMap`, yielding the result of applying
58/// the async mapping function `f` to each item from the underlying iterator `iter`.
59///
60/// The `next_async()` method awaits the next item and then applies the mapping function,
61/// awaiting its result before yielding it downstream.
62impl<B, I, F, Fut> AsyncIterator for AsyncMap<I, F>
63where
64 I: AsyncIterator,
65 F: FnMut(I::Item) -> Fut + Send,
66 Fut: Future<Output = B> + Send,
67{
68 type Item = B;
69
70 async fn next_async(&mut self) -> Option<Self::Item> {
71 if let Some(next) = self.iter.next_async().await {
72 Some((self.f)(next).await)
73 } else {
74 None
75 }
76 }
77
78 fn async_size_hint(&self) -> (usize, Option<usize>) {
79 self.iter.async_size_hint()
80 }
81}
82
83/// Provides a `Debug` implementation for `AsyncMap` that includes debug output for the underlying iterator.
84/// The mapping function `f` is not shown due to lack of generic support for `Debug` on closures.
85impl<I, F> Debug for AsyncMap<I, F>
86where
87 I: AsyncIterator + Debug,
88{
89 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
90 f.debug_struct("AsyncMap")
91 .field("iter", &self.iter)
92 .finish()
93 }
94}