Sub topic 7
Wrapping unsafe code in a safe API
This chapter assumes you know ownership, borrowing, slices, and structs in safe Rust. You should also know what an unsafe block allows and what a safety contract is. Here you will learn to hide unsafe code behind a function that no caller can misuse.
What makes an abstraction sound
A safe function is sound if no caller can cause undefined behavior by using it, whatever arguments they pass. Safe code can never be blamed for undefined behavior. If a safe function can trigger it, the bug lies in the function that contains the unsafe block.
The usual pattern has three steps:
- Check the preconditions at runtime, for example with
assert!. - Run the unsafe operation, which is now known to be valid.
- Return types that keep the guarantees, such as
&mut [T].
A worked example: split_at_mut
The borrow checker rejects two &mut borrows of one slice, even when they cover different parts. We know the two halves do not overlap, so we can build them with raw pointers.
use std::slice;
fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
let len = values.len();
let ptr = values.as_mut_ptr();
assert!(mid <= len);
// SAFETY: `mid <= len`, so both ranges lie inside the original slice,
// and they do not overlap, so the two &mut slices never alias.
unsafe {
(
slice::from_raw_parts_mut(ptr, mid),
slice::from_raw_parts_mut(ptr.add(mid), len - mid),
)
}
}
fn main() {
let mut data = [1, 2, 3, 4, 5];
let (left, right) = split_at_mut(&mut data, 2);
left[0] = 10;
right[0] = 30;
println!("{:?} {:?}", left, right);
}This prints [10, 2] [30, 4, 5]. Each piece of the code does a specific job:
assert!(mid <= len)turns a possible out-of-bounds pointer into a panic. A panic is safe. Undefined behavior is not.from_raw_parts_mutis an unsafe function. It requires a valid, aligned pointer and a length that stays inside one allocation. Theassert!and the origin ofptrsatisfy both requirements.ptr.add(mid)is also unsafe to use out of range. Withmid <= lenit stays within the slice or one past its end, which is allowed.- The two ranges are
0..midandmid..len. They share no elements, so the two&mutreferences never alias. - Lifetimes in the signature tie both outputs to the input borrow. The result cannot outlive
values.
Arguing soundness
For each unsafe call, write down its requirements and show where each one is met. The SAFETY: comment is where you record this argument. A reviewer can then check the comment against the code.
Ask these questions about your wrapper:
- Can any safe input, including
0,usize::MAX, or an empty slice, break a requirement? - Does the signature promise more than the code guarantees, for example a lifetime that is too long?
- If the function panics halfway through, does it leave data in a broken state?
Common mistakes
| Mistake | Why it is unsound |
|---|---|
| Using `debug_assert!` for a safety check | The check disappears in release builds, so undefined behavior returns. |
| Marking a function safe when it trusts the caller | A safe function cannot rely on caller promises. Make it `unsafe fn` instead. |
| Returning a reference with an unbounded lifetime | A caller can keep it after the data is freed. |
| Checking `mid < len` instead of `mid <= len` | This is merely too strict here. The reverse mistake, `mid <= len + 1`, would read out of bounds. |
Exercise
In split_at_mut, suppose you replace assert!(mid <= len) with debug_assert!(mid <= len). Is the function still sound? Why or why not?
Show answer
No. In release builds debug_assert! is removed, so a caller passing mid > len makes from_raw_parts_mut build a slice that extends past the original allocation. That is undefined behavior reachable from safe code, so the function is unsound.
Exercise
Why is it correct for split_at_mut to be a safe function, even though its body contains an unsafe block?
Show answer
The function checks the only precondition itself (mid <= len), and the rest follows from the input being a valid &mut [i32]. No safe caller can make the unsafe operations violate their requirements, so the function is sound and needs no unsafe in its signature.