| 1 | use core::pin::Pin; |
| 2 | |
| 3 | use pin_project_lite::pin_project; |
| 4 | |
| 5 | use crate::stream::Stream; |
| 6 | #[cfg (feature = "unstable" )] |
| 7 | use crate::stream::double_ended_stream::DoubleEndedStream; |
| 8 | use crate::task::{Context, Poll}; |
| 9 | |
| 10 | pin_project! { |
| 11 | /// A stream that was created from iterator. |
| 12 | /// |
| 13 | /// This stream is created by the [`from_iter`] function. |
| 14 | /// See it documentation for more. |
| 15 | /// |
| 16 | /// [`from_iter`]: fn.from_iter.html |
| 17 | #[derive (Clone, Debug)] |
| 18 | pub struct FromIter<I> { |
| 19 | iter: I, |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | /// Converts an iterator into a stream. |
| 24 | /// |
| 25 | /// # Examples |
| 26 | /// |
| 27 | /// ``` |
| 28 | /// # async_std::task::block_on(async { |
| 29 | /// # |
| 30 | /// use async_std::prelude::*; |
| 31 | /// use async_std::stream; |
| 32 | /// |
| 33 | /// let mut s = stream::from_iter(vec![0, 1, 2, 3]); |
| 34 | /// |
| 35 | /// assert_eq!(s.next().await, Some(0)); |
| 36 | /// assert_eq!(s.next().await, Some(1)); |
| 37 | /// assert_eq!(s.next().await, Some(2)); |
| 38 | /// assert_eq!(s.next().await, Some(3)); |
| 39 | /// assert_eq!(s.next().await, None); |
| 40 | /// # |
| 41 | /// # }) |
| 42 | /// ``` |
| 43 | pub fn from_iter<I: IntoIterator>(iter: I) -> FromIter<I::IntoIter> { |
| 44 | FromIter { |
| 45 | iter: iter.into_iter(), |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | impl<I: Iterator> Stream for FromIter<I> { |
| 50 | type Item = I::Item; |
| 51 | |
| 52 | fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 53 | Poll::Ready(self.iter.next()) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | #[cfg (feature = "unstable" )] |
| 58 | impl<T: DoubleEndedIterator> DoubleEndedStream for FromIter<T> { |
| 59 | fn poll_next_back(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<T::Item>> { |
| 60 | Poll::Ready(self.iter.next_back()) |
| 61 | } |
| 62 | } |
| 63 | |