Skip to content

Commit 57f303a

Browse files
rcseacordmanhatsu
authored andcommitted
Enhance values.rst with additional noncompliant and compliant examples
Added noncompliant and compliant examples demonstrating safe /unsafe memory initialization in Rust.
1 parent ab3bd77 commit 57f303a

File tree

1 file changed

+53
-1
lines changed

1 file changed

+53
-1
lines changed

src/coding-guidelines/values.rst

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,46 @@ Values
5151
:id: non_compl_ex_Qb5GqYTP6db1
5252
:status: draft
5353

54-
This noncompliant example creates a value from uninitialized memory via ``assume_init``:
54+
This noncompliant example creates a value of type ``u32`` from uninitialized memory via
55+
`assume_init <https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init>`_:
5556

5657
.. code-block:: rust
5758
5859
use std::mem::MaybeUninit;
5960
6061
let x: u32 = unsafe { MaybeUninit::uninit().assume_init() }; // UB
6162
63+
.. compliant_example::
64+
:id: compl_ex_Ke869nSXuShU
65+
:status: draft
66+
67+
Types such as ``u8``, ``u16``, ``u32``, and ``i128`` allow all possible bit patterns.
68+
Provided the memory is initialized, there is no undefined behavior.
69+
70+
.. code-block:: rust
71+
72+
union U {
73+
n: u32,
74+
bytes: [u8; 4],
75+
}
76+
77+
let u = U { bytes: [0xFF, 0xEE, 0xDD, 0xCC] };
78+
let n = unsafe { u.n }; // OK — all bit patterns valid for u32
79+
80+
.. compliant_example::
81+
:id: compl_ex_Ke869nSXuShV
82+
:status: draft
83+
84+
This compliant example calles the ``write`` function to fully initialize low-level memory.
85+
86+
.. code-block:: rust
87+
88+
use std::mem::MaybeUninit;
89+
90+
let mut x = MaybeUninit::<u64>::uninit();
91+
x.write(42);
92+
let val = unsafe { x.assume_init() }; // OK — value was fully initialized
93+
6294
.. non_compliant_example::
6395
:id: non_compl_ex_Qb5GqYTP6db2
6496
:status: draft
@@ -135,3 +167,23 @@ Values
135167
let u = U { x: 255 }; // 255 is not a valid bool representation
136168
let b = unsafe { u.b }; // UB — invalid bool
137169
170+
.. compliant_example::
171+
:id: compl_ex_Ke869nSXuShT
172+
:status: draft
173+
174+
Accessing padding bytes is allowed if not interpreted as typed data:
175+
176+
.. code-block:: rust
177+
178+
#[repr(C)]
179+
struct S {
180+
a: u8,
181+
b: u32,
182+
}
183+
184+
let mut buf = [0u8; std::mem::size_of::<S>()];
185+
buf[0] = 10;
186+
buf[1] = 20; // writing padding is fine
187+
188+
let p = buf.as_ptr() as *const S;
189+
let s = unsafe { p.read_unaligned() }; // OK — all *fields* are initialized (padding doesn’t matter)

0 commit comments

Comments
 (0)