Skip to content

Commit 38b1340

Browse files
authored
Revise union field access guidelines in values.rst
Clarify conditions for accessing union fields and update non-compliant examples.
1 parent d9d7249 commit 38b1340

File tree

1 file changed

+5
-19
lines changed

1 file changed

+5
-19
lines changed

src/coding-guidelines/values.rst

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ Values
2424

2525
- All bytes of the field read have been initialized by a prior write.
2626
- The bytes form a valid representation for the field's type
27-
(e.g., no invalid ``enum`` discriminants, no invalid pointer values, etc.).
27+
(e.g., ``enum`` discriminants are valid and ``bool`` has an underlying value of 0 or 1).
2828

2929
.. rationale::
3030
:id: rat_kjFRrhpS8Wu6
@@ -43,7 +43,8 @@ Values
4343
:status: draft
4444

4545
This noncompliant example creates a value of type ``u32`` from uninitialized memory via
46-
`assume_init <https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init>`_:
46+
`assume_init <https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init>`_.
47+
Here, calling ``assume_init`` is equivalent to an uninitialied read.
4748

4849
.. code-block:: rust
4950
@@ -153,20 +154,6 @@ Values
153154
x.write(42);
154155
let val = unsafe { x.assume_init() }; // OK — value was fully initialized
155156
156-
.. non_compliant_example::
157-
:id: non_compl_ex_Qb5GqYTP6db2
158-
:status: draft
159-
160-
Creating a reference from arbitrary or uninitialized bytes is always undefined behavior.
161-
References must be valid, aligned, properly dereferenceable, and non-null.
162-
Uninitialized memory cannot satisfy these invariants.
163-
164-
.. code-block:: rust
165-
166-
use std::mem::MaybeUninit;
167-
168-
let r: &u32 = unsafe { MaybeUninit::uninit().assume_init() }; // UB — invalid reference
169-
170157
.. non_compliant_example::
171158
:id: non_compl_ex_Qb5GqYTP6db5
172159
:status: draft
@@ -201,9 +188,8 @@ Values
201188
:status: draft
202189

203190
Even though unions allow reads of any field, not all bit patterns are valid for a ``bool``.
204-
Unions do not relax type validity requirements.
205-
Only the read itself is allowed;
206-
the resulting bytes must still be a valid bool.
191+
Unions do not relax type validity requirements for individual fields.
192+
The resulting bytes must still be a valid allocation of type ``bool``.
207193

208194
.. code-block:: rust
209195

0 commit comments

Comments
 (0)