Skip to content

Commit 693a725

Browse files
authored
Merge pull request #538 from k-nasa/stream_by_ref
Add stream by_ref
2 parents 3c6d41c + df92c63 commit 693a725

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/stream/stream/mod.rs

+48
Original file line numberDiff line numberDiff line change
@@ -1446,6 +1446,54 @@ extension_trait! {
14461446
}
14471447
}
14481448

1449+
#[doc = r#"
1450+
Borrows an stream, rather than consuming it.
1451+
1452+
This is useful to allow applying stream adaptors while still retaining ownership of the original stream.
1453+
1454+
# Examples
1455+
1456+
```
1457+
# fn main() { async_std::task::block_on(async {
1458+
#
1459+
use async_std::prelude::*;
1460+
use async_std::stream;
1461+
1462+
let a = vec![1isize, 2, 3];
1463+
1464+
let stream = stream::from_iter(a);
1465+
1466+
let sum: isize = stream.take(5).sum().await;
1467+
1468+
assert_eq!(sum, 6);
1469+
1470+
// if we try to use stream again, it won't work. The following line
1471+
// gives "error: use of moved value: `stream`
1472+
// assert_eq!(stream.next(), None);
1473+
1474+
// let's try that again
1475+
let a = vec![1isize, 2, 3];
1476+
1477+
let mut stream = stream::from_iter(a);
1478+
1479+
// instead, we add in a .by_ref()
1480+
let sum: isize = stream.by_ref().take(2).sum().await;
1481+
1482+
assert_eq!(sum, 3);
1483+
1484+
// now this is just fine:
1485+
assert_eq!(stream.next().await, Some(3));
1486+
assert_eq!(stream.next().await, None);
1487+
#
1488+
# }) }
1489+
```
1490+
"#]
1491+
#[cfg(all(feature = "default", feature = "unstable"))]
1492+
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
1493+
fn by_ref(&mut self) -> &mut Self {
1494+
self
1495+
}
1496+
14491497
#[doc = r#"
14501498
A stream adaptor similar to [`fold`] that holds internal state and produces a new
14511499
stream.

0 commit comments

Comments
 (0)