1313 :scope: system
1414 :tags: defect, safety, undefined-behavior
1515
16- When reading from a union field, ensure that the underlying bytes constitute a valid value
17- for that field' s type.
18- Reading a union field whose bytes do not represent a valid value
19- for the field' s type is undefined behavior.
16+ When reading from a union field, ensure that the underlying bytes constitute a valid value for that field' s type.
17+ Reading a union field whose bytes do not represent a valid value for the field' s type is undefined behavior.
2018
2119 Before accessing a union field:
2220
2927 :status: draft
3028
3129 Unions allow multiple fields to occupy the same memory, similar to C unions.
32- Unlike enums , unions do not track which field is currently active. It is the programmer ' s
33- responsibility to ensure that when a field is read, the underlying bytes are valid for
34- that field' s type [RUST-REF-UNION ]_.
30+ Unlike enumeration types , unions do not track which field is currently active.
31+ You must ensure that when a field is read,
32+ the underlying bytes are valid for that field' s type [1 ]_.
3533
3634 Every type has a *validity invariant* — a set of constraints that all values of
37- that type must satisfy [UCG-VALIDITY ]_.
35+ that type must satisfy [2 ]_.
3836 Reading a union field performs a *typed read*,
3937 which asserts that the bytes are valid for the target type.
4038 Violating this invariant is undefined behavior.
286284 :id: bib_UnionFieldValidity
287285 :status: draft
288286
287+ ```rst
289288 .. list-table::
290289 :header-rows: 0
291- :widths: 10 80
290+ :widths: 5 85
292291
293- * - .. [RUST-REF-UNION ]
292+ * - .. [1 ]
294293 - The Rust Project Developers. " Rust Reference: Unions." *The Rust Reference*, n.d. https:// doc.rust-lang.org/reference/items/unions.html.
295- * - .. [UCG-VALIDITY ]
294+ * - .. [2 ]
296295 - Rust Unsafe Code Guidelines Working Group. " Validity and Safety Invariant." *Rust Unsafe Code Guidelines*, n.d. https:// rust-lang.github.io/unsafe-code-guidelines/glossary.html#validity-and-safety-invariant.
297296
298297>>>>>>> c93b2cb (Update types-and -traits.rst):src/coding-guidelines/types-and-traits.rst
0 commit comments