async_iter_ext/combinator/
map.rs1use 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#[must_use = "async iterator combinators are lazy and do nothing unless consumed"]
14pub struct AsyncMap<I, F> {
15 pub(crate) iter: I,
16 pub(crate) f: F,
17}
18
19impl<B, I, F, Fut> PollSyncIter for AsyncMap<I, F>
20where
21 I: AsyncIterator + Unpin,
22 F: FnMut(I::Item) -> Fut + Unpin + Send,
23 Fut: Future<Output = B> + Send,
24{
25}
26
27impl<B, I, F, Fut> Future for AsyncMap<I, F>
28where
29 I: AsyncIterator + Unpin,
30 F: FnMut(I::Item) -> Fut + Unpin + Send,
31 Fut: Future<Output = B> + Send,
32{
33 type Output = SyncIter<IntoIter<B>>;
34
35 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
36 Self::poll_sync_iter(self, cx)
37 }
38}
39
40impl<B, I, F, Fut> AsyncIterator for AsyncMap<I, F>
41where
42 I: AsyncIterator,
43 F: FnMut(I::Item) -> Fut + Send,
44 Fut: Future<Output = B> + Send,
45{
46 type Item = B;
47
48 async fn next_async(&mut self) -> Option<Self::Item> {
49 if let Some(next) = self.iter.next_async().await {
50 Some((self.f)(next).await)
51 } else {
52 None
53 }
54 }
55
56 fn async_size_hint(&self) -> (usize, Option<usize>) {
57 self.iter.async_size_hint()
58 }
59}
60
61impl<I, F> Debug for AsyncMap<I, F>
62where
63 I: AsyncIterator + Debug,
64{
65 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
66 f.debug_struct("AsyncMap").field("iter", &self.iter).finish()
67 }
68}