Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Stream cloned #446

Merged
merged 6 commits into from
Nov 7, 2019
Merged
Show file tree
Hide file tree
Changes from all 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
32 changes: 32 additions & 0 deletions src/stream/stream/cloned.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use crate::stream::Stream;
use crate::task::{Context, Poll};
use pin_project_lite::pin_project;
use std::pin::Pin;

pin_project! {
#[derive(Debug)]
pub struct Cloned<S> {
#[pin]
stream: S,
}
}

impl<S> Cloned<S> {
pub(super) fn new(stream: S) -> Self {
Self { stream }
}
}

impl<'a, S, T: 'a> Stream for Cloned<S>
where
S: Stream<Item = &'a T>,
T: Clone,
{
type Item = T;

fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
let next = futures_core::ready!(this.stream.poll_next(cx));
Poll::Ready(next.cloned())
}
}
38 changes: 36 additions & 2 deletions src/stream/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
mod all;
mod any;
mod chain;
mod cloned;
mod cmp;
mod copied;
mod enumerate;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -372,6 +374,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 async_std::stream;

let v = stream::from_iter(vec![&1, &2, &3]);

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<Self>
where
Self: Sized + Stream<Item = &'a T>,
T : 'a + Clone,
{
Cloned::new(self)
}


#[doc = r#"
Creates an stream which copies all of its elements.
Expand All @@ -387,8 +423,6 @@ extension_trait! {
use async_std::stream;

let s = stream::from_iter(vec![&1, &2, &3]);
let second = stream::from_iter(vec![2, 3]);

let mut s_copied = s.copied();

assert_eq!(s_copied.next().await, Some(1));
Expand Down