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
use async_std::future::Future;
use async_std::sync::{self, Receiver};
use async_std::task;
use std::pin::Pin;
use std::task::{Context, Poll};
use crate::ParallelStream;
pin_project_lite::pin_project! {
#[derive(Debug)]
pub struct Map<T> {
#[pin]
receiver: Receiver<T>,
limit: Option<usize>,
}
}
impl<T: Send + 'static> Map<T> {
pub fn new<S, F, Fut>(mut stream: S, mut f: F) -> Self
where
S: ParallelStream,
F: FnMut(S::Item) -> Fut + Send + Sync + Copy + 'static,
Fut: Future<Output = T> + Send,
{
let (sender, receiver) = sync::channel(1);
let limit = stream.get_limit();
task::spawn(async move {
while let Some(item) = stream.next().await {
let sender = sender.clone();
task::spawn(async move {
let res = f(item).await;
sender.send(res).await;
});
}
});
Map { receiver, limit }
}
}
impl<T: Send + 'static> ParallelStream for Map<T> {
type Item = T;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
use async_std::prelude::*;
let this = self.project();
this.receiver.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
}
}
#[async_std::test]
async fn smoke() {
use async_std::prelude::*;
let s = async_std::stream::repeat(5usize).take(3);
let mut output = vec![];
let mut stream = crate::from_stream(s).map(|n| async move { n * 2 });
while let Some(n) = stream.next().await {
output.push(n);
}
assert_eq!(output, vec![10usize; 3]);
}