Skip to content

Commit c17f7d7

Browse files
committed
Add compliant example
1 parent c728977 commit c17f7d7

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

src/coding-guidelines/unsafety.rst

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,14 @@ Unsafety
3737

3838
.. code-block:: rust
3939
40-
fn example_function() {
40+
fn example_function() -> bool {
4141
unsafe {
4242
std::transmute<bool>(3_u8)
4343
}
4444
}
4545
46-
A necessary condition to read the value behind a pointer is that it points to a live allocation.
47-
This is never the case for the live pointer, therefore reading a null pointer is undefined behavior.
46+
A necessary condition to read the value behind a pointer is that it points to a valid allocation.
47+
This is never the case for a null pointer, therefore reading it is undefined behavior.
4848
See the safety precondition of :std:`std::ptr::read`.
4949

5050
.. code-block:: rust
@@ -55,4 +55,31 @@ Unsafety
5555
}
5656
}
5757
58+
.. compliant_example::
59+
:id: compl_ex_mt8h0T3BtONt
60+
:status: draft
61+
62+
Since ``0_u8`` is defined to represent the ``false`` value of bool, this example is free of
63+
undefined behavior.
64+
65+
.. code-block:: rust
66+
67+
fn example_function() -> bool {
68+
unsafe {
69+
std::transmute<bool>(0_u8);
70+
}
71+
}
72+
73+
``ptr`` points to a valid, aligned and properly initialized allocation.
74+
Therefore, it satisfies all safety preconditions of :std:`std::ptr::read` and can be read
75+
without undefined behavior.
76+
77+
.. code-block:: rust
78+
79+
fn example_function() {
80+
let ptr = Box::new(42).into_raw();
81+
unsafe {
82+
std::ptr::read(ptr);
83+
}
84+
}
5885

0 commit comments

Comments
 (0)