#generator #async-await #yield #await #async #future

gen-z

Macro-free stream construction through asynchronous generators via an awaitable sender

1 unstable release

0.1.0 Oct 23, 2020

#1968 in Asynchronous

Download history 1161/week @ 2024-04-13 1198/week @ 2024-04-20 1298/week @ 2024-04-27 1445/week @ 2024-05-04 1479/week @ 2024-05-11 1303/week @ 2024-05-18 1166/week @ 2024-05-25 1249/week @ 2024-06-01 955/week @ 2024-06-08 930/week @ 2024-06-15 1093/week @ 2024-06-22 993/week @ 2024-06-29 1155/week @ 2024-07-06 1242/week @ 2024-07-13 1503/week @ 2024-07-20 991/week @ 2024-07-27

5,008 downloads per month
Used in 4 crates (3 directly)

MIT/Apache

7KB
52 lines

Generators are still unstable, and generating streams requires complicated ownership handling, so this crate aims to enable ad-hoc generation of streams.

Current async implementations attempt to provide yield syntax via macros, but this is not transparent to IDEs at the time of this library's creation, so gen_z attempts to work in a way that IDEs understand.

gen_z(|mut z| async move {
  let awaited = bar().await; // Make awaitable calls in the generator
  z.send(awaited).await; // Streams do not support responses; `yield` has output `()`
  // Share yield helper with calls, allowing them to emit outputs while producing values
  let shared_result = baz(&mut z).await;
  z.send(foo + shared_result).await;
  // Return is infallible; if `Result` is needed, wrap calls to comply with TryStream
}) // => Result is a futures::stream::Stream<Item = T>
  • Send is required for Stream::Item.
    • The stream is Send if the provided future is also Send.
  • Sync is available if Stream::Item and the future are both Sync.
  • The generator only requires FnOnce, so it may close over mutable references.
  • Infinite streams can be generated by looping within the provided future
  • Generators are infallible; the given future must return (), run forever, or panic.
    • To use Result<_, _>, create an inner-future which returns Result and convert an Err return to a type compatible with Stream::Item. TryStream compatibility can be achieved by setting the Stream::Item type to Result<T, TErr>.

Dependencies

~1MB
~15K SLoC