Search code examples
rustmio

Generic length of array when reading a stream buffer


I would like to set a generic value (n) in the array based on the bytes that are written in the stream. Now I do not know the exact length of the buffer, I just create a hard coded array to read the stream bytes.

use mio::net::TcpStream;

...
let mut buf = [0;12];
stream.read_exact(&mut buf).unwrap();

I would like to swap the 12 hard coded length for a bytes length (n), any clues?


Solution

  • Use Read::read_to_end(). It won't work with non-blocking streams, but just use tokio. Example of using tokio's read_to_end():

    async fn read_to_end(stream: &mut tokio::net::TcpStream) -> Vec<u8> {
        use tokio::io::AsyncReadExt;
        
        let mut data = Vec::new();
        stream.read_to_end(&mut data).await.expect("read failed");
        data
    }