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: Send, 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 + Send>> 
18    where
19        <S as IntoStream>::IntoStream: Send,
20    {
21        let stream = stream.into_stream();
22
23        Box::pin(async move {
24            // Using `take_while` here because it is able to stop the stream early
25            // if a failure occurs
26            let mut found_none = false;
27            let out: V = stream
28                .take_while(|elem| {
29                    elem.is_some() || {
30                        found_none = true;
31                        // Stop processing the stream on `None`
32                        false
33                    }
34                })
35                .filter_map(identity)
36                .collect()
37                .await;
38
39            if found_none { None } else { Some(out) }
40        })
41    }
42}