Skip to content

Commit 2be2c2d

Browse files
committed
Add stream::collect implementation
1 parent c0375ae commit 2be2c2d

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/stream.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,17 @@ pub async fn next<St>(stream: &mut St) -> Option<St::Item>
1111
await!(future_next)
1212
}
1313

14+
pub async fn collect<St, C>(mut stream: St) -> C
15+
where St: Stream + Unpin,
16+
C: Default + Extend<St::Item>
17+
{
18+
let mut collection = C::default();
19+
while let Some(item) = await!(next(&mut stream)) {
20+
collection.extend(Some(item));
21+
}
22+
collection
23+
}
24+
1425
#[cfg(test)]
1526
mod tests {
1627
use futures::{stream, executor};
@@ -26,4 +37,11 @@ mod tests {
2637
assert_eq!(executor::block_on(next(&mut stream)), None);
2738
}
2839

40+
#[test]
41+
fn test_collect() {
42+
let stream = stream::iter(1..=5);
43+
44+
let collection : Vec<i32> = executor::block_on(collect(stream));
45+
assert_eq!(collection, vec![1, 2, 3, 4, 5]);
46+
}
2947
}

0 commit comments

Comments
 (0)