Skip to content

add Stream::copied #442

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

Merged
1 commit merged into from
Nov 2, 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
33 changes: 33 additions & 0 deletions src/stream/stream/copied.rs
Original file line number Diff line number Diff line change
@@ -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 Copied<S> {
#[pin]
stream: S,
}
}

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

impl<'a, S, T: 'a> Stream for Copied<S>
where
S: Stream<Item = &'a T>,
T: Copy,
{
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.copied())
}
}
38 changes: 38 additions & 0 deletions src/stream/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ mod all;
mod any;
mod chain;
mod cmp;
mod copied;
mod enumerate;
mod eq;
mod filter;
Expand Down Expand Up @@ -88,6 +89,7 @@ use try_fold::TryFoldFuture;
use try_for_each::TryForEachFuture;

pub use chain::Chain;
pub use copied::Copied;
pub use filter::Filter;
pub use fuse::Fuse;
pub use inspect::Inspect;
Expand Down Expand Up @@ -369,6 +371,42 @@ 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_copied = v.copied();

assert_eq!(v_copied.next().await, Some(1));
assert_eq!(v_copied.next().await, Some(2));
assert_eq!(v_copied.next().await, Some(3));
assert_eq!(v_copied.next().await, None);


#
# }) }
```
"#]
fn copied<'a,T>(self) -> Copied<Self>
where
Self: Sized + Stream<Item = &'a T>,
T : 'a + Copy,
{
Copied::new(self)
}

#[doc = r#"
Creates a stream that gives the current element's count as well as the next value.

Expand Down