Skip to content

Commit 3b6313a

Browse files
authored
Merge pull request #1367 from yjhn/patch-1
Remove obsolete note about soundness hole in type-layout.md
2 parents 353e038 + 2dc423d commit 3b6313a

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

src/type-layout.md

+22-8
Original file line numberDiff line numberDiff line change
@@ -549,13 +549,28 @@ The `align` modifier can also be applied on an `enum`.
549549
When it is, the effect on the `enum`'s alignment is the same as if the `enum`
550550
was wrapped in a newtype `struct` with the same `align` modifier.
551551

552-
<div class="warning">
553-
554-
***Warning:*** Dereferencing an unaligned pointer is [undefined behavior] and
555-
it is possible to [safely create unaligned pointers to `packed` fields][27060].
556-
Like all ways to create undefined behavior in safe Rust, this is a bug.
557-
558-
</div>
552+
> Note: References to unaligned fields are not allowed because it is [undefined behavior].
553+
> When fields are unaligned due to an alignment modifier, consider the following options for using references and dereferences:
554+
>
555+
> ```rust
556+
> #[repr(packed)]
557+
> struct Packed {
558+
> f1: u8,
559+
> f2: u16,
560+
> }
561+
> let mut e = Packed { f1: 1, f2: 2 };
562+
> // Instead of creating a reference to a field, copy the value to a local variable.
563+
> let x = e.f2;
564+
> // Or in situations like `println!` which creates a reference, use braces
565+
> // to change it to a copy of the value.
566+
> println!("{}", {e.f2});
567+
> // Or if you need a pointer, use the unaligned methods for reading and writing
568+
> // instead of dereferencing the pointer directly.
569+
> let ptr: *const u16 = std::ptr::addr_of!(e.f2);
570+
> let value = unsafe { ptr.read_unaligned() };
571+
> let mut_ptr: *mut u16 = std::ptr::addr_of_mut!(e.f2);
572+
> unsafe { mut_ptr.write_unaligned(3) }
573+
> ```
559574
560575
### The `transparent` Representation
561576
@@ -587,7 +602,6 @@ used with any other representation.
587602
[enumerations]: items/enumerations.md
588603
[zero-variant enums]: items/enumerations.md#zero-variant-enums
589604
[undefined behavior]: behavior-considered-undefined.md
590-
[27060]: https://github.com/rust-lang/rust/issues/27060
591605
[55149]: https://github.com/rust-lang/rust/issues/55149
592606
[`PhantomData<T>`]: special-types-and-traits.md#phantomdatat
593607
[Default]: #the-default-representation

0 commit comments

Comments
 (0)