Skip to content

Do typed copies of unions preserve "invalid" bytes? #555

Closed
@jswrenn

Description

@jswrenn

For zerocopy, @joshlf and I are interested in whether we can soundly round-trip values through a union that aren't bit-valid instances of a non-ZST field; e.g.:

union Tricky {
    a: bool,
    b: (),
}

fn main() {
    let src = 3u8;

    // Is it sound to do this? Or insta-UB a la transmuting `3` to `bool`?
    let dst: Tricky = unsafe {
        core::mem::transmute(src)
    };

    // Is it sound to do this? Or are we possibly reading an uninit byte here?
    assert_eq!(src,
        unsafe { core::mem::transmute(dst) }
    )
}

The reasons for our concern is that we know typed copies don't have to preserve padding, but will they preserve initialized-but-invalid bytes?

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-unionsTopic: Related to unions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions