Read exactly n bytes?

If I want to write exactly n bytes, I can use: Write in std::io - Rust

For reading, I am a bit confused but which function to use here Read in std::io - Rust

I am expecting a function of signature (&mut self, n: usize) -> Vec<u8> , but not seeing it.

Right now, what is the correct way to read n bytes and produce a Vec ? Am I supposed to:

let mut x = vec![0_u8; n]; // construct array of n bytes
return x;


1 Like

Your approach will work, I guess. One possibly nicer approach (because it has a chance of not needing to zero-initialize memory) might be

let mut x = Vec::with_capacity(n);
(&mut reader).take(n as u64).read_to_end(&mut x);
return x;

though I'm not actually entirely certain which of the two approaches is "the correct way" or the best way; or if there's another alternative I've missed.

Thats the solution I would recommend.

In general, Rust libraries try to avoid allocating buffers unless they need to instead preferring to accept a &mut [u8] argument. That way the caller can choose when the allocations are done, read data into a sub-section of some larger buffer, and reuse the same buffer across multiple calls.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.