Skip to content

Commit 5fb9d3e

Browse files
recursion128Stjepan Glavina
authored and
Stjepan Glavina
committed
add Stream::copied (#442)
1 parent 4c63392 commit 5fb9d3e

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

src/stream/stream/copied.rs

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
use crate::stream::Stream;
2+
use crate::task::{Context, Poll};
3+
use pin_project_lite::pin_project;
4+
use std::pin::Pin;
5+
6+
pin_project! {
7+
#[doc(hidden)]
8+
#[allow(missing_debug_implementations)]
9+
pub struct Copied<S> {
10+
#[pin]
11+
stream: S,
12+
}
13+
}
14+
15+
impl<S> Copied<S> {
16+
pub(super) fn new(stream: S) -> Self {
17+
Copied { stream }
18+
}
19+
}
20+
21+
impl<'a, S, T: 'a> Stream for Copied<S>
22+
where
23+
S: Stream<Item = &'a T>,
24+
T: Copy,
25+
{
26+
type Item = T;
27+
28+
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
29+
let this = self.project();
30+
let next = futures_core::ready!(this.stream.poll_next(cx));
31+
Poll::Ready(next.copied())
32+
}
33+
}

src/stream/stream/mod.rs

+38
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ mod all;
2525
mod any;
2626
mod chain;
2727
mod cmp;
28+
mod copied;
2829
mod enumerate;
2930
mod eq;
3031
mod filter;
@@ -88,6 +89,7 @@ use try_fold::TryFoldFuture;
8889
use try_for_each::TryForEachFuture;
8990

9091
pub use chain::Chain;
92+
pub use copied::Copied;
9193
pub use filter::Filter;
9294
pub use fuse::Fuse;
9395
pub use inspect::Inspect;
@@ -369,6 +371,42 @@ extension_trait! {
369371
Chain::new(self, other)
370372
}
371373

374+
375+
#[doc = r#"
376+
Creates an stream which copies all of its elements.
377+
378+
# Examples
379+
380+
Basic usage:
381+
382+
```
383+
# fn main() { async_std::task::block_on(async {
384+
#
385+
use async_std::prelude::*;
386+
use std::collections::VecDeque;
387+
388+
let v: VecDeque<_> = vec![&1, &2, &3].into_iter().collect();
389+
390+
let mut v_copied = v.copied();
391+
392+
assert_eq!(v_copied.next().await, Some(1));
393+
assert_eq!(v_copied.next().await, Some(2));
394+
assert_eq!(v_copied.next().await, Some(3));
395+
assert_eq!(v_copied.next().await, None);
396+
397+
398+
#
399+
# }) }
400+
```
401+
"#]
402+
fn copied<'a,T>(self) -> Copied<Self>
403+
where
404+
Self: Sized + Stream<Item = &'a T>,
405+
T : 'a + Copy,
406+
{
407+
Copied::new(self)
408+
}
409+
372410
#[doc = r#"
373411
Creates a stream that gives the current element's count as well as the next value.
374412

0 commit comments

Comments
 (0)