Skip to content

Validity of unions with a zero-sized field #147

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

Merged
merged 3 commits into from
Jul 18, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions reference/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,7 @@
- [Function pointers](./layout/function-pointers.md)
- [Arrays and Slices](./layout/arrays-and-slices.md)
- [Packed SIMD vectors](./layout/packed-simd-vectors.md)
- [Validity](./validity.md)
- [Unions](./validity/unions.md)
- [Optimizations](./optimizations.md)
- [Return value optimization](./optimizations/return_value_optimization.md)
25 changes: 25 additions & 0 deletions reference/src/validity/unions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Validity of unions

**Disclaimer**: This chapter is a work-in-progress. What's contained here
represents the consensus from issue [#73]. The statements in here are not (yet)
"guaranteed" not to change until an RFC ratifies them.

The bit `i` of an union is allowed to have value `v` _iff_ there is a variant of
the union such that bit `i` of the variant is allowed to have value `v`. We
assume all variants to be "filled up" to the same size with padding, which may
have any value.

## Validity of unions with zero-sized fields

A union containing a zero-sized field can contain any value. An example of such
an union is [`MaybeUninit`].

<details><summary><b>Rationale</b></summary>

This follows from the definition of the values that `union` bits are allowed to
take. The zero-sized type has size `0`, and its variant is filled up to
the `union` size with padding. Since padding is allowed to take any value, any
bit in the `union` is allowed to take any value.

[#73]: https://github.com/rust-lang/unsafe-code-guidelines/issues/73
[`MaybeUninit`]: https://doc.rust-lang.org/std/mem/union.MaybeUninit.html