Sub topic 14
Keeping unsafe small and reviewable
This chapter assumes you can write safe abstractions over unsafe code, document # Safety sections, and run Cargo commands. It covers how to arrange a project so that a reviewer can check its unsafe code quickly.
Why size matters
Inside an unsafe block, the compiler no longer proves memory safety for the operations you marked. A reviewer must then check those operations by hand. Reviewing 5 lines against a clear invariant is feasible. Reviewing 500 lines that rely on assumptions made elsewhere is not.
The goal is to make the unsafe surface small, and to make each piece's justification visible next to the code.
Shrink each block
Put only the operations that need unsafe inside the block. Compute values, check preconditions, and handle errors outside it. Prefer one unsafe operation per block, each with its own SAFETY: comment.
In an unsafe fn, the body is not automatically an unsafe block in modern Rust. Turn on the lint that enforces this, and ask Clippy to flag undocumented blocks:
#![deny(unsafe_op_in_unsafe_fn)]
#![warn(clippy::undocumented_unsafe_blocks)]
fn main() {
println!("lints enabled");
}In a crate with no unsafe code, use #![forbid(unsafe_code)]. The compiler then rejects any unsafe that someone adds later.
Let privacy hold the invariant
An unsafe block is only sound if some invariant is true. Make that invariant impossible to break from outside by using private fields and a checked constructor.
mod ascii {
pub struct Ascii(Vec<u8>);
impl Ascii {
pub fn new(bytes: Vec<u8>) -> Option<Ascii> {
if bytes.is_ascii() {
Some(Ascii(bytes))
} else {
None
}
}
pub fn as_str(&self) -> &str {
// SAFETY: the only constructor checks that every byte is ASCII,
// and the field is private, so the bytes are always valid UTF-8.
unsafe { std::str::from_utf8_unchecked(&self.0) }
}
}
}
fn main() {
let text = ascii::Ascii::new(b"hello".to_vec()).unwrap();
println!("{}", text.as_str());
}The reviewer reads only the ascii module. Code outside it cannot build an Ascii that holds non-ASCII bytes. Keep such modules small, because any code in the same module can touch the private field.
Isolate and review
Put unsafe code in its own module or crate, with a small public API. A common layout has a raw module that holds every unsafe block, and the rest of the crate stays safe.
[lints.rust]
unsafe_op_in_unsafe_fn = "deny"
[lints.clippy]
undocumented_unsafe_blocks = "warn"Run Miri on the tests that exercise the unsafe paths (cargo +nightly miri test). Run it in CI so that regressions are caught on every change.
Reviewer checklist
- Does each unsafe block have a
SAFETY:comment that names every requirement of the operation? - Can safe code outside the module break the invariant the comment relies on?
- Does each
unsafe fnhave a# Safetysection that a caller can act on? - Could the unsafe block be smaller, or replaced by a safe standard library function?
- Do tests cover the edge cases, such as empty slices, zero length, and maximum index?
Common errors
- A
SAFETY:comment that says "this is fine". It must state why each requirement holds. - A safe function that depends on a caller's promise. If misuse can cause undefined behavior, the function must be
unsafe. - Large unsafe blocks that hide a missing check in the middle.
Exercise
A safe method get_unchecked_wrapper(&self, i: usize) -> &u8 calls slice.get_unchecked(i) without checking i, and its doc says "callers must pass i < len". What is wrong, and what are two ways to fix it?
Show answer
A safe function must not cause undefined behavior for any input, and here a caller can pass i >= len using only safe code. Fix it either by adding assert!(i < self.len()) (or using get(i) and handling None) so the function stays safe, or by marking it unsafe fn with a # Safety section so callers take on the obligation.