1 | use super::assert_stream; |
2 | use core::pin::Pin; |
3 | use futures_core::stream::Stream; |
4 | use futures_core::task::{Context, Poll}; |
5 | |
6 | /// Stream for the [`iter`] function. |
7 | #[derive (Debug, Clone)] |
8 | #[must_use = "streams do nothing unless polled" ] |
9 | pub struct Iter<I> { |
10 | iter: I, |
11 | } |
12 | |
13 | impl<I> Unpin for Iter<I> {} |
14 | |
15 | /// Converts an `Iterator` into a `Stream` which is always ready |
16 | /// to yield the next value. |
17 | /// |
18 | /// Iterators in Rust don't express the ability to block, so this adapter |
19 | /// simply always calls `iter.next()` and returns that. |
20 | /// |
21 | /// ``` |
22 | /// # futures::executor::block_on(async { |
23 | /// use futures::stream::{self, StreamExt}; |
24 | /// |
25 | /// let stream = stream::iter(vec![17, 19]); |
26 | /// assert_eq!(vec![17, 19], stream.collect::<Vec<i32>>().await); |
27 | /// # }); |
28 | /// ``` |
29 | pub fn iter<I>(i: I) -> Iter<I::IntoIter> |
30 | where |
31 | I: IntoIterator, |
32 | { |
33 | assert_stream::<I::Item, _>(Iter { iter: i.into_iter() }) |
34 | } |
35 | |
36 | impl<I> Stream for Iter<I> |
37 | where |
38 | I: Iterator, |
39 | { |
40 | type Item = I::Item; |
41 | |
42 | fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<I::Item>> { |
43 | Poll::Ready(self.iter.next()) |
44 | } |
45 | |
46 | fn size_hint(&self) -> (usize, Option<usize>) { |
47 | self.iter.size_hint() |
48 | } |
49 | } |
50 | |