Write a safe function that wraps the unsafe operation, using an unsafe block only for the specific low-level action while validating inputs and maintaining invariants in the safe API. This isolates the risk to a single, audited location and prevents unsafe code from leaking into the rest of your application.
pub fn safe_dereference(ptr: *const i32) -> Option<i32> {
if ptr.is_null() {
return None;
}
unsafe {
Some(*ptr)
}
}
In this pattern, the public safe_dereference function checks for null pointers before entering the unsafe block, ensuring that the raw pointer dereference is only performed when it is guaranteed to be valid.