Sound safe wrappers
Quick answer
A sound safe wrapper hides an unsafe implementation behind an interface that cannot violate memory safety when called by safe clients. Its correctness depends on the entire API, not just one unsafe block.
Check every public path
Use private fields, explicit invariants, safe construction and validation before the unsafe region. Think about empty inputs, errors, mutation, panics, destructor order and concurrent access. This wrapper demonstrates an in-bounds check with a local proof. It is intentionally simpler than a production abstraction, and the standard get method is preferable for this task.
fn byte_at(data: &[u8], i: usize) -> Option<u8> { if i >= data.len() { return None; } // SAFETY: i < len; the shared slice holds initialized bytes during the read. Some(unsafe { *data.get_unchecked(i) })}fn main() { println!("{:?} {:?}", byte_at(b"ab", 1), byte_at(b"ab", 2)); }Expected stdout (not executed):
Some(98) NoneSafe callers cannot bypass the check.
fn first(data: &[u8]) -> Option<u8> { data.first().copied() }fn main() { println!("{:?} {:?}", first(b""), first(b"A")); }Expected stdout (not executed):
None Some(65)The safe standard-library alternative covers empty and nonempty inputs.
Common mistake
A private unsafe function is not automatically sound; every path to it must uphold its contract.
Try it yourself
Test index zero, the last index, the length and usize::MAX using the safe wrapper.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Sound safe wrappers — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A safe wrapper returns a slice over internal partially initialized storage. What must it ensure?
Sound safe wrappers — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn byte_at(data: &[u8], i: usize) -> Option<u8> { if i >= data.len() { return None; } // SAFETY: i < len; the shared slice holds initialized bytes during the read. Some(unsafe { *data.get_unchecked(i) }) } fn main() { println!("{:?} {:?}", byte_at(b"ab", 1), byte_at(b"ab", 2)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Sound safe wrappers — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn first(data: &[u8]) -> Option<u8> { data.first().copied() } fn main() { println!("{:?} {:?}", first(b""), first(b"A")); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.