async_std/stream/extend.rs
1use core::pin::Pin;
2use core::future::Future;
3
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 + Send>>
38 where
39 <T as IntoStream>::IntoStream: Send;
40}
41
42/// Extends a collection with the contents of a stream.
43///
44/// Streams produce a series of values asynchronously, and collections can also be thought of as a
45/// series of values. The [`Extend`] trait bridges this gap, allowing you to extend a collection
46/// asynchronously by including the contents of that stream. When extending a collection with an
47/// already existing key, that entry is updated or, in the case of collections that permit multiple
48/// entries with equal keys, that entry is inserted.
49///
50/// [`Extend`]: trait.Extend.html
51///
52/// ## Examples
53///
54/// ```
55/// # async_std::task::block_on(async {
56/// #
57/// use async_std::prelude::*;
58/// use async_std::stream;
59///
60/// let mut v: Vec<usize> = vec![1, 2];
61/// let s = stream::repeat(3usize).take(3);
62/// stream::extend(&mut v, s).await;
63///
64/// assert_eq!(v, vec![1, 2, 3, 3, 3]);
65/// #
66/// # })
67/// ```
68#[cfg(feature = "unstable")]
69#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
70pub async fn extend<'a, C, T, S>(collection: &mut C, stream: S)
71where
72 C: Extend<T>,
73 S: IntoStream<Item = T> + 'a,
74 <S as IntoStream>::IntoStream: Send,
75{
76 Extend::extend(collection, stream).await
77}