Skip to content

Commit 8a0e294

Browse files
authored
Merge pull request #446 from yjhmelody/stream-cloned
Add Stream cloned
2 parents 2cb887e + 5179f30 commit 8a0e294

File tree

2 files changed

+68
-2
lines changed

2 files changed

+68
-2
lines changed

src/stream/stream/cloned.rs

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
#[derive(Debug)]
8+
pub struct Cloned<S> {
9+
#[pin]
10+
stream: S,
11+
}
12+
}
13+
14+
impl<S> Cloned<S> {
15+
pub(super) fn new(stream: S) -> Self {
16+
Self { stream }
17+
}
18+
}
19+
20+
impl<'a, S, T: 'a> Stream for Cloned<S>
21+
where
22+
S: Stream<Item = &'a T>,
23+
T: Clone,
24+
{
25+
type Item = T;
26+
27+
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
28+
let this = self.project();
29+
let next = futures_core::ready!(this.stream.poll_next(cx));
30+
Poll::Ready(next.cloned())
31+
}
32+
}

src/stream/stream/mod.rs

+36-2
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;
@@ -379,6 +381,40 @@ extension_trait! {
379381
Chain::new(self, other)
380382
}
381383

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

383419
#[doc = r#"
384420
Creates an stream which copies all of its elements.
@@ -394,8 +430,6 @@ extension_trait! {
394430
use async_std::stream;
395431
396432
let s = stream::from_iter(vec![&1, &2, &3]);
397-
let second = stream::from_iter(vec![2, 3]);
398-
399433
let mut s_copied = s.copied();
400434
401435
assert_eq!(s_copied.next().await, Some(1));

0 commit comments

Comments
 (0)