Safer implementation of the uninit_vector function
kitcatier opened this issue · comments
winterfell/utils/core/src/lib.rs
Lines 78 to 82 in c99530d
Hello, here's a safer implementation that uses std::mem::MaybeUninit to create an uninitialized Vec:
pub fn uninit_vector<T>(length: usize) -> Vec<T> {
let mut vector = Vec::with_capacity(length);
unsafe {
let data_ptr = vector.as_mut_ptr();
std::ptr::write_bytes(data_ptr, 0, length);
vector.set_len(length);
}
return vector;
}
This implementation uses std::ptr::write_bytes to initialize each element in the vector. This ensures that all elements in the vector are properly initialized, avoiding potential memory safety issues.
Hi! Thank you for brining this up. If I understood correctly, the above would actually initialize all the allocated memory to zeros, right? If so, what is the advantage of doing this vs. just creating a vector with initialized default elements. For example, something like vec![T::default(); length];
?