Skip to content

Commit d1b29ac

Browse files
committed
Add stream::map implementation
1 parent 1c5b4cc commit d1b29ac

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/stream.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,22 @@ pub async fn collect<St, C>(stream: St) -> C
2424
collection
2525
}
2626

27+
pub fn map<St, U, F>(stream: St, f: F) -> impl Stream<Item = U>
28+
where F: FnMut(St::Item) -> U,
29+
St: Stream + Unpin,
30+
{
31+
futures::stream::unfold((stream, f), move |(mut stream, mut f)| {
32+
async {
33+
if let Some(item) = await!(next(&mut stream)) {
34+
let mapped = f(item);
35+
Some((mapped, (stream, f)))
36+
} else {
37+
None
38+
}
39+
}
40+
})
41+
}
42+
2743
#[cfg(test)]
2844
mod tests {
2945
use futures::{stream, executor};
@@ -46,4 +62,12 @@ mod tests {
4662
let collection : Vec<i32> = executor::block_on(collect(stream));
4763
assert_eq!(collection, vec![1, 2, 3, 4, 5]);
4864
}
65+
66+
#[test]
67+
fn test_map() {
68+
let stream = stream::iter(1..=3);
69+
let stream = map(stream, |x| x * 2);
70+
71+
assert_eq!(vec![2, 4, 6], executor::block_on(collect::<_, Vec<_>>(stream)));
72+
}
4973
}

0 commit comments

Comments
 (0)