Skip to content

Commit 40c4e1a

Browse files
committed
feat: Add stream::from_iter
1 parent da795de commit 40c4e1a

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/stream/from_iter.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
#[derive(Debug)]
10+
pub struct FromIter<I> {
11+
iter: I,
12+
}
13+
}
14+
15+
/// # Examples
16+
///```
17+
/// # async_std::task::block_on(async {
18+
/// #
19+
/// use async_std::prelude::*;
20+
/// use async_std::stream;
21+
///
22+
/// let mut s = stream::from_iter(vec![0, 1, 2, 3]);
23+
///
24+
/// assert_eq!(s.next().await, Some(0));
25+
/// assert_eq!(s.next().await, Some(1));
26+
/// assert_eq!(s.next().await, Some(2));
27+
/// assert_eq!(s.next().await, Some(3));
28+
/// assert_eq!(s.next().await, None);
29+
/// #
30+
/// # })
31+
///````
32+
pub fn from_iter<I: IntoIterator>(iter: I) -> FromIter<<I as std::iter::IntoIterator>::IntoIter> {
33+
FromIter {
34+
iter: iter.into_iter(),
35+
}
36+
}
37+
38+
impl<I: Iterator> Stream for FromIter<I> {
39+
type Item = I::Item;
40+
41+
fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
42+
Poll::Ready(self.iter.next())
43+
}
44+
}

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)