|
| 1 | +# Representation of unions |
| 2 | + |
| 3 | +**Disclaimer:** This chapter represents the consensus from issue |
| 4 | +[#13]. The statements in here are not (yet) "guaranteed" |
| 5 | +not to change until an RFC ratifies them. |
| 6 | + |
| 7 | +[#13]: https://github.com/rust-rfcs/unsafe-code-guidelines/issues/13 |
| 8 | + |
| 9 | +The only degree of freedom the compiler has when computing the layout of a union |
| 10 | +like |
| 11 | + |
| 12 | +```rust |
| 13 | +union U { f1: T1, f2: T2 } |
| 14 | +``` |
| 15 | + |
| 16 | +is to determine the offset of the fields. The layout of these fields themselves |
| 17 | +is already entirely determined by their types, and since we intend to allow |
| 18 | +creating references to fields (`&u.f1`), unions do not have any wiggle-room |
| 19 | +there. |
| 20 | + |
| 21 | +### C-compatible layout ("repr C") |
| 22 | + |
| 23 | +For unions tagged `#[repr(C)]`, the compiler will apply the C layout scheme. Per |
| 24 | +sections [6.5.8.5] and [6.7.2.1.16] of the C11 specification, this means that |
| 25 | +the offset of every field is 0. Unsafe code can case a pointer to the union to |
| 26 | +a field type to obtain a pointer to any field, and vice versa. |
| 27 | + |
| 28 | +[6.5.8.5]: http://port70.net/~nsz/c/c11/n1570.html#6.5.8p5 |
| 29 | +[6.7.2.1.16]: http://port70.net/~nsz/c/c11/n1570.html#6.7.2.1p16 |
| 30 | + |
| 31 | +### Default layout ("repr rust") |
| 32 | + |
| 33 | +**The default layout of unions is not specified.** As of this writing, we want |
| 34 | +to keep the option of using non-zero offsets open for the future; whether this |
| 35 | +is useful depends on what exactly the compiler-assumed invariants about union |
| 36 | +contents are. |
0 commit comments