Skip to content

Commit de67bf0

Browse files
committed
feat: Add stream by_ref
1 parent 77a0419 commit de67bf0

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/stream/stream/mod.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1404,6 +1404,52 @@ extension_trait! {
14041404
}
14051405
}
14061406

1407+
#[doc = r#"
1408+
Borrows an stream, rather than consuming it.
1409+
1410+
This is useful to allow applying stream adaptors while still retaining ownership of the original stream.
1411+
1412+
# Examples
1413+
1414+
```
1415+
# fn main() { async_std::task::block_on(async {
1416+
#
1417+
use async_std::prelude::*;
1418+
use async_std::stream;
1419+
1420+
let a = vec![1isize, 2, 3];
1421+
1422+
let stream = stream::from_iter(a);
1423+
1424+
let sum: isize = stream.take(5).sum().await;
1425+
1426+
assert_eq!(sum, 6);
1427+
1428+
// if we try to use stream again, it won't work. The following line
1429+
// gives "error: use of moved value: `stream`
1430+
// assert_eq!(stream.next(), None);
1431+
1432+
// let's try that again
1433+
let a = vec![1isize, 2, 3];
1434+
1435+
let mut stream = stream::from_iter(a);
1436+
1437+
// instead, we add in a .by_ref()
1438+
let sum: isize = stream.by_ref().take(2).sum().await;
1439+
1440+
assert_eq!(sum, 3);
1441+
1442+
// now this is just fine:
1443+
assert_eq!(stream.next().await, Some(3));
1444+
assert_eq!(stream.next().await, None);
1445+
#
1446+
# }) }
1447+
```
1448+
"#]
1449+
fn by_ref(&mut self) -> &mut Self {
1450+
self
1451+
}
1452+
14071453
#[doc = r#"
14081454
A stream adaptor similar to [`fold`] that holds internal state and produces a new
14091455
stream.

0 commit comments

Comments
 (0)