Skip to content

Commit

Permalink
add Stream::copied (#442)
Browse files Browse the repository at this point in the history
  • Loading branch information
recursion128 authored and Stjepan Glavina committed Nov 2, 2019
1 parent 4c63392 commit 5fb9d3e
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
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

0 comments on commit 5fb9d3e

Please sign in to comment.