18 releases

new 0.1.17 Dec 6, 2024
0.1.16 Sep 5, 2024
0.1.15 Mar 14, 2024
0.1.14 Apr 26, 2023
0.1.0 Dec 23, 2020

#243 in Asynchronous

Download history 1194314/week @ 2024-08-21 1111258/week @ 2024-08-28 1297272/week @ 2024-09-04 1198283/week @ 2024-09-11 1179115/week @ 2024-09-18 1296779/week @ 2024-09-25 1318372/week @ 2024-10-02 1295627/week @ 2024-10-09 1428907/week @ 2024-10-16 1432541/week @ 2024-10-23 1439910/week @ 2024-10-30 1359913/week @ 2024-11-06 1382130/week @ 2024-11-13 1372909/week @ 2024-11-20 1166301/week @ 2024-11-27 1151406/week @ 2024-12-04

5,325,738 downloads per month
Used in 7,219 crates (1,544 directly)

MIT license

3MB
40K SLoC

tokio-stream

Utilities to work with Stream and tokio.

License

This project is licensed under the MIT license.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Tokio by you, shall be licensed as MIT, without any additional terms or conditions.


lib.rs:

Stream utilities for Tokio.

A Stream is an asynchronous sequence of values. It can be thought of as an asynchronous version of the standard library's Iterator trait.

This crate provides helpers to work with them. For examples of usage and a more in-depth description of streams you can also refer to the streams tutorial on the tokio website.

Iterating over a Stream

Due to similarities with the standard library's Iterator trait, some new users may assume that they can use for in syntax to iterate over a Stream, but this is unfortunately not possible. Instead, you can use a while let loop as follows:

use tokio_stream::{self as stream, StreamExt};

#[tokio::main]
async fn main() {
    let mut stream = stream::iter(vec![0, 1, 2]);

    while let Some(value) = stream.next().await {
        println!("Got {}", value);
    }
}

Returning a Stream from a function

A common way to stream values from a function is to pass in the sender half of a channel and use the receiver as the stream. This requires awaiting both futures to ensure progress is made. Another alternative is the async-stream crate, which contains macros that provide a yield keyword and allow you to return an impl Stream.

Conversion to and from AsyncRead/AsyncWrite

It is often desirable to convert a Stream into an AsyncRead, especially when dealing with plaintext formats streamed over the network. The opposite conversion from an AsyncRead into a Stream is also another commonly required feature. To enable these conversions, tokio-util provides the StreamReader and ReaderStream types when the io feature is enabled.

Dependencies

~0–7.5MB
~51K SLoC