read_volatile in std::ptr - Rust (original) (raw)

Function read_volatile

1.9.0

pub unsafe fn read_volatile<T>(src: *const T) -> T

Expand description

Performs a volatile read of the value from src without moving it.

Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:

Note that volatile memory operations where T is a zero-sized type are noops and may be ignored.

§Safety

Like read, read_volatile creates a bitwise copy of T, regardless of whether T isCopy. If T is not Copy, using both the returned value and the value at *src canviolate memory safety. However, storing non-Copy types in volatile memory is almost certainly incorrect.

Behavior is undefined if any of the following conditions are violated:

Note that even if T has size 0, the pointer must be properly aligned.

§Examples

Basic usage:

let x = 12;
let y = &x as *const i32;

unsafe {
    assert_eq!(std::ptr::read_volatile(y), 12);
}