• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use core::mem;
2 use core::pin::Pin;
3 use futures_core::future::{FusedFuture, Future};
4 use futures_core::ready;
5 use futures_core::stream::{FusedStream, TryStream};
6 use futures_core::task::{Context, Poll};
7 use pin_project_lite::pin_project;
8 
9 pin_project! {
10     /// Future for the [`try_collect`](super::TryStreamExt::try_collect) method.
11     #[derive(Debug)]
12     #[must_use = "futures do nothing unless you `.await` or poll them"]
13     pub struct TryCollect<St, C> {
14         #[pin]
15         stream: St,
16         items: C,
17     }
18 }
19 
20 impl<St: TryStream, C: Default> TryCollect<St, C> {
new(s: St) -> Self21     pub(super) fn new(s: St) -> Self {
22         Self {
23             stream: s,
24             items: Default::default(),
25         }
26     }
27 }
28 
29 impl<St, C> FusedFuture for TryCollect<St, C>
30 where
31     St: TryStream + FusedStream,
32     C: Default + Extend<St::Ok>,
33 {
is_terminated(&self) -> bool34     fn is_terminated(&self) -> bool {
35         self.stream.is_terminated()
36     }
37 }
38 
39 impl<St, C> Future for TryCollect<St, C>
40 where
41     St: TryStream,
42     C: Default + Extend<St::Ok>,
43 {
44     type Output = Result<C, St::Error>;
45 
poll( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Self::Output>46     fn poll(
47         self: Pin<&mut Self>,
48         cx: &mut Context<'_>,
49     ) -> Poll<Self::Output> {
50         let mut this = self.project();
51         Poll::Ready(Ok(loop {
52             match ready!(this.stream.as_mut().try_poll_next(cx)?) {
53                 Some(x) => this.items.extend(Some(x)),
54                 None => break mem::replace(this.items, Default::default()),
55             }
56         }))
57     }
58 }
59