Lesson 5 of 9 · 28m
Unsafe Rust When It Is Actually Justified
Use unsafe to implement invariants the compiler cannot verify, isolate it behind safe APIs, and document the proof obligations.
Unsafe Rust is not a license to write C with a different logo. It is a mechanism for implementing abstractions whose correctness depends on invariants the compiler cannot express. If you cannot state those invariants in one paragraph, you are not ready to write the unsafe block. If you can state them but cannot keep them local, the abstraction is wrong.
The correct unsafe shape
The durable pattern is small unsafe core, safe public shell:
pub struct Slab {
buf: Vec<u8>,
}
impl Slab {
pub fn write_at(&mut self, index: usize, value: u8) -> Result<(), Error> {
if index >= self.buf.len() {
return Err(Error::OutOfBounds);
}
unsafe {
// SAFETY: bounds checked above; index is within the allocation.
*self.buf.as_mut_ptr().add(index) = value;
}
Ok(())
}
}The invariant is local and checkable: index < len. The unsafe block does not leak proof obligations to callers. In real code, prefer safe indexing unless measurement proves the bounds check matters; the example shows the shape, not a recommendation to sprinkle raw pointers everywhere.
Justifications that survive review
Good reasons include FFI, memory-mapped device access, custom allocators, pinning internals, intrusive data structures, performance-critical code with measured benefit, and implementing synchronization primitives. Bad reasons include "the borrow checker was annoying," "I saw this in a forum," and "it is probably faster."
Every unsafe block needs a SAFETY comment that names the invariant and why it holds. Not poetry. Proof:
// SAFETY: `ptr` comes from `Vec::as_mut_ptr` for the same allocation,
// len bytes are initialized, and no other reference to this region exists
// for the duration of the write because `self` is exclusively borrowed.Undefined behavior is not theoretical
The failure mode is not always an immediate crash. Misaligned reads, invalid references, aliasing violations, use-after-free, invalid enum values, and data races can produce behavior that depends on optimization level, compiler version, architecture, or seemingly unrelated changes. That is why unsafe review is architectural review.
Validate boundaries aggressively
At the edge of unsafe code, validate everything:
pointer alignment and provenance
allocation size and length units
initialization state
aliasing and exclusive access
thread safety and Send/Sync claims
panic paths and drop orderIf callers can pass lengths, indexes, file descriptors, or pointers, assume they will eventually pass nonsense. Make nonsense fail safely before entering the invariant-preserving region.
Use Miri and sanitizers where applicable
Miri catches undefined behavior in many pure Rust cases:
cargo +nightly miri testIt does not support every FFI or OS interaction, but when it runs, it is one of the highest-value checks available. Also run stress tests under thread sanitizer or loom for concurrency primitives. Unsafe code that only works in the happy-path unit test is not close to done.
Field notes
unsafeon a function means callers may need to uphold invariants;unsafeinside a safe function means the function must encapsulate them.- Do not mark a module unsafe to reduce friction. Small blocks make review possible.
transmuteis almost never the first answer. Lifetime, layout, and enum validity mistakes hide there.- If a safe abstraction is impossible without global reasoning, redesign the ownership boundary instead of expanding unsafe.
Was this lesson helpful?