#async-stream #stream #future #async #macro

nightly no-std futures-async-stream

Async stream for Rust and the futures crate

26 releases

0.2.12 Aug 23, 2024
0.2.11 Apr 27, 2024
0.2.10 Jan 12, 2024
0.2.9 Oct 21, 2023
0.1.0-alpha.1 Jul 31, 2019

#654 in Asynchronous

Download history 2691/week @ 2024-07-18 2562/week @ 2024-07-25 2629/week @ 2024-08-01 2409/week @ 2024-08-08 2622/week @ 2024-08-15 1848/week @ 2024-08-22 2103/week @ 2024-08-29 2003/week @ 2024-09-05 1671/week @ 2024-09-12 2469/week @ 2024-09-19 1615/week @ 2024-09-26 1025/week @ 2024-10-03 2526/week @ 2024-10-10 2256/week @ 2024-10-17 2396/week @ 2024-10-24 2167/week @ 2024-10-31

9,734 downloads per month
Used in 10 crates (9 directly)

Apache-2.0 OR MIT

38KB
356 lines

futures-async-stream

crates.io docs.rs license github actions

Async stream for Rust and the futures crate.

This crate provides useful features for streams, using async_await and unstable coroutines.

Usage

Add this to your Cargo.toml:

[dependencies]
futures-async-stream = "0.2"
futures = "0.3"

Compiler support: requires rustc nightly-2024-04-25+

#[for_await]

Processes streams using a for loop.

This is a reimplement of futures-await's #[async] for loops for futures 0.3 and is an experimental implementation of the idea listed as the next step of async/await.

#![feature(proc_macro_hygiene, stmt_expr_attributes)]

use futures::stream::Stream;
use futures_async_stream::for_await;

async fn collect(stream: impl Stream<Item = i32>) -> Vec<i32> {
    let mut vec = vec![];
    #[for_await]
    for value in stream {
        vec.push(value);
    }
    vec
}

value has the Item type of the stream passed in. Note that async for loops can only be used inside of async functions, closures, blocks, #[stream] functions and stream_block! macros.

#[stream]

Creates streams via coroutines.

This is a reimplement of futures-await's #[stream] for futures 0.3 and is an experimental implementation of the idea listed as the next step of async/await.

#![feature(coroutines)]

use futures::stream::Stream;
use futures_async_stream::stream;

// Returns a stream of i32
#[stream(item = i32)]
async fn foo(stream: impl Stream<Item = String>) {
    // `for_await` is built into `stream`. If you use `for_await` only in `stream`, there is no need to import `for_await`.
    #[for_await]
    for x in stream {
        yield x.parse().unwrap();
    }
}

To early exit from a #[stream] function or block, use return.

#[stream] on async fn must have an item type specified via item = some::Path and the values output from the stream must be yielded via the yield expression.

#[stream] can also be used on async blocks:

#![feature(coroutines, proc_macro_hygiene, stmt_expr_attributes)]

use futures::stream::Stream;
use futures_async_stream::stream;

fn foo() -> impl Stream<Item = i32> {
    #[stream]
    async move {
        for i in 0..10 {
            yield i;
        }
    }
}

Note that #[stream] on async block does not require the item argument, but it may require additional type annotations.

Using async stream functions in traits

You can use async stream functions in traits by passing boxed or boxed_local as an argument.

#![feature(coroutines)]

use futures_async_stream::stream;

trait Foo {
    #[stream(boxed, item = u32)]
    async fn method(&mut self);
}

struct Bar(u32);

impl Foo for Bar {
    #[stream(boxed, item = u32)]
    async fn method(&mut self) {
        while self.0 < u32::MAX {
            self.0 += 1;
            yield self.0;
        }
    }
}

A async stream function that received a boxed argument is converted to a function that returns Pin<Box<dyn Stream<Item = item> + Send + 'lifetime>>. If you passed boxed_local instead of boxed, async stream function returns a non-thread-safe stream (Pin<Box<dyn Stream<Item = item> + 'lifetime>>).

#![feature(coroutines)]

use std::pin::Pin;

use futures::stream::Stream;
use futures_async_stream::stream;

// The trait itself can be defined without unstable features.
trait Foo {
    fn method(&mut self) -> Pin<Box<dyn Stream<Item = u32> + Send + '_>>;
}

struct Bar(u32);

impl Foo for Bar {
    #[stream(boxed, item = u32)]
    async fn method(&mut self) {
        while self.0 < u32::MAX {
            self.0 += 1;
            yield self.0;
        }
    }
}

#[try_stream]

? operator can be used with the #[try_stream]. The Item of the returned stream is Result with Ok being the value yielded and Err the error type returned by ? operator or return Err(...).

#![feature(coroutines)]

use futures::stream::Stream;
use futures_async_stream::try_stream;

#[try_stream(ok = i32, error = Box<dyn std::error::Error>)]
async fn foo(stream: impl Stream<Item = String>) {
    #[for_await]
    for x in stream {
        yield x.parse()?;
    }
}

#[try_stream] can be used wherever #[stream] can be used.

To early exit from a #[try_stream] function or block, use return Ok(()).

How to write the equivalent code without this API?

#[for_await]

You can write this by combining while let loop, .await, pin! macro, and StreamExt::next() method:

use std::pin::pin;

use futures::stream::{Stream, StreamExt};

async fn collect(stream: impl Stream<Item = i32>) -> Vec<i32> {
    let mut vec = vec![];
    let mut stream = pin!(stream);
    while let Some(value) = stream.next().await {
        vec.push(value);
    }
    vec
}

#[stream]

You can write this by manually implementing the combinator:

use std::{
    pin::Pin,
    task::{ready, Context, Poll},
};

use futures::stream::Stream;
use pin_project::pin_project;

fn foo<S>(stream: S) -> impl Stream<Item = i32>
where
    S: Stream<Item = String>,
{
    Foo { stream }
}

#[pin_project]
struct Foo<S> {
    #[pin]
    stream: S,
}

impl<S> Stream for Foo<S>
where
    S: Stream<Item = String>,
{
    type Item = i32;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        if let Some(x) = ready!(self.project().stream.poll_next(cx)) {
            Poll::Ready(Some(x.parse().unwrap()))
        } else {
            Poll::Ready(None)
        }
    }
}

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~310–780KB
~17K SLoC