simple_comms/protocol/
io_helpers.rs

1use std::io::{self, Read};
2
3use tokio::io::AsyncReadExt;
4
5// Read helpers
6pub fn read_with_std_io<R: Read>(reader: &mut R, buffer: &mut [u8]) -> io::Result<()> {
7    reader.read_exact(buffer)?;
8    Ok(())
9}
10
11pub async fn read_with_tokio_io<R: AsyncReadExt + Unpin>(
12    reader: &mut R,
13    buffer: &mut Vec<u8>,
14) -> io::Result<()> {
15    reader.read_to_end(buffer).await?;
16    Ok(())
17}
18
19pub async fn read_until<T>(stream: &mut T, delimiter: Vec<u8>) -> io::Result<Vec<u8>>
20where
21    T: AsyncReadExt + Unpin,
22{
23    let mut result_buffer: Vec<u8> = Vec::new();
24    let delimiter_len = delimiter.len();
25
26    loop {
27        // Buffer for reading a single byte at a time
28        let mut byte = [0u8];
29
30        // Read one byte
31        let bytes_read = stream.read(&mut byte).await?;
32        if bytes_read == 0 {
33            // End of stream reached without finding the delimiter
34            return Err(io::Error::new(
35                io::ErrorKind::UnexpectedEof,
36                "Delimiter not found",
37            ));
38        }
39
40        // Append the byte to the result buffer
41        result_buffer.push(byte[0]);
42
43        // Check if the end of result_buffer matches the delimiter
44        if result_buffer.len() >= delimiter_len
45            && result_buffer[result_buffer.len() - delimiter_len..] == delimiter[..]
46        {
47            // Found the delimiter; return the buffer up to (and including) it
48            return Ok(result_buffer);
49        }
50    }
51}