diff --git a/src/stream/stream/cloned.rs b/src/stream/stream/cloned.rs new file mode 100644 index 0000000..779e49d --- /dev/null +++ b/src/stream/stream/cloned.rs @@ -0,0 +1,33 @@ +use crate::stream::Stream; +use crate::task::{Context, Poll}; +use pin_project_lite::pin_project; +use std::pin::Pin; + +pin_project! { + #[doc(hidden)] + #[allow(missing_debug_implementations)] + pub struct Cloned { + #[pin] + stream: S, + } +} + +impl Cloned { + pub(super) fn new(stream: S) -> Self { + Self { stream } + } +} + +impl<'a, S, T: 'a> Stream for Cloned +where + S: Stream, + T: Clone, +{ + type Item = T; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.project(); + let next = futures_core::ready!(this.stream.poll_next(cx)); + Poll::Ready(next.cloned()) + } +} diff --git a/src/stream/stream/mod.rs b/src/stream/stream/mod.rs index e182c03..9595f80 100644 --- a/src/stream/stream/mod.rs +++ b/src/stream/stream/mod.rs @@ -24,6 +24,7 @@ mod all; mod any; mod chain; +mod cloned; mod cmp; mod copied; mod enumerate; @@ -91,6 +92,7 @@ use try_fold::TryFoldFuture; use try_for_each::TryForEachFuture; pub use chain::Chain; +pub use cloned::Cloned; pub use copied::Copied; pub use filter::Filter; pub use fuse::Fuse; @@ -373,6 +375,40 @@ extension_trait! { Chain::new(self, other) } + #[doc = r#" + Creates an stream which copies all of its elements. + + # Examples + + Basic usage: + + ``` + # fn main() { async_std::task::block_on(async { + # + use async_std::prelude::*; + use std::collections::VecDeque; + + let v: VecDeque<_> = vec![&1, &2, &3].into_iter().collect(); + + let mut v_cloned = v.cloned(); + + assert_eq!(v_cloned.next().await, Some(1)); + assert_eq!(v_cloned.next().await, Some(2)); + assert_eq!(v_cloned.next().await, Some(3)); + assert_eq!(v_cloned.next().await, None); + + # + # }) } + ``` + "#] + fn cloned<'a,T>(self) -> Cloned + where + Self: Sized + Stream, + T : 'a + Clone, + { + Cloned::new(self) + } + #[doc = r#" Creates an stream which copies all of its elements. @@ -395,7 +431,6 @@ extension_trait! { assert_eq!(v_copied.next().await, Some(2)); assert_eq!(v_copied.next().await, Some(3)); assert_eq!(v_copied.next().await, None); - # # }) }