I have a reader that contains info about a 51*51 grid, where each spot on the grid is represented by an f32. I want to read this data into a vector so that I can easily deal with it:
pub fn from_reader<R: Read + Seek>(reader: &mut R) -> Arena {
let arena_size = 51 * 51;
let arena_byte_size = arena_size * size_of::<f32>();
let mut arena = vec![0.0f32; arena_size];
unsafe {
let mut arena_slice =
std::slice::from_raw_parts_mut(arena.as_mut_ptr() as *mut u8, arena_byte_size);
let _ = reader.read(&mut arena_slice);
};
//...
}
This method is inconvenient and unnecessarily slow as it forces the vector to be initialized with 0 values for all its elements. I originally wanted to simply allocate a buffer, not initialize it, read the data into it then use from_raw_parts to create a vector out of it. However I was informed that this is undefined behavior since for some unfathomable reason, read and read_exact require the caller to initialize the data being passed to them before calling either of them.
Why is this the case? Is there any workaround? Are there any solutions being worked on by the Rust team?