rust-lang / unsafe-code-guidelines

Forum for discussion about what unsafe code can and can't do
https://rust-lang.github.io/unsafe-code-guidelines
Apache License 2.0
657 stars 57 forks source link

Minimum guarantees for union construction and typed copies? #533

Open joshlf opened 1 day ago

joshlf commented 1 day ago

Given https://github.com/rust-lang/unsafe-code-guidelines/issues/438#issuecomment-2385126730, zerocopy is interested in exploring alternative routes to supporting union transmutations. Our current thinking is that we can accomplish this via safety rather than bit validity requirements.

In order to do this, we'd need two things guaranteed from the language. My question is: Are we comfortable guaranteeing these two invariants?

Safe union construction

Given a union where every possible value of every field contains an initialized byte at a particular offset, we'd like it to be impossible for safe code to produce a value of that union which has an uninitialized byte at that byte offset. It would be acceptable for unsafe code to be able to produce such a value.

Typed union copies

We'd like to guarantee that, in a typed copy of a union value, the byte at any byte position is preserved if that position is initialized in any valid value of any field type. This amounts to saying that the following code is guaranteed to be sound:

let t: T = ...;
let mu = MaybeUninint::<T>::new(t);
// SAFETY: This typed copy copies all of the initialized bytes in `t`, which is a valid `T`.
let t = unsafe { mu.assume_init() };