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
#![feature(type_alias_impl_trait)]
#![forbid(unsafe_code, future_incompatible, rust_2018_idioms)]
#![deny(missing_debug_implementations, nonstandard_style)]
#![warn(missing_docs, unreachable_pub)]
pub use async_trait::async_trait;
use std::future::Future;
pub mod prelude {
pub use super::{IntoIterator, Iterator, FromIterator, Extend};
}
#[async_trait(?Send)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub trait Iterator {
type Item;
async fn next(&mut self) -> Option<Self::Item>;
fn size_hint(&self) -> (usize, Option<usize>) {
(0, None)
}
fn map<B, F>(self, f: F) -> Map<Self, F>
where
Self: Sized,
F: FnMut(Self::Item) -> B
{
Map {
stream: self,
f,
}
}
#[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
}
}
#[async_trait(?Send)]
pub trait IntoIterator {
type Item;
type IntoIter: Iterator<Item = Self::Item>;
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
}
}
#[async_trait(?Send)]
pub trait FromIterator<A>: Sized {
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
}
}
#[async_trait(?Send)]
pub trait Extend<A> {
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);
}
}
}
#[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)
}
}