parallel_stream/par_stream/
mod.rs

1use async_std::future::Future;
2use async_std::task::{Context, Poll};
3
4use std::pin::Pin;
5
6use crate::FromParallelStream;
7
8pub use for_each::ForEach;
9pub use map::Map;
10pub use next::NextFuture;
11pub use take::Take;
12
13mod for_each;
14mod map;
15mod next;
16mod take;
17
18/// Parallel version of the standard `Stream` trait.
19pub trait ParallelStream: Sized + Send + Sync + Unpin + 'static {
20    /// The type of items yielded by this stream.
21    type Item: Send;
22
23    /// Attempts to receive the next item from the stream.
24    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>;
25
26    /// Set a max concurrency limit
27    fn limit(self, limit: impl Into<Option<usize>>) -> Self;
28
29    /// Get the max concurrency limit
30    fn get_limit(&self) -> Option<usize>;
31
32    /// Applies `f` to each item of this stream in parallel, producing a new
33    /// stream with the results.
34    fn map<F, T, Fut>(self, f: F) -> Map<T>
35    where
36        F: FnMut(Self::Item) -> Fut + Send + Sync + Copy + 'static,
37        T: Send + 'static,
38        Fut: Future<Output = T> + Send,
39    {
40        Map::new(self, f)
41    }
42
43    /// Applies `f` to each item of this stream in parallel, producing a new
44    /// stream with the results.
45    fn next(&mut self) -> NextFuture<'_, Self> {
46        NextFuture::new(self)
47    }
48
49    /// Creates a stream that yields its first `n` elements.
50    fn take(self, n: usize) -> Take<Self>
51    where
52        Self: Sized,
53    {
54        Take::new(self, n)
55    }
56
57    /// Applies `f` to each item of this stream in parallel.
58    fn for_each<F, Fut>(self, f: F) -> ForEach
59    where
60        F: FnMut(Self::Item) -> Fut + Send + Sync + Copy + 'static,
61        Fut: Future<Output = ()> + Send,
62    {
63        ForEach::new(self, f)
64    }
65
66    /// Transforms a stream into a collection.
67    ///
68    ///`collect()` can take anything streamable, and turn it into a relevant
69    /// collection. This is one of the more powerful methods in the async
70    /// standard library, used in a variety of contexts.
71    fn collect<'a, B>(self) -> Pin<Box<dyn Future<Output = B> + 'a + Send>>
72    where
73        Self: Sized + 'a,
74        B: FromParallelStream<Self::Item>,
75    {
76        FromParallelStream::from_par_stream(self)
77    }
78}