All Projects → taiki-e → futures-async-stream

taiki-e / futures-async-stream

Licence: other
Async stream for Rust and the futures crate.

Programming Languages

rust
11053 projects
shell
77523 projects

Projects that are alternatives of or similar to futures-async-stream

easy-ext
An attribute macro for easily writing extension trait pattern.
Stars: ✭ 17 (-87.94%)
Mutual labels:  no-std, proc-macro
Drone Core
The core crate for Drone, an Embedded Operating System.
Stars: ✭ 263 (+86.52%)
Mutual labels:  asynchronous, no-std
drone-cortexm
ARM® Cortex®-M platform crate for Drone, an Embedded Operating System.
Stars: ✭ 31 (-78.01%)
Mutual labels:  asynchronous, no-std
Drone
CLI utility for Drone, an Embedded Operating System.
Stars: ✭ 114 (-19.15%)
Mutual labels:  asynchronous, no-std
async-stm32f1xx
Abstractions for asynchronous programming on the STM32F1xx family of microcontrollers.
Stars: ✭ 24 (-82.98%)
Mutual labels:  asynchronous, no-std
drone-stm32-map
STM32 peripheral mappings for Drone, an Embedded Operating System.
Stars: ✭ 16 (-88.65%)
Mutual labels:  asynchronous, no-std
asynctools
Various asynchronous tools for Nim language
Stars: ✭ 88 (-37.59%)
Mutual labels:  asynchronous
optimath
A #[no_std] LinAlg library
Stars: ✭ 47 (-66.67%)
Mutual labels:  no-std
promise
Common interface for simple asynchronous placeholders.
Stars: ✭ 66 (-53.19%)
Mutual labels:  asynchronous
Promise
Asynchronous Programming with Promises
Stars: ✭ 15 (-89.36%)
Mutual labels:  asynchronous
superstruct
Rust library for versioned data types
Stars: ✭ 27 (-80.85%)
Mutual labels:  proc-macro
cpsfy
🚀 Tiny goodies for Continuation-Passing-Style functions, fully tested
Stars: ✭ 58 (-58.87%)
Mutual labels:  asynchronous
Rx.Book
High level asynchronous programming with Reactive Extensions
Stars: ✭ 67 (-52.48%)
Mutual labels:  asynchronous
buckshot
A fast and capable Minecraft name sniper.
Stars: ✭ 21 (-85.11%)
Mutual labels:  asynchronous
asio-grpc
Asynchronous gRPC with Asio/unified executors
Stars: ✭ 100 (-29.08%)
Mutual labels:  asynchronous
MQTT.jl
An asynchronous MQTT client library for julia
Stars: ✭ 15 (-89.36%)
Mutual labels:  asynchronous
asynchronous
A D port of Python's asyncio library
Stars: ✭ 35 (-75.18%)
Mutual labels:  asynchronous
fetch-http-client
A http client wrapper for fetch api with middleware support.
Stars: ✭ 42 (-70.21%)
Mutual labels:  asynchronous
Shift
Light-weight EventKit wrapper.
Stars: ✭ 31 (-78.01%)
Mutual labels:  asynchronous
cheap-watch
If it works, why use something else? // Mirror of https://git.chor.date/Conduitry/cheap-watch
Stars: ✭ 64 (-54.61%)
Mutual labels:  asynchronous

futures-async-stream

crates.io docs.rs license rustc build status

Async stream for Rust and the futures crate.

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

Usage

Add this to your Cargo.toml:

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

Compiler support: requires rustc nightly-2021-03-11+

#[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::new();
    #[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 generators.

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(generators)]

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();
    }
}

#[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(generators, 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(generators)]
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-threadsafe stream (Pin<Box<dyn Stream<Item = item> + 'lifetime>>).

#![feature(generators)]

use futures::stream::Stream;
use futures_async_stream::stream;
use std::pin::Pin;

// 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(generators)]

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.

How to write the equivalent code without this API?

#[for_await]

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

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

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

#[stream]

You can write this by manually implementing the combinator:

use futures::{
    ready,
    stream::Stream,
    task::{Context, Poll},
};
use pin_project::pin_project;
use std::pin::Pin;

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].