1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
//! An async version of iterator.
//! 
//! This crate provides the following capabilities:
//! 
//! - The base async `Iterator` trait implemented with `async fn next`
//! - The ability to `collect` into a `vec`
//! - The ability to asynchronously `map` over values in the iterator
//! - The ability to extend `vec` with an async iterator
//!
//! # Trait definitions
//!
//! All traits make use of the `async_trait` annotation. In order to implement
//! the traits, use `async_trait`.

#![feature(type_alias_impl_trait)]
#![forbid(unsafe_code, future_incompatible, rust_2018_idioms)]
#![deny(missing_debug_implementations, nonstandard_style)]
#![warn(missing_docs, unreachable_pub)]

/// `async-trait` re-export
pub use async_trait::async_trait;
use std::future::Future;

/// The `async-iterator` prelude
pub mod prelude {
    pub use super::{IntoIterator, Iterator, FromIterator, Extend};
}

/// An interface for dealing with iterators.
#[async_trait(?Send)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub trait Iterator {
    /// The type of the elements being iterated over.
    type Item;

    /// Advances the iterator and returns the next value.
    async fn next(&mut self) -> Option<Self::Item>;

    /// Returns the bounds on the remaining length of the iterator.
    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, None)
    }

    /// Takes a closure and creates an iterator which calls that closure on each element.
    fn map<B, F>(self, f: F) -> Map<Self, F>
    where
        Self: Sized,
        F: FnMut(Self::Item) -> B
    {
        Map {
            stream: self,
            f,
        }
    }

    /// Transforms an iterator into a collection.
    #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
    async fn collect<B: FromIterator<Self::Item>>(self) -> B
    where
        Self: Sized,
    {
        FromIterator::from_iter(self).await
    }
}

/// Conversion into an [`Iterator`].
#[async_trait(?Send)]
pub trait IntoIterator {
    /// The type of the elements being iterated over.
    type Item;

    /// Which kind of iterator are we turning this into?
    type IntoIter: Iterator<Item = Self::Item>;

    /// Creates an iterator from a value.
    async fn into_iter(self) -> Self::IntoIter;
}

#[async_trait(?Send)]
impl<I: Iterator> IntoIterator for I {
    type Item = I::Item;
    type IntoIter = I;

    async fn into_iter(self) -> I {
        self
    }
}

/// Conversion from an [`Iterator`].
#[async_trait(?Send)]
pub trait FromIterator<A>: Sized {
    /// Creates a value from an iterator.
    async fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self;
}

#[async_trait(?Send)]
impl<T> FromIterator<T> for Vec<T> {
    #[inline]
    async fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
        let mut iter = iter.into_iter().await;
        let mut output = Vec::with_capacity(iter.size_hint().1.unwrap_or_default());
        while let Some(item) = iter.next().await {
            output.push(item);
        }
        output
    }
}

/// Extend a collection with the contents of an iterator.
#[async_trait(?Send)]
pub trait Extend<A> {
    /// Extends a collection with the contents of an iterator.
    async fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T);
}

#[async_trait(?Send)]
impl<T> Extend<T> for Vec<T> {
    #[inline]
    async fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        let mut iter = iter.into_iter().await;
        self.reserve(iter.size_hint().1.unwrap_or_default());
        while let Some(item) = iter.next().await {
            self.push(item);
        }
    }
}

/// An iterator that maps value of another stream with a function.
#[derive(Debug)]
pub struct Map<I, F> {
    stream: I,
    f: F,
}

#[async_trait(?Send)]
impl<I, F, B, Fut> Iterator for Map<I, F>
where
    I: Iterator,
    F: FnMut(I::Item) -> Fut,
    Fut: Future<Output = B>,
{
    type Item = B;

    async fn next(&mut self) -> Option<Self::Item> {
        let item = self.stream.next().await?;
        let out = (self.f)(item).await;
        Some(out)
    }
}