What Is the Unsafe Contract and How to Document It

Unsafe Rust allows bypassing memory safety checks for low-level tasks, documented by wrapping code in unsafe blocks with safety justifications.

The unsafe keyword in Rust allows you to opt out of the compiler's memory safety guarantees to perform low-level operations like dereferencing raw pointers or calling unsafe functions. You document this by wrapping the risky code in an unsafe block and adding a comment explaining why the specific operation is safe in that context.

/// # Safety
/// This is safe because `ptr` is guaranteed to be valid and initialized.
unsafe fn read_raw_pointer(ptr: *const i32) -> i32 {
    *ptr
}