Skip to content

Commit e17a670

Browse files
authored
Merge pull request #415 from k-nasa/stream_from_iter
Add stream::from_iter
2 parents a3b7421 + 2f3c867 commit e17a670

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/stream/from_iter.rs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
}

src/stream/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,7 @@
302302
303303
pub use empty::{empty, Empty};
304304
pub use from_fn::{from_fn, FromFn};
305+
pub use from_iter::{from_iter, FromIter};
305306
pub use once::{once, Once};
306307
pub use repeat::{repeat, Repeat};
307308
pub use repeat_with::{repeat_with, RepeatWith};
@@ -313,6 +314,7 @@ pub(crate) mod stream;
313314

314315
mod empty;
315316
mod from_fn;
317+
mod from_iter;
316318
mod once;
317319
mod repeat;
318320
mod repeat_with;

0 commit comments

Comments
 (0)