Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions tokio/src/stream/extend.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use crate::stream::{Stream, StreamExt};
use std::{iter::Extend, marker::Unpin};
/// Extends a slice from a Stream
/// # Example
/// `rust,no_run`
/// use tokio::stream;
///
/// let mut b = vec![-2];
/// let stream = stream::iter(vec![0, 2, 4, 6]);
///
/// stream::extend(&mut buff, s).await;
/// assert_eq!(vec![-2, 0, 2, 4, 6], buff);
pub async fn extend<E, S, T>(buff: &mut E, mut b: S)
where
S: Stream<Item = T> + Unpin,
E: Extend<T>,
{
while let Some(item) = b.next().await {
buff.extend(std::iter::once(item))
}
}
2 changes: 2 additions & 0 deletions tokio/src/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ mod collect;
use collect::Collect;
pub use collect::FromStream;

mod extend;
pub use extend::extend;
mod empty;
pub use empty::{empty, Empty};

Expand Down
26 changes: 26 additions & 0 deletions tokio/tests/stream_extend.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use std::collections::HashMap;

use tokio::stream;

#[tokio::test]
async fn vec_extend_stream() {
let s = stream::iter(vec![0, 2, 4, 6]);
let mut buff = vec![-2];
stream::extend(&mut buff, s).await;
assert_eq!(buff, vec![-2, 0, 2, 4, 6]);
}

#[tokio::test]
async fn hash_map_extend_stream() {
let hm: HashMap<String, i32> = vec![("one".to_string(), 1)].into_iter().collect();
let s = stream::iter(hm);

let mut buff: HashMap<String, i32> = vec![("zero".to_string(), 0)].into_iter().collect();
buff.insert("zero".to_string(), 0);
stream::extend(&mut buff, s).await;

let hm_expected: HashMap<_, _> = vec![("zero".to_string(), 0), ("one".to_string(), 1)]
.into_iter()
.collect();
assert_eq!(hm_expected, buff);
}