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

I have a structure with BufStream<T> where T: Read+Write . BufStream could be TcpStream , and I would like to read n bytes from it. Not a fixed number of bytes in a predefined buffer, but I have a line / stream that indicates the number of bytes read.

Is there a good way to do this?

+8
rust
source share
2 answers

Since you can use Rust 1.6, Read::read_exact . If bytes_to_read is the number of bytes to read, it is probably determined at runtime, and reader is the stream to read:

 let mut buf = vec![0u8; bytes_to_read]; reader.read_exact(&mut buf)?; 

The part that was not clear to me from the read_exact documentation was that the target buffer could be a dynamically allocated Vec .

Thanks to the Rust Gitter community for pointing out this solution.

+4
source share

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

 use std::io::prelude::*; use std::io::BufReader; use std::str; fn read_n<R>(reader: R, bytes_to_read: u64) -> Vec<u8> where R: Read, { let mut buf = vec![]; let mut chunk = reader.take(bytes_to_read); // Do appropriate error handling for your situation 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) ); } 
+3
source share

All Articles