async_channel_io

Crates.ioasync_channel_io
lib.rsasync_channel_io
version0.3.0
sourcesrc
created_at2024-04-15 03:10:20.568299
updated_at2024-04-15 03:10:20.568299
description`AsyncRead` and `AsyncWrite` implementations for `async_channel`
homepage
repositoryhttps://github.com/TristanStreich/async_channel_io
max_upload_size
id1208763
size16,916
(TristanStreich)

documentation

https://docs.rs/async_channel_io

README

async_channel_io

Crates.io MIT licensed Build Status

Wrappers around async_channel Sender and Receiver which implement AsyncRead and AsyncWrite

Examples

Writer

use tokio::time;
use async_channel_io::ChannelWriter;
use futures::AsyncWriteExt;

async fn example() {
    let (send, recv) = async_channel::unbounded();
    let mut async_writer = ChannelWriter::new(send);

    async_writer.write(b"Hello").await.unwrap();
    tokio::spawn(async move {
        time::sleep(time::Duration::from_millis(50)).await;
        async_writer.write(b" World!").await.unwrap();
    });

    let mut message = String::new();

    while let Ok(received) = recv.recv().await {
        message.push_str(std::str::from_utf8(&received).unwrap())
    };
    assert_eq!(message, "Hello World!")
}

Reader

use tokio::time;
use async_channel_io::ChannelReader;
use futures::AsyncReadExt;

async fn example() {
    let (send, recv) = async_channel::unbounded();
    let mut async_reader = ChannelReader::new(recv);

    // Have some waiting in receiver
    send.send(String::from("hello").into()).await.unwrap();

    tokio::spawn(async move {
        // send some later
        time::sleep(time::Duration::from_millis(50)).await;
        send.send(String::from(" world").into()).await.unwrap();
    });
    let mut buf = vec![0; 11];

    async_reader.read_exact(&mut buf).await.unwrap();

    let read = String::from_utf8_lossy(&buf).to_string();
    assert_eq!("hello world", read);
}
Commit count: 14

cargo fmt