Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

async_for! #2759

Open
khoover opened this issue Jul 7, 2023 · 1 comment
Open

async_for! #2759

khoover opened this issue Jul 7, 2023 · 1 comment
Labels
A-stream Area: futures::stream

Comments

@khoover
Copy link

khoover commented Jul 7, 2023

Searching through past issues didn't turn anything up, but it seems like a killer feature for streams would be, roughly, async for x in stream { ... }. While this doesn't work currently, it seems relatively straightforward to write a macro_rule! for it?

pub fn assert_stream<S: Stream>(s: S) -> S { s }

macro_rules! async_for {
    ($var:ident in $stream:expr, $blk:block) => {
        {
            let mut stream = ::core::pin::pin!(assert_stream($stream));
            while let Some($var) = ::futures::stream::StreamExt::next(&mut stream).await {
                $blk
            }
        }
    }
}

A simple test like

async fn test_async_for<S: Stream<Item = u8>>(mut stream: S) {
    let mut stream = core::pin::pin!(stream); // Commenting this line out makes building fail.
    async_for!(x in stream.by_ref(), {
        println!("{}", x);
        break;
    });
    println!("{:?}", stream.next().await);
}

worked just fine using the macro.

@taiki-e
Copy link
Member

taiki-e commented Jul 17, 2023

Thanks for the proposal.

I don't have a strong opinion on whether futures-rs should include this, since async-stream and others already have the ability to do this.

@taiki-e taiki-e added the A-stream Area: futures::stream label Jul 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-stream Area: futures::stream
Projects
None yet
Development

No branches or pull requests

2 participants