Sub topic 7
Wrapping unsafe code in a safe API
This chapter assumes you can read and write safe Rust, know what raw pointers are, and have seen unsafe blocks and unsafe fn contracts. It covers how to hide unsafe code behind an interface that other code cannot misuse.
Why wrap unsafe code
Most unsafe code in real programs is not exposed to callers. Vec, String, Rc, and Mutex all use unsafe code internally, and you use them without writing unsafe. They work because each one wraps its unsafe operations in a safe API.
A safe API is sound if no sequence of safe calls can cause undefined behavior. A safe API is unsound if some safe program can cause undefined behavior through it, even if that program is unlikely or silly. Soundness is a yes-or-no property. A function that is "almost always fine" is unsound.
This gives two jobs:
- Inside the abstraction, you uphold every contract of the unsafe operations you use.
- At the boundary, you make sure callers cannot break those contracts, whatever they pass in.
A first example: split_at_mut
The borrow checker rejects any attempt to hold two &mut references into the same slice. Two non-overlapping halves are safe, but the checker cannot prove that. The standard library solves this with unsafe code behind a safe function. Here is the same idea:
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);
}The function is not marked unsafe, and it has three properties that make it sound:
- It checks the precondition itself.
from_raw_parts_mutrequires the range to be valid, so the function callsassert!(mid <= len)first. A badmidpanics. A panic is a defined, safe failure. - The lifetimes come from the input. The elided lifetimes tie both returned slices to the borrow of
values. Raw-pointer functions likefrom_raw_parts_mutreturn slices with an unconstrained lifetime, and the function signature is what stops that lifetime from growing. - The SAFETY comment gives an argument. It does not say "this is fine". It names the facts (
mid <= len, no overlap) that satisfy the contract.
The unsafe boundary is the module
Checking arguments is enough for a free function. For a type with private state, the check must cover the whole type, because safe code that is not careful can change that state.
Unsafe code relies on facts about data, called invariants. For example, "len never exceeds the length of the buffer" is an invariant. An invariant is only trustworthy if no code outside your control can break it. In Rust, you control this with privacy: private fields can only be changed by code in the same module.
mod bounded {
pub struct Bounded {
data: Vec<u32>,
// Invariant: len <= data.len()
len: usize,
}
impl Bounded {
pub fn new(data: Vec<u32>, len: usize) -> Option<Bounded> {
if len <= data.len() {
Some(Bounded { data, len })
} else {
None
}
}
pub fn get(&self, i: usize) -> Option<u32> {
if i < self.len {
// SAFETY: `i < len` and the invariant `len <= data.len()`
// give `i < data.len()`, so the index is in bounds.
Some(unsafe { *self.data.get_unchecked(i) })
} else {
None
}
}
pub fn shrink(&mut self, new_len: usize) {
assert!(new_len <= self.len);
self.len = new_len;
}
}
}
fn main() {
let mut b = bounded::Bounded::new(vec![10, 20, 30, 40], 3).unwrap();
println!("{:?} {:?}", b.get(2), b.get(3));
b.shrink(1);
println!("{:?}", b.get(2));
}The unsafe block in get is correct only because every function that can write len preserves the invariant. new checks it, and shrink can only make len smaller. If the fields were pub, any caller could write b.len = 1_000_000 in safe code, and get would read out of bounds. The bug would be in the unsafe block's assumption, but the cause would be the public field.
This leads to a rule for reviewing: a safe function that contains unsafe code is only as sound as every other function in the same module that touches the same state. When you audit an unsafe block, read the whole module, not only the block.
A common unsound pattern
This function looks harmless and compiles without warnings:
// UNSOUND: safe signature, but the precondition is never checked.
fn first(values: &[u32]) -> u32 {
unsafe { *values.get_unchecked(0) }
}
fn main() {
// Fine only because the slice is not empty.
println!("{}", first(&[5, 6, 7]));
}Calling first(&[]) in safe code is undefined behavior. There are two ways to fix it:
- Check the condition and return
Option<u32>or panic, so the function stays safe. - Mark the function
unsafe fnand documentvaluesas needing at least one element. This moves the burden to the caller, as in the previous chapter.
Choose the safe version when the check is cheap. Choose unsafe fn when the check costs real performance and callers can often prove the condition cheaply themselves.
How the safety argument flows
Design rules for sound wrappers
| Situation | Sound approach | Unsound approach |
|---|---|---|
| Precondition depends on arguments | `assert!` or return `Result`/`Option` before the unsafe block | Assume callers pass good values |
| Precondition depends on stored state | Keep the state private and update it only in the module | Make the field `pub` |
| Returning references from raw pointers | Tie the lifetime to `&self` or an input reference | Let the compiler infer an unbounded lifetime |
| Check is expensive and caller can prove it | Offer an `unsafe fn` variant with a `# Safety` section | Hide the cost by skipping the check in a safe fn |
| Generic code calls user closures or trait methods | Assume they can panic or behave oddly | Assume they are well-behaved |
Panics and user code
Safe code can panic, and a panic unwinds through your function. If your unsafe code leaves data in a half-built state when that happens, a later destructor might read invalid memory. For example, you may have extended a Vec's length before initializing the new elements. Then a closure the user supplied panics, and drop runs on garbage.
To avoid this:
- Keep the invariants true at every point where code you do not control can run. This includes closures, trait methods,
Clone,Drop, andPartialEq. - Update the length only after the elements it covers are initialized.
- Do not assume a generic type's methods return consistent results between two calls.
Writing the argument
Every unsafe block in a wrapper should have a comment that answers one question: why does each requirement of the unsafe operation hold here? A useful comment lists the facts it relies on and where each comes from. It might say "checked by the assert! above" or "invariant of Bounded, maintained by new and shrink". A comment such as "this is safe" or "we know it's valid" cannot be checked, so it does not help a reviewer.
Also document any contract that remains for callers. If your public API is safe, there should be none.
Checking your wrapper
A wrapper can be wrong in ways that tests of normal use will not show. Three habits help:
- Write tests for edge inputs: empty slices,
mid == 0,mid == len, and zero-sized types. - Test the failure paths.
split_at_mut(&mut data, 99)should panic, not read memory. - Run the tests under Miri, covered later in this tutorial, which reports many violations that look fine at run time.
Exercise
The Bounded type above gets a new method pub fn set_len(&mut self, n: usize) { self.len = n; }. Is Bounded still sound? What is the smallest change that fixes it while keeping the method?
Show answer
No. A safe caller can write b.set_len(1000) and then b.get(500), and get_unchecked reads out of bounds, which is undefined behavior. The bug is in set_len, because it breaks the invariant len <= data.len() that get relies on. The smallest fix is to check the value first, with assert!(n <= self.data.len()); or by returning an Option or Result. Alternatively, make set_len an unsafe fn whose # Safety section requires n <= data.len().
Exercise
Why does split_at_mut call assert!(mid <= len) before the unsafe block instead of putting it inside a SAFETY comment only?
Show answer
A comment does not run. slice::from_raw_parts_mut requires the ranges to be valid, and the function is safe to call with any mid. Without the assert!, a caller passing a mid larger than len would cause undefined behavior from safe code. The assert! turns that case into a panic and makes the claim in the SAFETY comment true.