Skip to content

Commit 24c0a88

Browse files
committed
unions: call out field offset issues
1 parent 7a5aab5 commit 24c0a88

File tree

2 files changed

+12
-9
lines changed

2 files changed

+12
-9
lines changed

src/items/unions.md

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,13 @@ let f = u.f1;
3939

4040
Unions have no notion of an "active field". Instead, every union access just
4141
interprets the storage at the type of the field used for the access. Reading a
42-
union field reads the bits of the union at the field's type. It is the
43-
programmer's responsibility to make sure that the data is valid at that
44-
type. Failing to do so results in undefined behavior. For example, reading the
45-
value `3` at type `bool` is undefined behavior. Effectively, writing to and then
46-
reading from a union is analogous to a [`transmute`] from the type used for
42+
union field reads the bits of the union at the field's type. Fields might have a
43+
non-zero offset (except when `#[repr(C)]` is used); in that case the bits
44+
starting at the offset of the fields are read. It is the programmer's
45+
responsibility to make sure that the data is valid at that type. Failing to do
46+
so results in undefined behavior. For example, reading the value `3` at type
47+
`bool` is undefined behavior. Effectively, writing to and then reading from a
48+
`#[repr(C)]` union is analogous to a [`transmute`] from the type used for
4749
writing to the type used for reading.
4850

4951
Consequently, all reads of union fields have to be placed in `unsafe` blocks:

src/types/union.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
# Union types
22

33
A *union type* is a nominal, heterogeneous C-like union, denoted by the name of
4-
a [`union` item].
4+
a [`union` item][item].
55

6-
A union access transmutes the content of the union to the type of the accessed
6+
Unions have no notion of an "active field". Instead, every union access
7+
transmutes parts of the content of the union to the type of the accessed
78
field. Since transmutes can cause unexpected or undefined behaviour, `unsafe` is
89
required to read from a union field or to write to a field that doesn't
9-
implement [`Copy`].
10+
implement [`Copy`]. See the [item] documentation for further details.
1011

1112
The memory layout of a `union` is undefined by default, but the `#[repr(...)]`
1213
attribute can be used to fix a layout.
1314

1415
[`Copy`]: special-types-and-traits.html#copy
15-
[`union` item]: items/unions.html
16+
[item]: items/unions.html

0 commit comments

Comments
 (0)