#tokio #read-stream #stream #io #async-io #rewind #read-write

tokio-io-rewind

A simple library to rewind tokio::io::AsyncRead and tokio::io::AsyncWrite streams

3 releases

0.1.2 Mar 26, 2024
0.1.1 Mar 26, 2024
0.1.0 Mar 26, 2024

#322 in Asynchronous

Download history 282/week @ 2024-03-24 129/week @ 2024-03-31 179/week @ 2024-04-07 67/week @ 2024-04-14 35/week @ 2024-04-21 18/week @ 2024-04-28 66/week @ 2024-05-05

194 downloads per month

MIT license

10KB
104 lines

tokio-io-rewind

tokio-io-rewind is a Rust crate providing a wrapper for types implementing the AsyncRead and AsyncWrite traits, allowing for the prepending of bytes to the read stream. This functionality is particularly useful in scenarios where data read from a stream needs to be re-examined or processed again, making it an ideal choice for networking, parsing, and proxying tasks where data manipulation is crucial.

Features

  • Prepend Bytes: Easily prepend bytes to the beginning of your read stream.
  • Transparent Async Operations: Works seamlessly with async read and write operations, ensuring minimal overhead.
  • Flexibility: Can be used with any type that implements AsyncRead and AsyncWrite, offering wide applicability.

Usage

To use tokio-io-rewind, add it as a dependency in your Cargo.toml:

[dependencies]
tokio-io-rewind = "0.1"

Basic Example

use tokio_io_rewind::Rewind;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use bytes::Bytes;

#[tokio::main]
async fn main() {
    let inner_stream = tokio::io::Cursor::new(b"world".to_vec());
    let mut rewind_stream = Rewind::new(inner_stream);
    
    // Prepend "hello " to the stream
    rewind_stream.rewind(Bytes::from_static(b"hello "));
    
    let mut buf = Vec::new();
    rewind_stream.read_to_end(&mut buf).await.unwrap();
    
    assert_eq!(buf, b"hello world");
}

Advanced Usage

For more advanced use cases, such as pre-buffering data or handling complex async write operations, tokio-io-rewind can be configured with additional buffer states or integrated into custom async flows.

Buffered Initialization

To initialize with a buffer, you can use:

let preloaded_buffer = Bytes::from_static(b"initial data");
let rewind_stream = Rewind::new_buffered(inner_stream, preloaded_buffer);

This preloads the stream with "initial data" that will be read before any subsequent data.

License

MIT License

Dependencies

~2.1–3MB
~49K SLoC