Read an arbitrary number of bytes from type implementing Read

后端 未结 3 1394
南旧
南旧 2021-01-13 08:33

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

3条回答
  •  萌比男神i
    2021-01-13 09:12

    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.

提交回复
热议问题