Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jswrenn opened this issue Feb 6, 2025 · 1 comment
Open

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

jswrenn opened this issue Feb 6, 2025 · 1 comment
Labels
A-unions Topic: Related to unions

Comments

@jswrenn
Copy link
Member

jswrenn commented Feb 6, 2025

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?

@RalfJung RalfJung changed the title Do typed copies preserve invalid bytes? Do typed copies of unions preserve invalid bytes? Feb 8, 2025
@RalfJung RalfJung changed the title Do typed copies of unions preserve invalid bytes? Do typed copies of unions preserve "invalid" bytes? Feb 8, 2025
@RalfJung RalfJung added the A-unions Topic: Related to unions label Feb 8, 2025
@RalfJung
Copy link
Member

RalfJung commented Feb 8, 2025

This is tied up with the broader discussion around the value representation of unions, #438 and #494.

I think for unions that look like MaybeUninit, we have general consensus that non-padding bytes are exactly preserved -- but we don't have stable guarantees in that area and we don't (yet) have a good framework for even making such guarantees.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-unions Topic: Related to unions
Projects
None yet
Development

No branches or pull requests

2 participants