Answer#
unsafe means: "the compiler cannot prove this is sound, and I take responsibility". The comment is where that responsibility is written down, so a reviewer can check it. A good comment states the specific condition and where it was established, not "this is fine".
/// Return the byte at `i`, or None when `i` is out of range.
fn byte_at(data: &[u8], i: usize) -> Option<u8> {
if i >= data.len() {
return None;
}
// SAFETY: `i < data.len()` was checked on the lines above, so the index is in bounds.
Some(unsafe { *data.get_unchecked(i) })
}
fn main() {
let data = [1u8, 2, 3];
println!("{:?} {:?}", byte_at(&data, 2), byte_at(&data, 3));
}Some(3) NoneThe block uses get_unchecked, which skips the bounds check; the comment names the condition (i < data.len()) and points to the lines that check it. If someone later deletes the if, the comment makes the mistake visible.
How to review one#
- Which condition does this operation require? (Pointer valid and aligned, index in range, value initialised, no overlapping mutable access, valid UTF-8, and so on. The documentation of the unsafe function lists them under "Safety".)
- Is that condition guaranteed by the code around it, for every possible input, including empty input and extreme values?
- Could another safe function in the same module break the condition (for example by changing a length field)? If so, the invariant belongs to the whole module: write it down and keep the fields private.
- Is there a safe alternative that is fast enough?
getinstead ofget_uncheckedis usually the answer; measure before choosing the unchecked form. - Is there a test that would fail if the condition were broken?
Tools#
- Clippy has an optional lint
clippy::undocumented_unsafe_blocksthat warns when anunsafeblock has no// SAFETY:comment. Enable it in the crate with#![warn(clippy::undocumented_unsafe_blocks)]. It is listed in the Clippy lint index; this thread did not run it. - Miri is an interpreter that runs your tests and reports many kinds of undefined behaviour. It needs a nightly toolchain component:
cargo +nightly miri test. It was not available on the toolchain used for this thread and was not run. Read its README for its limits: it checks what the test executes, nothing more. - Sanitizers and fuzzing (see the thread on fuzzing) find bugs that tests with expected inputs miss.
Common mistakes#
- Comments that restate the code ("SAFETY: we dereference the pointer").
- A comment on the block but no
# Safetysection on the function, so callers do not know what they promised. - Treating Miri as proof. It finds problems; a clean run does not show their absence.
Related questions#
Who is responsible when a safe function wraps unsafe code?#
The author of the wrapper. A safe function must be sound for all inputs. If it is not, it must be marked unsafe.
Do I need a SAFETY comment on a block inside a test?#
The lint applies to tests too if enabled. Keeping the habit costs little, and tests are where such code is first exercised.
Sources#
- The Rustonomicon, "Working with Unsafe": https://doc.rust-lang.org/nomicon/working-with-unsafe.html
- Rust API Guidelines, documentation section: https://rust-lang.github.io/api-guidelines/documentation.html
- Clippy lint
undocumented_unsafe_blocks: https://rust-lang.github.io/rust-clippy/master/index.html#undocumented_unsafe_blocks - Miri: https://github.com/rust-lang/miri