Function write_volatile

pub const unsafe fn write_volatile<T>(dst: *mut T, src: T)

Performs a volatile write of a memory location with the given value without reading or dropping the old value.

Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), 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 on zero-sized types (e.g., if a zero-sized type is passed to write_volatile) are noops and may be ignored.

write_volatile does not drop the contents of dst. This is safe, but it could leak allocations or resources, so care should be taken not to overwrite an object that should be dropped when operating on Rust memory. Additionally, it does not drop src. Semantically, src is moved into the location pointed to by dst.

When invoked during const evaluation, this behaves like a regular write. In particular, such reads must always follow the first of the two cases above.

Store splitting

Exactly which hardware stores are performed by this function is, in general, highly target-dependent.

For a simple scalar, such as when T is a thin pointer, this will typically be one store assuming your target supports a store of exactly that size and alignment.

For anything else, it will be split into multiple stores in some unspecified way. This can happen even for scalars: notably, on many targets storing a u128 will still need to be split, despite being "one" scalar. On many targets storing anything larger than a pointer will need to be split. On all current targets a store larger than 64 bytes will need to be split. Any store whose size is not a power of two will also almost certainly need to be split.

There is no stability guarantee on how that splitting happens. It may change at any point.

Safety

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 mut x = 0;
let y = &mut x as *mut i32;
let z = 12;

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