Initializing possibly uninit bytes
It would be useful if bytemuck could derive initialization of possibly uninit bytes from a type. This would open up the possibility of transmuting a value into a byte array by first initializing these bytes, and thus roundtripping enums with variants with fields!
E.g.:
/// # Safety
///
/// `ensure_no_uninit` sets any possibly uninit bytes to zero,
/// leaving the value's memory fully initialized.
pub unsafe trait EnsureNoUninit: 'static + Copy + Sized
{
fn ensure_no_uninit(&mut self);
}
#[proc_macro_derive(EnsureNoUninit)]
pub fn derive_ensurenouninit(...) { ... }
pub fn bytes_of_2<T: EnsureNoUninit>(t: &mut T) -> &[u8]
{
t.ensure_no_uninit();
unsafe { internal::bytes_of(t) }
}
#[derive(Clone, Copy)]
#[repr(u16)]
enum Example
{
A(u8),
B(u16),
}
unsafe impl EnsureNoUninit for Example
{
fn ensure_no_uninit(&mut self)
{
// Somehow zero out the padding byte after Self::A.
}
}
This seems potentially possible, at least it's possible in some cases.
Now that #292 landed, this is possible by manually manually adding padding to variants where necessary. This still won't support cases where the alignment of any variant is higher than the alignment of the discriminant, so this is still technically useful in cases where you're following an external data spec you can't control, but I'm not sure it's worth the extra complexity to do so.