Sub topic 14
Keeping unsafe small and reviewable
This chapter assumes you have read the earlier chapters on safety contracts, safe abstractions, and Miri. You should be comfortable writing an unsafe block with a SAFETY comment and running cargo miri test. Here the question changes from "how do I write unsafe code" to "how do I arrange a project so that unsafe code stays correct as it changes".
Why size matters
The compiler cannot check unsafe code, so every bug in it must be found by a person or a tool. People find bugs by reading, and reading is only reliable when the reader can hold the whole argument in their head. A reviewer who has to check 300 lines of unsafe code across five files will skim. A reviewer who checks one three-line block and a nearby comment will not.
Two quantities are worth minimizing:
- Surface: how many lines are inside
unsafeblocks, and how many functions areunsafe. - Distance: how far the code that establishes a fact is from the code that relies on it.
A bug in unsafe code is often not in the unsafe block itself. A safe line elsewhere in the module may break an assumption the block depends on. This is why the unit of review is the module, not the block.
Shrink the block
An unsafe block should contain only the operations that need it. Compute, validate, and convert in safe code first, then enter unsafe for one operation.
fn zero_prefix(buf: &mut [u8], n: usize) {
// Safe code decides how many bytes to touch.
let n = n.min(buf.len());
let p = buf.as_mut_ptr();
// SAFETY: `n <= buf.len()`, so `p..p + n` lies inside `buf`,
// and `buf` is an exclusive borrow, so the writes cannot race or alias.
unsafe { p.write_bytes(0, n) };
}
fn main() {
let mut data = [1u8, 2, 3, 4, 5];
zero_prefix(&mut data, 3);
println!("{:?}", data);
zero_prefix(&mut data, 100);
println!("{:?}", data);
}The min call is outside the block. A reader sees that the length is clamped, then sees one unsafe call that depends on exactly that fact.
Avoid wrapping a whole function body in unsafe { ... }. Doing so makes every line look suspicious, which hides the lines that really are. It also lets a later edit add a second unsafe operation without anyone noticing.
One operation, one comment
A good rule is one unsafe operation per block, and one SAFETY comment per block. If a block needs several operations, each with its own justification, split it. A comment that says "all of this is fine" is a sign that nobody listed what "this" includes.
Put the invariant behind a module boundary
The strongest tool for keeping unsafe code reviewable is privacy. If a type has a private field that must satisfy an invariant, only code in the same module can break it. The reviewer's job shrinks to that module.
mod cursor {
pub struct Cursor<'a> {
data: &'a [u32],
// Invariant: `pos < data.len()`. Only this module can change it.
pos: usize,
}
impl<'a> Cursor<'a> {
pub fn new(data: &'a [u32]) -> Option<Self> {
if data.is_empty() {
None
} else {
Some(Cursor { data, pos: 0 })
}
}
pub fn current(&self) -> u32 {
// SAFETY: `new` establishes `pos < data.len()` (data is non-empty,
// pos is 0) and `advance` is the only code that changes `pos`;
// it preserves the invariant.
unsafe { *self.data.get_unchecked(self.pos) }
}
pub fn advance(&mut self) -> bool {
if self.pos + 1 < self.data.len() {
self.pos += 1;
true
} else {
false
}
}
}
}
fn main() {
let values = [10, 20, 30];
let mut c = cursor::Cursor::new(&values).unwrap();
println!("{}", c.current());
while c.advance() {
println!("{}", c.current());
}
}The SAFETY comment names where the invariant is created and where it could be broken. A reviewer can check new and advance and be done. If someone adds a pub fn seek(&mut self, pos: usize) that skips the check, the comment is now false, and the reviewer has a concrete thing to compare against.
This example is for teaching. In real code, self.data[self.pos] costs one bounds check and is almost always fast enough. Reach for unchecked access only after measuring.
<br>
Prefer a tested abstraction to new unsafe
Before writing unsafe code, check whether someone has already written and audited it. Often the standard library has what you need:
| You want to | Instead of raw unsafe, try |
|---|---|
| Split a slice into two mutable parts | `split_at_mut`, `chunks_mut` |
| Read an unaligned integer | `u32::from_le_bytes`, `ptr::read_unaligned` |
| Swap or replace through a reference | `mem::swap`, `mem::replace`, `mem::take` |
| Delay initialization | `OnceLock`, `LazyLock`, `MaybeUninit` only as a last resort |
| Share mutable state | `Mutex`, `RwLock`, atomics, `Cell`, `RefCell` |
| Reinterpret bytes as a type | A crate such as `bytemuck`, which checks the preconditions |
Each row replaces a custom argument with one that has been reviewed by many people. If you still need your own unsafe code, put it in a small dedicated module or crate so the review can be scoped to it.
Make the tools enforce the rules
Habits fail under deadline pressure. Compiler and Clippy lints do not.
// At the top of lib.rs or main.rs.
#![deny(unsafe_op_in_unsafe_fn)]
#![warn(clippy::undocumented_unsafe_blocks)]
#![warn(clippy::missing_safety_doc)]
/// Reads the first byte of a slice without a bounds check.
///
/// # Safety
///
/// `bytes` must not be empty.
pub unsafe fn first_unchecked(bytes: &[u8]) -> u8 {
// SAFETY: the caller guarantees `bytes` is not empty.
unsafe { *bytes.get_unchecked(0) }
}
fn main() {
let data = [7u8, 8, 9];
// SAFETY: `data` has three elements, so it is not empty.
let b = unsafe { first_unchecked(&data) };
println!("{b}");
}What each lint gives you:
unsafe_op_in_unsafe_fnmakes the body of anunsafe fnrequire explicitunsafeblocks. Without it, the whole function body is one large unsafe region, which is the opposite of what this chapter recommends. In the 2024 edition it warns by default.clippy::undocumented_unsafe_blocksflags anyunsafeblock without a// SAFETY:comment.clippy::missing_safety_docflags publicunsafe fnitems without a# Safetysection.
Crates that need no unsafe code at all should say so:
#![forbid(unsafe_code)]
fn main() {
println!("no unsafe here, and the compiler will keep it that way");
}forbid cannot be overridden by an inner #[allow], so a future contributor who adds an unsafe block gets a compile error and must remove the attribute deliberately, which a reviewer will see.
Test the boundary, run Miri on it
A safe API over unsafe code should be tested with inputs at the edge of its contract. Empty slices, mid == 0, mid == len, zero-sized types, and the largest index are the usual places for mistakes. Normal tests often pass on code with undefined behavior, because the optimizer has not yet exploited it. Miri reports the problem anyway.
fn split_first_half(values: &mut [i32]) -> (&mut [i32], &mut [i32]) {
let mid = values.len() / 2;
values.split_at_mut(mid)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_slice() {
let mut v: [i32; 0] = [];
let (a, b) = split_first_half(&mut v);
assert!(a.is_empty() && b.is_empty());
}
#[test]
fn odd_length() {
let mut v = [1, 2, 3];
let (a, b) = split_first_half(&mut v);
a[0] = 9;
b[0] = 8;
assert_eq!(v, [9, 8, 3]);
}
}
fn main() {
let mut v = [1, 2, 3, 4];
let (a, b) = split_first_half(&mut v);
a[0] = 0;
b[0] = 0;
println!("{:?}", v);
}Run the tests under Miri in CI, not only on your machine:
rustup +nightly component add miri
cargo +nightly miri testMiri only checks the paths your tests execute. It does not prove the absence of undefined behavior, so it complements the safety argument and does not replace it.
A review workflow
The following flow works for reviewing one unsafe block, whether you wrote it or someone else did.
Questions to ask in review:
- Which operation from the five is this, and what does its documentation require?
- Does the comment say why the requirement holds here, or does it only say that it holds?
- Could a panic between establishing a fact and using it leave a value half-built? Drop code that runs during unwinding can see broken invariants.
- Does the code behave correctly for zero-sized types, empty inputs, and maximum sizes?
- If the type is generic, does the argument still hold for every
T, including types with a customDropor interior mutability? - Is the abstraction sound for any safe caller, or only for the callers that exist today?
The last question is the main test. Soundness means no safe code can cause undefined behavior through your API. "It works with how we call it" is not soundness, and it breaks as soon as someone adds a new caller.
<br>
Common mistakes
- Comment drift. A
SAFETYcomment is correct on the day it is written. Treat a change to anything it mentions as a change to the comment too. - Checking in a different place than using. A
debug_assert!disappears in release builds. If safety depends on the check, useassert!, or return an error. - Hiding unsafe behind a macro. A macro that expands to
unsafeat every call site spreads the review area to every caller. Prefer a function. - Marking a function
unsafeto avoid thinking. Anunsafe fnpushes the proof onto every caller. If the function can check its own preconditions cheaply, make it safe and check. - Adding
unsafe impl Sendto silence an error. Treat the compiler error as information. The type contains something that is not thread-safe, and the impl needs the same argument as any other unsafe code.
Summary
Keep each unsafe block to one operation, with safe code doing the setup. Put invariants in private fields so the review area is a module. Choose existing audited abstractions before writing new ones. Turn on lints that demand SAFETY and # Safety documentation, use #![forbid(unsafe_code)] where possible, and run boundary tests under Miri in CI. In review, ask whether any safe caller could break the contract, not whether current callers do.
Exercise
A teammate submits a function with a 40-line unsafe block. It parses a header from a &[u8], computes a length, then calls slice::from_raw_parts(ptr.add(8), len). The only comment says // SAFETY: this is fine. List three concrete changes you would ask for.
Show answer
(1) Move parsing and length computation out of the unsafe block so that only from_raw_parts (and add, if it is not covered by the same argument) remain inside. (2) Add an assert! or return an error if 8 + len > bytes.len(), because the call needs the range to lie inside the original allocation. Use assert!, not debug_assert!, since safety depends on it. (3) Replace the comment with a real argument: name the preconditions of from_raw_parts (non-null, aligned, valid for len reads, initialized, not mutated for the lifetime) and say which line establishes each. Optionally, add a test with a header that claims a length larger than the buffer, and run it under Miri.
Exercise
A struct Buf { ptr: *mut u8, len: usize } has both fields pub. Its get(&self, i: usize) -> u8 method does unsafe { *self.ptr.add(i) } after checking i < self.len. Is get sound? Explain.
Show answer
No. Because the fields are public, safe code anywhere can build a Buf with a dangling ptr or a len larger than the allocation, then call get and cause undefined behavior. The i < self.len check is only meaningful if len is trustworthy, and public fields remove that guarantee. Make the fields private, provide a constructor that establishes the invariant (or an unsafe fn from_raw_parts that documents it), and write the SAFETY comment around that invariant.
Exercise
Which lint should you enable to make the compiler reject an unsafe operation in the body of an unsafe fn unless it sits in its own unsafe block, and why does that help review?
Show answer
unsafe_op_in_unsafe_fn (set to deny). Without it, the body of an unsafe fn is treated as one unsafe region, so every operation is unchecked and none needs its own SAFETY comment. With it, each unsafe operation is visibly marked and can be reviewed and documented individually.