|
| 1 | +use std::pin::Pin; |
| 2 | + |
| 3 | +use pin_project_lite::pin_project; |
| 4 | + |
| 5 | +use crate::stream::Stream; |
| 6 | +use crate::task::{Context, Poll}; |
| 7 | + |
| 8 | +pin_project! { |
| 9 | + /// A stream that created from iterator |
| 10 | + /// |
| 11 | + /// This stream is created by the [`from_iter`] function. |
| 12 | + /// See it documentation for more. |
| 13 | + /// |
| 14 | + /// [`from_iter`]: fn.from_iter.html |
| 15 | + #[derive(Debug)] |
| 16 | + pub struct FromIter<I> { |
| 17 | + iter: I, |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +/// # Examples |
| 22 | +///``` |
| 23 | +/// # async_std::task::block_on(async { |
| 24 | +/// # |
| 25 | +/// use async_std::prelude::*; |
| 26 | +/// use async_std::stream; |
| 27 | +/// |
| 28 | +/// let mut s = stream::from_iter(vec![0, 1, 2, 3]); |
| 29 | +/// |
| 30 | +/// assert_eq!(s.next().await, Some(0)); |
| 31 | +/// assert_eq!(s.next().await, Some(1)); |
| 32 | +/// assert_eq!(s.next().await, Some(2)); |
| 33 | +/// assert_eq!(s.next().await, Some(3)); |
| 34 | +/// assert_eq!(s.next().await, None); |
| 35 | +/// # |
| 36 | +/// # }) |
| 37 | +///```` |
| 38 | +pub fn from_iter<I: IntoIterator>(iter: I) -> FromIter<<I as std::iter::IntoIterator>::IntoIter> { |
| 39 | + FromIter { |
| 40 | + iter: iter.into_iter(), |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +impl<I: Iterator> Stream for FromIter<I> { |
| 45 | + type Item = I::Item; |
| 46 | + |
| 47 | + fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 48 | + Poll::Ready(self.iter.next()) |
| 49 | + } |
| 50 | +} |
0 commit comments