#iterator #stream #async-stream #future #coroutine #yield #value

nightly no-std stream-future

Implement an async iterator with return value

8 releases (4 breaking)

0.5.0 May 21, 2024
0.4.1 Oct 24, 2023
0.4.0 Mar 21, 2023
0.3.1 Dec 24, 2022
0.1.1 Aug 26, 2022

#1828 in Asynchronous

Download history 6/week @ 2024-07-16 76/week @ 2024-07-23 37/week @ 2024-07-30 10/week @ 2024-08-06 3/week @ 2024-08-13 6/week @ 2024-09-10 33/week @ 2024-09-17 38/week @ 2024-09-24 28/week @ 2024-10-01 21/week @ 2024-10-08 16/week @ 2024-10-15 2/week @ 2024-10-29

52 downloads per month
Used in 2 crates

MIT license

12KB
150 lines

stream-future

crates.io docs.rs

This is a no_std compatible library to author a Future with Stream implemented. You can author simply with await and yield.

A nightly feature coroutines is required.

#![feature(coroutines)]

use stream_future::stream;

#[derive(Debug)]
enum Prog {
    Stage1,
    Stage2,
}

#[stream(Prog)]
async fn foo() -> Result<i32> {
    yield Prog::Stage1;
    // some works...
    yield Prog::Stage2;
    // some other works...
    Ok(0)
}

use tokio_stream::StreamExt;

let bar = foo();
tokio::pin!(bar);
while let Some(prog) = bar.next().await {
    println!("{:?}", prog);
}
let bar = bar.await?;
assert_eq!(bar, 0);
#![feature(coroutines)]

use stream_future::try_stream;

#[derive(Debug)]
enum Prog {
    Stage1,
    Stage2,
}

#[try_stream(Prog)]
async fn foo() -> Result<()> {
    yield Prog::Stage1;
    // some works...
    yield Prog::Stage2;
    // some other works...
    Ok(())
}

let bar = foo();
tokio::pin!(bar);
while let Some(prog) = bar.try_next().await? {
    println!("{:?}", prog);
}

You can specify the yield type in the attribute. Either the yield type or return type could be (). You can simply await other futures, and the macro will handle that.

Compare with async-stream

You can return any value you like! The caller can simply await and get the value without iterate the stream.

This library is 7x faster than async-stream, according to our benchmark.

Dependencies

~275–730KB
~16K SLoC