futures_util/stream/
collect.rs

1use std::prelude::v1::*;
2
3use std::mem;
4
5use futures_core::{Future, Poll, Async, Stream};
6use futures_core::task;
7
8/// A future which collects all of the values of a stream into a vector.
9///
10/// This future is created by the `Stream::collect` method.
11#[derive(Debug)]
12#[must_use = "streams do nothing unless polled"]
13pub struct Collect<S, C> where S: Stream {
14    stream: S,
15    items: C,
16}
17
18pub fn new<S, C>(s: S) -> Collect<S, C>
19    where S: Stream, C: Default
20{
21    Collect {
22        stream: s,
23        items: Default::default(),
24    }
25}
26
27impl<S: Stream, C: Default> Collect<S, C> {
28    fn finish(&mut self) -> C {
29        mem::replace(&mut self.items, Default::default())
30    }
31}
32
33impl<S, C> Future for Collect<S, C>
34    where S: Stream, C: Default + Extend<S:: Item>
35{
36    type Item = C;
37    type Error = S::Error;
38
39    fn poll(&mut self, cx: &mut task::Context) -> Poll<C, S::Error> {
40        loop {
41            match self.stream.poll_next(cx) {
42                Ok(Async::Ready(Some(e))) => self.items.extend(Some(e)),
43                Ok(Async::Ready(None)) => return Ok(Async::Ready(self.finish())),
44                Ok(Async::Pending) => return Ok(Async::Pending),
45                Err(e) => {
46                    self.finish();
47                    return Err(e)
48                }
49            }
50        }
51    }
52}