I have something that is Read
; currently it\'s a File
. I want to read a number of bytes from it that is only known at runtime (length prefix in a b
You can always use a bit of unsafe
to create a vector of uninitialized memory. It is perfectly safe to do with primitive types:
let mut v: Vec = Vec::with_capacity(length);
unsafe { v.set_len(length); }
let count = file.read(vec.as_mut_slice()).unwrap();
This way, vec.len()
will be set to its capacity, and all bytes in it will be uninitialized (likely zeros, but possibly some garbage). This way you can avoid zeroing the memory, which is pretty safe for primitive types.
Note that read()
method on Read
is not guaranteed to fill the whole slice. It is possible for it to return with number of bytes less than the slice length. There are several RFCs on adding methods to fill this gap, for example, this one.