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> Iter<I> { |
14 | /// Acquires a reference to the underlying iterator that this stream is pulling from. |
15 | pub fn get_ref(&self) -> &I { |
16 | &self.iter |
17 | } |
18 | |
19 | /// Acquires a mutable reference to the underlying iterator that this stream is pulling from. |
20 | pub fn get_mut(&mut self) -> &mut I { |
21 | &mut self.iter |
22 | } |
23 | |
24 | /// Consumes this stream, returning the underlying iterator. |
25 | pub fn into_inner(self) -> I { |
26 | self.iter |
27 | } |
28 | } |
29 | |
30 | impl<I> Unpin for Iter<I> {} |
31 | |
32 | /// Converts an `Iterator` into a `Stream` which is always ready |
33 | /// to yield the next value. |
34 | /// |
35 | /// Iterators in Rust don't express the ability to block, so this adapter |
36 | /// simply always calls `iter.next()` and returns that. |
37 | /// |
38 | /// ``` |
39 | /// # futures::executor::block_on(async { |
40 | /// use futures::stream::{self, StreamExt}; |
41 | /// |
42 | /// let stream = stream::iter(vec![17, 19]); |
43 | /// assert_eq!(vec![17, 19], stream.collect::<Vec<i32>>().await); |
44 | /// # }); |
45 | /// ``` |
46 | pub fn iter<I>(i: I) -> Iter<I::IntoIter> |
47 | where |
48 | I: IntoIterator, |
49 | { |
50 | assert_stream::<I::Item, _>(Iter { iter: i.into_iter() }) |
51 | } |
52 | |
53 | impl<I> Stream for Iter<I> |
54 | where |
55 | I: Iterator, |
56 | { |
57 | type Item = I::Item; |
58 | |
59 | fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<I::Item>> { |
60 | Poll::Ready(self.iter.next()) |
61 | } |
62 | |
63 | fn size_hint(&self) -> (usize, Option<usize>) { |
64 | self.iter.size_hint() |
65 | } |
66 | } |
67 | |