Skip to content

Initializing possibly uninit bytes #302

Open
@zopsicle

Description

@zopsicle

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.
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    proc-macrosI don't do proc-macros, but I accepts PRs about them.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions