Skip to content

Commit

Permalink
Explain pinning in README
Browse files Browse the repository at this point in the history
  • Loading branch information
kornelski committed Feb 11, 2020
1 parent 91f6a38 commit ba34e04
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ async fn main() {
}
};

pin_mut!(s); // needed for iteration
// Stream must be pinned before iteration. It can be done with Box::pin,
// but the pin_mut macro is more efficient. See "Pinning" section.
pin_mut!(s);

while let Some(value) = s.next().await {
println!("got {}", value);
Expand Down Expand Up @@ -60,7 +62,7 @@ fn zero_to_three() -> impl Stream<Item = u32> {
#[tokio::main]
async fn main() {
let s = zero_to_three();
pin_mut!(s); // needed for iteration
pin_mut!(s); // Pinning is needed for iteration

while let Some(value) = s.next().await {
println!("got {}", value);
Expand Down Expand Up @@ -99,7 +101,7 @@ fn double<S: Stream<Item = u32>>(input: S)
#[tokio::main]
async fn main() {
let s = double(zero_to_three());
pin_mut!(s); // needed for iteration
pin_mut!(s); // Pinning is needed for iteration

while let Some(value) = s.next().await {
println!("got {}", value);
Expand Down Expand Up @@ -135,6 +137,20 @@ fn bind_and_accept(addr: SocketAddr)
}
```

## Pinning

If you wrap the stream in `Box::pin`, the callers won't need to pin it before iterating it. This is more convenient for the callers, but adds a cost of using dynamic dispatch.

```rust
fn zero_to_three() -> impl Stream<Item = u32> {
Box::pin(stream! {
for i in 0..3 {
yield i;
}
})
}
```

## Implementation

The `stream!` and `try_stream!` macros are implemented using proc macros.
Expand Down

0 comments on commit ba34e04

Please sign in to comment.