add Stream::copied (#442)

poc-serde-support
Zhang Guyu 5 years ago committed by Stjepan Glavina
parent 4c63392a85
commit 5fb9d3e980

@ -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())
}
}

@ -25,6 +25,7 @@ mod all;
mod any; mod any;
mod chain; mod chain;
mod cmp; mod cmp;
mod copied;
mod enumerate; mod enumerate;
mod eq; mod eq;
mod filter; mod filter;
@ -88,6 +89,7 @@ use try_fold::TryFoldFuture;
use try_for_each::TryForEachFuture; use try_for_each::TryForEachFuture;
pub use chain::Chain; pub use chain::Chain;
pub use copied::Copied;
pub use filter::Filter; pub use filter::Filter;
pub use fuse::Fuse; pub use fuse::Fuse;
pub use inspect::Inspect; pub use inspect::Inspect;
@ -369,6 +371,42 @@ extension_trait! {
Chain::new(self, other) 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#" #[doc = r#"
Creates a stream that gives the current element's count as well as the next value. Creates a stream that gives the current element's count as well as the next value.

Loading…
Cancel
Save