async_std/option/
from_stream.rs

1use std::pin::Pin;
2
3use crate::prelude::*;
4use crate::stream::{FromStream, IntoStream};
5use std::convert::identity;
6
7impl<T, V> FromStream<Option<T>> for Option<V>
8where
9    V: FromStream<T>,
10{
11    /// Takes each element in the stream: if it is `None`, no further
12    /// elements are taken, and `None` is returned. Should no `None`
13    /// occur, a container with the values of each `Option` is returned.
14    #[inline]
15    fn from_stream<'a, S: IntoStream<Item = Option<T>> + 'a>(
16        stream: S,
17    ) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
18        let stream = stream.into_stream();
19
20        Box::pin(async move {
21            // Using `take_while` here because it is able to stop the stream early
22            // if a failure occurs
23            let mut found_none = false;
24            let out: V = stream
25                .take_while(|elem| {
26                    elem.is_some() || {
27                        found_none = true;
28                        // Stop processing the stream on `None`
29                        false
30                    }
31                })
32                .filter_map(identity)
33                .collect()
34                .await;
35
36            if found_none { None } else { Some(out) }
37        })
38    }
39}