#async-await #generator #coroutine #yield #await #async

macro genawaiter2-proc-macro

procedural macro for generators (genawaiter2)

1 unstable release

0.100.1 Dec 23, 2024
0.100.0 Dec 23, 2024
0.99.1 Dec 23, 2024

#2397 in Asynchronous

Download history 839/week @ 2024-12-23 1171/week @ 2024-12-30 1782/week @ 2025-01-06 1115/week @ 2025-01-13 1260/week @ 2025-01-20 409/week @ 2025-01-27

4,636 downloads per month
Used in genawaiter2

MIT/Apache

11KB
165 lines

genawaiter

crate-badge docs-badge ci-badge

This crate implements stackless generators (aka coroutines) in stable Rust. Instead of using yield, which won't be stabilized anytime soon, you use async/await, which is stable today.

Features:

  • supports resume arguments and completion values
  • supports async generators (e.g., Streams)
  • allocation-free
  • no runtime dependencies
    • no compile-time dependencies either, with default-features = false
  • built on top of standard language constructs, which means there are no platform-specific shenanigans

Example:

let odd_numbers_less_than_ten = gen!({
    let mut n = 1;
    while n < 10 {
        yield_!(n); // Suspend a function at any point with a value.
        n += 2;
    }
});

// Generators can be used as ordinary iterators.
for num in odd_numbers_less_than_ten {
    println!("{}", num);
}

Result:

1
3
5
7
9

And here is the same generator, this time without macros. This is how you do things with default-features = false (which eliminates the proc macro dependencies).

let odd_numbers_less_than_ten = Gen::new(|co| async move {
    let mut n = 1;
    while n < 10 {
        co.yield_(n).await;
        n += 2;
    }
});

See the docs for more.

Development

Install prerequisites

Install the pre-commit hook

pre-commit install

This installs a Git hook that runs a quick sanity check before every commit.

Run the app

cargo run

Run the tests

cargo test

Dependencies

~1.5MB
~39K SLoC