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
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use crate::{from_stream, FromParallelStream, FromStream, IntoParallelStream, ParallelStream};
use async_std::stream::{from_iter, FromIter};
use std::vec;
pin_project_lite::pin_project! {
#[derive(Debug)]
pub struct IntoParStream<T> {
#[pin]
stream: FromStream<FromIter<vec::IntoIter<T>>>,
limit: Option<usize>,
}
}
impl<T: Send + Sync + 'static> ParallelStream for IntoParStream<T> {
type Item = T;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
this.stream.poll_next(cx)
}
fn limit(mut self, limit: impl Into<Option<usize>>) -> Self {
self.limit = limit.into();
self
}
fn get_limit(&self) -> Option<usize> {
self.limit
}
}
impl<T: Send + Sync + 'static> IntoParallelStream for Vec<T> {
type Item = T;
type IntoParStream = IntoParStream<T>;
#[inline]
fn into_par_stream(self) -> Self::IntoParStream {
IntoParStream {
stream: from_stream(from_iter(self)),
limit: None,
}
}
}
impl<T: Send> FromParallelStream<T> for Vec<T> {
fn from_par_stream<'a, S>(stream: S) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
where
S: IntoParallelStream<Item = T> + Send + 'a,
{
Box::pin(async move {
let mut stream = stream.into_par_stream();
let mut res = Vec::with_capacity(0);
while let Some(item) = stream.next().await {
res.push(item);
}
res
})
}
}
#[async_std::test]
async fn smoke() {
use crate::IntoParallelStream;
let v = vec![1, 2, 3, 4];
let mut stream = v.into_par_stream().map(|n| async move { n * n });
let mut out = vec![];
while let Some(n) = stream.next().await {
out.push(n);
}
out.sort();
assert_eq!(out, vec![1usize, 4, 9, 16]);
}