Skip to content

Commit 4942dc7

Browse files
committed
Add Stream cloned
1 parent fa91d7f commit 4942dc7

File tree

2 files changed

+69
-1
lines changed

2 files changed

+69
-1
lines changed

src/stream/stream/cloned.rs

Lines changed: 33 additions & 0 deletions
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 Cloned<S> {
10+
#[pin]
11+
stream: S,
12+
}
13+
}
14+
15+
impl<S> Cloned<S> {
16+
pub(super) fn new(stream: S) -> Self {
17+
Self { stream }
18+
}
19+
}
20+
21+
impl<'a, S, T: 'a> Stream for Cloned<S>
22+
where
23+
S: Stream<Item = &'a T>,
24+
T: Clone,
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.cloned())
32+
}
33+
}

src/stream/stream/mod.rs

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
mod all;
2525
mod any;
2626
mod chain;
27+
mod cloned;
2728
mod cmp;
2829
mod copied;
2930
mod enumerate;
@@ -91,6 +92,7 @@ use try_fold::TryFoldFuture;
9192
use try_for_each::TryForEachFuture;
9293

9394
pub use chain::Chain;
95+
pub use cloned::Cloned;
9496
pub use copied::Copied;
9597
pub use filter::Filter;
9698
pub use fuse::Fuse;
@@ -373,6 +375,40 @@ extension_trait! {
373375
Chain::new(self, other)
374376
}
375377

378+
#[doc = r#"
379+
Creates an stream which copies all of its elements.
380+
381+
# Examples
382+
383+
Basic usage:
384+
385+
```
386+
# fn main() { async_std::task::block_on(async {
387+
#
388+
use async_std::prelude::*;
389+
use std::collections::VecDeque;
390+
391+
let v: VecDeque<_> = vec![&1, &2, &3].into_iter().collect();
392+
393+
let mut v_cloned = v.cloned();
394+
395+
assert_eq!(v_cloned.next().await, Some(1));
396+
assert_eq!(v_cloned.next().await, Some(2));
397+
assert_eq!(v_cloned.next().await, Some(3));
398+
assert_eq!(v_cloned.next().await, None);
399+
400+
#
401+
# }) }
402+
```
403+
"#]
404+
fn cloned<'a,T>(self) -> Cloned<Self>
405+
where
406+
Self: Sized + Stream<Item = &'a T>,
407+
T : 'a + Clone,
408+
{
409+
Cloned::new(self)
410+
}
411+
376412

377413
#[doc = r#"
378414
Creates an stream which copies all of its elements.
@@ -395,7 +431,6 @@ extension_trait! {
395431
assert_eq!(v_copied.next().await, Some(2));
396432
assert_eq!(v_copied.next().await, Some(3));
397433
assert_eq!(v_copied.next().await, None);
398-
399434
400435
#
401436
# }) }

0 commit comments

Comments
 (0)