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
use futures_core::future::Future;
use futures_core::stream::TryStream;
use futures_core::task::{self, Poll};
use std::marker::Unpin;
use std::mem::{self, PinMut};
use std::prelude::v1::*;
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct TryCollect<S, C> where S: TryStream {
stream: S,
items: C,
}
pub fn new<S, C>(s: S) -> TryCollect<S, C>
where S: TryStream, C: Default
{
TryCollect {
stream: s,
items: Default::default(),
}
}
impl<S: TryStream, C: Default> TryCollect<S, C> {
fn finish(mut self: PinMut<Self>) -> C {
mem::replace(self.items(), Default::default())
}
unsafe_pinned!(stream: S);
unsafe_unpinned!(items: C);
}
impl<S: Unpin + TryStream, C> Unpin for TryCollect<S, C> {}
impl<S, C> Future for TryCollect<S, C>
where S: TryStream, C: Default + Extend<S::Ok>
{
type Output = Result<C, S::Error>;
fn poll(
mut self: PinMut<Self>,
cx: &mut task::Context
) -> Poll<Self::Output> {
loop {
match ready!(self.stream().try_poll_next(cx)) {
Some(Ok(x)) => self.items().extend(Some(x)),
Some(Err(e)) => return Poll::Ready(Err(e)),
None => return Poll::Ready(Ok(self.finish())),
}
}
}
}