async_std/stream/extend.rs
1use std::pin::Pin;
2
3use crate::prelude::*;
4use crate::stream::IntoStream;
5
6/// Extends a collection with the contents of a stream.
7///
8/// Streams produce a series of values asynchronously, and collections can also be thought of as a
9/// series of values. The `Extend` trait bridges this gap, allowing you to extend a collection
10/// asynchronously by including the contents of that stream. When extending a collection with an
11/// already existing key, that entry is updated or, in the case of collections that permit multiple
12/// entries with equal keys, that entry is inserted.
13///
14/// ## Examples
15///
16/// ```
17/// # async_std::task::block_on(async {
18/// #
19/// use async_std::prelude::*;
20/// use async_std::stream;
21///
22/// let mut v: Vec<usize> = vec![1, 2];
23/// let s = stream::repeat(3usize).take(3);
24/// stream::Extend::extend(&mut v, s).await;
25///
26/// assert_eq!(v, vec![1, 2, 3, 3, 3]);
27/// #
28/// # })
29/// ```
30#[cfg(feature = "unstable")]
31#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
32pub trait Extend<A> {
33 /// Extends a collection with the contents of a stream.
34 fn extend<'a, T: IntoStream<Item = A> + 'a>(
35 &'a mut self,
36 stream: T,
37 ) -> Pin<Box<dyn Future<Output = ()> + 'a>>;
38}
39
40/// Extends a collection with the contents of a stream.
41///
42/// Streams produce a series of values asynchronously, and collections can also be thought of as a
43/// series of values. The [`Extend`] trait bridges this gap, allowing you to extend a collection
44/// asynchronously by including the contents of that stream. When extending a collection with an
45/// already existing key, that entry is updated or, in the case of collections that permit multiple
46/// entries with equal keys, that entry is inserted.
47///
48/// [`Extend`]: trait.Extend.html
49///
50/// ## Examples
51///
52/// ```
53/// # async_std::task::block_on(async {
54/// #
55/// use async_std::prelude::*;
56/// use async_std::stream;
57///
58/// let mut v: Vec<usize> = vec![1, 2];
59/// let s = stream::repeat(3usize).take(3);
60/// stream::extend(&mut v, s).await;
61///
62/// assert_eq!(v, vec![1, 2, 3, 3, 3]);
63/// #
64/// # })
65/// ```
66#[cfg(feature = "unstable")]
67#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
68pub async fn extend<'a, C, T, S>(collection: &mut C, stream: S)
69where
70 C: Extend<T>,
71 S: IntoStream<Item = T> + 'a,
72{
73 Extend::extend(collection, stream).await
74}