futures_concurrency/concurrent_stream/
from_concurrent_stream.rs

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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
use super::{ConcurrentStream, Consumer, ConsumerState, IntoConcurrentStream};
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::vec::Vec;
use core::future::Future;
use core::pin::Pin;
use futures_buffered::FuturesUnordered;
use futures_lite::StreamExt;
use pin_project::pin_project;

/// Conversion from a [`ConcurrentStream`]
#[allow(async_fn_in_trait)]
pub trait FromConcurrentStream<A>: Sized {
    /// Creates a value from a concurrent iterator.
    async fn from_concurrent_stream<T>(iter: T) -> Self
    where
        T: IntoConcurrentStream<Item = A>;
}

impl<T> FromConcurrentStream<T> for Vec<T> {
    async fn from_concurrent_stream<S>(iter: S) -> Self
    where
        S: IntoConcurrentStream<Item = T>,
    {
        let stream = iter.into_co_stream();
        let mut output = Vec::with_capacity(stream.size_hint().1.unwrap_or_default());
        stream.drive(VecConsumer::new(&mut output)).await;
        output
    }
}

impl<T, E> FromConcurrentStream<Result<T, E>> for Result<Vec<T>, E> {
    async fn from_concurrent_stream<S>(iter: S) -> Self
    where
        S: IntoConcurrentStream<Item = Result<T, E>>,
    {
        let stream = iter.into_co_stream();
        let mut output = Ok(Vec::with_capacity(stream.size_hint().1.unwrap_or_default()));
        stream.drive(ResultVecConsumer::new(&mut output)).await;
        output
    }
}

// TODO: replace this with a generalized `fold` operation
#[pin_project]
pub(crate) struct VecConsumer<'a, Fut: Future> {
    #[pin]
    group: FuturesUnordered<Fut>,
    output: &'a mut Vec<Fut::Output>,
}

impl<'a, Fut: Future> VecConsumer<'a, Fut> {
    pub(crate) fn new(output: &'a mut Vec<Fut::Output>) -> Self {
        Self {
            group: FuturesUnordered::new(),
            output,
        }
    }
}

impl<'a, Item, Fut> Consumer<Item, Fut> for VecConsumer<'a, Fut>
where
    Fut: Future<Output = Item>,
{
    type Output = ();

    async fn send(self: Pin<&mut Self>, future: Fut) -> super::ConsumerState {
        let mut this = self.project();
        // unbounded concurrency, so we just goooo
        this.group.as_mut().push(future);
        ConsumerState::Continue
    }

    async fn progress(self: Pin<&mut Self>) -> super::ConsumerState {
        let mut this = self.project();
        while let Some(item) = this.group.next().await {
            this.output.push(item);
        }
        ConsumerState::Empty
    }
    async fn flush(self: Pin<&mut Self>) -> Self::Output {
        let mut this = self.project();
        while let Some(item) = this.group.next().await {
            this.output.push(item);
        }
    }
}

#[pin_project]
pub(crate) struct ResultVecConsumer<'a, Fut: Future, T, E> {
    #[pin]
    group: FuturesUnordered<Fut>,
    output: &'a mut Result<Vec<T>, E>,
}

impl<'a, Fut: Future, T, E> ResultVecConsumer<'a, Fut, T, E> {
    pub(crate) fn new(output: &'a mut Result<Vec<T>, E>) -> Self {
        Self {
            group: FuturesUnordered::new(),
            output,
        }
    }
}

impl<'a, Fut, T, E> Consumer<Result<T, E>, Fut> for ResultVecConsumer<'a, Fut, T, E>
where
    Fut: Future<Output = Result<T, E>>,
{
    type Output = ();

    async fn send(self: Pin<&mut Self>, future: Fut) -> super::ConsumerState {
        let mut this = self.project();
        // unbounded concurrency, so we just goooo
        this.group.as_mut().push(future);
        ConsumerState::Continue
    }

    async fn progress(self: Pin<&mut Self>) -> super::ConsumerState {
        let mut this = self.project();
        let Ok(items) = this.output else {
            return ConsumerState::Break;
        };

        while let Some(item) = this.group.next().await {
            match item {
                Ok(item) => {
                    items.push(item);
                }
                Err(e) => {
                    **this.output = Err(e);
                    return ConsumerState::Break;
                }
            }
        }
        ConsumerState::Empty
    }

    async fn flush(self: Pin<&mut Self>) -> Self::Output {
        self.progress().await;
    }
}

#[cfg(test)]
mod test {
    use crate::prelude::*;
    use futures_lite::stream;

    #[test]
    fn collect() {
        futures_lite::future::block_on(async {
            let v: Vec<_> = stream::repeat(1).co().take(5).collect().await;
            assert_eq!(v, &[1, 1, 1, 1, 1]);
        });
    }

    #[test]
    fn collect_to_result_ok() {
        futures_lite::future::block_on(async {
            let v: Result<Vec<_>, ()> = stream::repeat(Ok(1)).co().take(5).collect().await;
            assert_eq!(v, Ok(vec![1, 1, 1, 1, 1]));
        });
    }

    #[test]
    fn collect_to_result_err() {
        futures_lite::future::block_on(async {
            let v: Result<Vec<_>, _> = stream::repeat(Err::<u8, _>(()))
                .co()
                .take(5)
                .collect()
                .await;
            assert_eq!(v, Err(()));
        });
    }
}