Function core::ptr::read_unaligned 1.17.0[−][src]
pub unsafe fn read_unaligned<T>(src: *const T) -> T
Reads the value from src
without moving it. This leaves the
memory in src
unchanged.
Unlike read
, read_unaligned
works with unaligned pointers.
Safety
Behavior is undefined if any of the following conditions are violated:
src
must be valid.
Like read
, read_unaligned
creates a bitwise copy of T
, regardless of
whether T
is Copy
. If T
is not Copy
, using both the returned
value and the value at *src
can violate memory safety.
Examples
Access members of a packed struct by reference:
use std::ptr; #[repr(packed, C)] #[derive(Default)] struct Packed { _padding: u8, unaligned: u32, } let x = Packed { _padding: 0x00, unaligned: 0x01020304, }; let v = unsafe { // Take a reference to a 32-bit integer which is not aligned. let unaligned = &x.unaligned; // Dereferencing normally will emit an unaligned load instruction, // causing undefined behavior. // let v = *unaligned; // ERROR // Instead, use `read_unaligned` to read improperly aligned values. let v = ptr::read_unaligned(unaligned); v }; // Accessing unaligned values directly is safe. assert!(x.unaligned == v);Run