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.
Behavior is undefined if any of the following conditions are violated:
src
must be valid for reads.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.
Note that even if T
has size 0
, the pointer must be non-NULL.
Access members of a packed struct by reference:
use std::ptr; #[repr(packed, C)] struct Packed { _padding: u8, unaligned: u32, } let x = Packed { _padding: 0x00, unaligned: 0x01020304, }; let v = unsafe { // Take the address of a 32-bit integer which is not aligned. // This must be done as a raw pointer; unaligned references are invalid. let unaligned = &x.unaligned as *const u32; // Dereferencing normally will emit an aligned 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);
© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/ptr/fn.read_unaligned.html