#async-read #delimiter #slice #tokio #read-stream #byte-stream #async-buf-read

read_until_slice

AsyncBufRead::read_until extension to take a slice as a delimiter instead of a single u8

9 releases

0.1.8 Dec 20, 2024
0.1.7 Sep 22, 2024
0.1.6 Aug 9, 2024
0.1.5 Jun 2, 2024
0.1.2 Feb 18, 2024

#416 in Asynchronous

Download history 157/week @ 2024-09-17 69/week @ 2024-09-24 27/week @ 2024-10-01 21/week @ 2024-10-08 13/week @ 2024-10-15 2/week @ 2024-10-22 1/week @ 2024-11-12 8/week @ 2024-11-19 6/week @ 2024-11-26 1/week @ 2024-12-03 31/week @ 2024-12-10 125/week @ 2024-12-17 6/week @ 2024-12-24 4/week @ 2024-12-31

167 downloads per month
Used in 3 crates (2 directly)

MIT license

9KB
103 lines

read_until_slice  LICENSE crates.io Version Documentation

The tokio io-util feature provides the method:

pub async fn read_until(&mut self, delimiter: u8, buf: Vec<u8>) -> Result<usize>

on impl AsyncBufRead + Unpin.

This reads from an async buffered reader until either EOF or the delimiter is reached.

While useful, it is limited to a single byte delimiter.

This crate extends this by taking a slice as a delimiter instead of a single byte.

pub async fn read_until_slice(&mut self, delimiter: &[u8], buf: Vec<u8>) -> Result<usize>

on the same impl AsyncBufRead + Unpin.

Example

// Open socket
let stream = TcpStream::connect(addr)
    .await
    .expect("could not connect to remote address");
// Split stream into reader and writer halves
let (reader, mut writer) = split(stream);
// Buffer read stream
let mut reader = BufReader::new(reader);
...
// Read until new line delimiter into buffer
let mut buffer = vec![];
let delimiter = b"\r\n";
let n = reader.read_until(delimiter, &mut buffer)
    .await
    .expect("could not read from socket");
assert_eq!(n, buffer.len());
if buffer.ends_with(delimiter) {
    println!("end of line delimiter reached");
} else {
    println!("end of stream reached");
}

Dependencies

~2.1–7.5MB
~50K SLoC