2 ms·
The Box::new_zeroed family lets us sidestep this. I thought it was stabilised, but looks like not yet Box::<u8>::new_zeroed_slice(10 * 1024 * 1024) says we wan
by tialaramex 2y ago
The Box::new_zeroed family lets us sidestep this. I thought it was stabilised, but looks like not yet
Box::<u8>::new_zeroed_slice(10 * 1024 * 1024) says we want 10MiB of zero bytes as a MaybeUninit inside a box, we can then (since these are just bytes in our example) assume_init() since that's valid for our type although in the real world probably we'd actually store some actual data in the memory we've allocated - but it doesn't go on the stack.
If we're overwriting it all anyway there's also an adjacent set of uninit functions to skip the zero step, although of course the OS might be zeroing the page anyway.
- Arnavion 2y agoRight, in the absence of placement-exprs, the alternatives are based around MaybeUninit. Box::new_zeroed() for the "boxed zero array" case, Box::new_uninit() + MaybeUninit::write() + Box::assume_init() for the "boxed arbitrary large value case", Vec::reserve() + Vec::spare_capacity_mut() + MaybeUninit::write() + Vec::set_len() for the "append to Vec" case, etc.