Skip to content

Commit 6702509

Browse files
committed
Validity of unions with a zero-sized field
1 parent 97cbda4 commit 6702509

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

reference/src/SUMMARY.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,7 @@
1111
- [Function pointers](./layout/function-pointers.md)
1212
- [Arrays and Slices](./layout/arrays-and-slices.md)
1313
- [Packed SIMD vectors](./layout/packed-simd-vectors.md)
14+
- [Validity](./validity.md)
15+
- [Unions](./validity/unions.md)
1416
- [Optimizations](./optimizations.md)
1517
- [Return value optimization](./optimizations/return_value_optimization.md)

reference/src/validity/unions.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Validity of unions
2+
3+
**Disclaimer**: This chapter is a work-in-progress. What's contained here
4+
represents the consensus from issue [#73]. The statements in here are not (yet)
5+
"guaranteed" not to change until an RFC ratifies them.
6+
7+
The bit `i` of an union is allowed to have value `v` _iff_ there is a variant of
8+
the union such that bit `i` of the variant is allowed to have value `v`. We
9+
assume all variants to be "filled up" to the same size with padding, which may
10+
have any value.
11+
12+
## Validity of unions with zero-sized fields
13+
14+
A union containing a zero-sized field can contain any value. An example of such
15+
an union is [`MaybeUninit`].
16+
17+
<details><summary><b>Rationale</b></summary>
18+
19+
This follows from the definition of the values that `union` bits are allowed to
20+
take. The zero-sized type has size `0`, and its variant is filled up to
21+
the `union` size with padding. Since padding is allowed to take any value, any
22+
bit in the `union` is allowed to take any value.
23+
24+
[#73]: https://github.com/rust-lang/unsafe-code-guidelines/issues/73
25+
[`MaybeUninit`]: https://doc.rust-lang.org/std/mem/union.MaybeUninit.html

0 commit comments

Comments
 (0)