How to read a specific number of bytes from a stream?

后端 未结 2 1997
梦谈多话
梦谈多话 2020-12-06 05:24

I have a struct with a BufStream where T: Read+Write. The BufStream can be a TcpStream and I\'d like to read n b

2条回答
  •  攒了一身酷
    2020-12-06 05:32

    It sounds like you want Read::take and Read::read_to_end:

    use std::{
        io::{prelude::*, BufReader},
        str,
    };
    
    fn read_n(reader: R, bytes_to_read: u64) -> Vec
    where
        R: Read,
    {
        let mut buf = vec![];
        let mut chunk = reader.take(bytes_to_read);
        // Do appropriate error handling for your situation
        // Maybe it's OK if you didn't read enough bytes?
        let n = chunk.read_to_end(&mut buf).expect("Didn't read enough");
        assert_eq!(bytes_to_read as usize, n);
        buf
    }
    
    fn main() {
        let input_data = b"hello world";
        let mut reader = BufReader::new(&input_data[..]);
    
        let first = read_n(&mut reader, 5);
        let _ = read_n(&mut reader, 1);
        let second = read_n(&mut reader, 5);
    
        println!(
            "{:?}, {:?}",
            str::from_utf8(&first),
            str::from_utf8(&second)
        );
    }
    

提交回复
热议问题