I have a small crate called arr that is specifically designed for large fixed-sized heap arrays (billions of elements could be stored in this). I have a problem though in understanding the proper way to implement Drop for this array.
pub struct Array<T> {
size: usize,
ptr: *mut T,
}
My original Drop looked like this:
impl<T> Drop for Array<T> {
fn drop(&mut self) {
let objsize = std::mem::size_of::<T>();
let layout = Layout::from_size_align(self.size * objsize, 8).unwrap();
unsafe {
dealloc(self.ptr as *mut u8, layout);
}
}
}
However - this is clearly not right, because if T is a Drop then I am leaking memory - a fact which a kindly github member pointed out to me. But how best should I free this memory? Naively I think I could loop through all the elements and call std::ptr::drop_in_place on them:
for i in 0..(self.size as isize) {
std::ptr::drop_in_place(self.ptr.wrapping_offset(i));
}
But if the array is a billion u8's isn't this a terrible idea as that would be a billion no-ops? I guess the compiler should be smart enough to do dead-code elision so perhaps I'm falling prey to premature optimization.