@@ -549,13 +549,28 @@ The `align` modifier can also be applied on an `enum`.
549
549
When it is, the effect on the ` enum ` 's alignment is the same as if the ` enum `
550
550
was wrapped in a newtype ` struct ` with the same ` align ` modifier.
551
551
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
+ > ```
559
574
560
575
### The `transparent ` Representation
561
576
@@ -587,7 +602,6 @@ used with any other representation.
587
602
[enumerations ]: items / enumerations . md
588
603
[zero - variant enums ]: items / enumerations . md#zero - variant - enums
589
604
[undefined behavior ]: behavior - considered - undefined . md
590
- [ 27060 ] : https://github.com/rust-lang/rust/issues/27060
591
605
[55149 ]: https : // github.com/rust-lang/rust/issues/55149
592
606
[`PhantomData <T >`]: special - types - and - traits . md#phantomdatat
593
607
[Default ]: #the - default - representation
0 commit comments