futures_util/stream/
iter_ok.rs

1use core::marker;
2
3use futures_core::{Async, Poll, Stream};
4use futures_core::task;
5
6/// A stream which is just a shim over an underlying instance of `Iterator`.
7///
8/// This stream will never block and is always ready.
9#[derive(Debug)]
10#[must_use = "streams do nothing unless polled"]
11pub struct IterOk<I, E> {
12    iter: I,
13    _marker: marker::PhantomData<fn() -> E>,
14}
15
16/// Converts an `Iterator` into a `Stream` which is always ready
17/// to yield the next value.
18///
19/// Iterators in Rust don't express the ability to block, so this adapter
20/// simply always calls `iter.next()` and returns that.
21///
22/// ```rust
23/// # extern crate futures;
24/// # extern crate futures_executor;
25/// use futures::prelude::*;
26/// use futures::stream;
27/// use futures_executor::block_on;
28///
29/// # fn main() {
30/// let mut stream = stream::iter_ok::<_, ()>(vec![17, 19]);
31/// assert_eq!(Ok(vec![17, 19]), block_on(stream.collect()));
32/// # }
33/// ```
34pub fn iter_ok<I, E>(i: I) -> IterOk<I::IntoIter, E>
35    where I: IntoIterator,
36{
37    IterOk {
38        iter: i.into_iter(),
39        _marker: marker::PhantomData,
40    }
41}
42
43impl<I, E> Stream for IterOk<I, E>
44    where I: Iterator,
45{
46    type Item = I::Item;
47    type Error = E;
48
49    fn poll_next(&mut self, _: &mut task::Context) -> Poll<Option<I::Item>, E> {
50        Ok(Async::Ready(self.iter.next()))
51    }
52}