|
| 1 | +use std::pin::Pin; |
| 2 | + |
| 3 | +use crate::future::Future; |
| 4 | +use crate::stream::{IntoStream, Stream}; |
| 5 | + |
| 6 | +/// Extend 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 | +/// # fn main() { async_std::task::block_on(async { |
| 18 | +/// # |
| 19 | +/// use async_std::prelude::*; |
| 20 | +/// use async_std::stream::{self, Extend}; |
| 21 | +/// |
| 22 | +/// let mut v: Vec<usize> = vec![1, 2]; |
| 23 | +/// let s = stream::repeat(3usize).take(3); |
| 24 | +/// v.extend_with_stream(s).await; |
| 25 | +/// |
| 26 | +/// assert_eq!(v, vec![1, 2, 3, 3, 3]); |
| 27 | +/// # |
| 28 | +/// # }) } |
| 29 | +/// ``` |
| 30 | +#[cfg_attr(feature = "docs", doc(cfg(unstable)))] |
| 31 | +pub trait Extend<A> { |
| 32 | + /// Extends a collection with the contents of a stream. |
| 33 | + fn extend_with_stream<'a, T: IntoStream<Item = A> + 'a>( |
| 34 | + &'a mut self, |
| 35 | + stream: T, |
| 36 | + ) -> Pin<Box<dyn Future<Output = ()> + 'a>>; |
| 37 | +} |
| 38 | + |
| 39 | +impl Extend<()> for () { |
| 40 | + fn extend_with_stream<'a, T: IntoStream<Item = ()> + 'a>( |
| 41 | + &'a mut self, |
| 42 | + stream: T, |
| 43 | + ) -> Pin<Box<dyn Future<Output = ()> + 'a>> { |
| 44 | + let stream = stream.into_stream(); |
| 45 | + Box::pin(async move { |
| 46 | + pin_utils::pin_mut!(stream); |
| 47 | + while let Some(_) = stream.next().await {} |
| 48 | + }) |
| 49 | + } |
| 50 | +} |
0 commit comments