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