In Rust, why does making the `len` field of a `MaybeUninit`-backed stack vector `pub` break soundness when no `unsafe` code changed?
answer
- who can write the field
- unsafe code trusts state
- the module is the boundary
- why Vec::set_len is unsafe
basics
~20 sThe unsafe code in as_slice and Drop trusts that buf[..len] is initialised. A pub len lets safe code in any module set it to any value, so safe code can cause undefined behaviour. Privacy is what keeps a safety invariant trustworthy.
solid answer
~40 sAn unsafe block is usually justified by a **safety invariant** stored in fields: here, `len <= N` and `buf[..len]` initialised. The unsafe code cannot check that invariant at run time, so it has to trust every piece of code that can write those fields. With a private field, that is the defining module and its descendants, which you can audit. With `pub len`, any safe code anywhere can write `v.len = 3`, and the next `as_slice` builds a slice over uninitialised slots: undefined behaviour reached from safe code, so the type is unsound. That is why std keeps `Vec`'s length private and exposes `set_len` only as an `unsafe fn` whose docs require `new_len <= capacity()` and initialised elements.
code
rust · 37 linesmod stackvec {
use std::mem::MaybeUninit;
pub struct StackVec<T, const N: usize> {
buf: [MaybeUninit<T>; N],
pub len: usize, // BUG: the safety invariant is now writable by anyone
}
impl<T, const N: usize> StackVec<T, N> {
pub fn new() -> Self {
StackVec { buf: [const { MaybeUninit::uninit() }; N], len: 0 }
}
pub fn push(&mut self, value: T) -> Result<(), T> {
if self.len >= N {
return Err(value);
}
self.buf[self.len].write(value);
self.len += 1;
Ok(())
}
pub fn as_slice(&self) -> &[T] {
// SAFETY: relies on buf[..len] being initialised and len <= N.
unsafe { std::slice::from_raw_parts(self.buf.as_ptr().cast::<T>(), self.len) }
}
}
}
use stackvec::StackVec;
fn main() {
let mut v: StackVec<u8, 4> = StackVec::new();
v.push(1).unwrap();
v.len = 3; // 100% safe code in another module
println!("{:?}", v.as_slice());
}go deeper
Recall that struct fields are private by default and that a private field cannot be written from outside its module; that is the tool unsafe code relies on.
Explain the chain: unsafe code trusts a field, so whoever can write the field is part of the proof. Show why pub len lets safe code cause undefined behaviour and why set_len is unsafe.
Show that the audit unit is the module and its descendants: one safe method that breaks the invariant makes the type unsound. Review constructors, Clone and Default impls, and every writer of the trusted fields.
Argue for a layout rule: invariant-carrying types live in small modules with private fields and documented invariants, so the reviewed surface stays small as the codebase grows.
## Safety invariants live in fields An unsafe block is rarely self-justifying. In a fixed-capacity stack vector that stores `[MaybeUninit<T>; N]` and a count, `as_slice` builds a `&[T]` with `slice::from_raw_parts(buf.as_ptr().cast::<T>(), len)`, and `Drop` calls `assume_init_drop` on the first `len` slots. Both are sound only if a **safety invariant** holds: - `len <= N`, so the slice stays inside the array; - every slot in `buf[..len]` holds an initialised `T`; - no slot at or above `len` is treated as initialised. Nothing at run time can verify the second point: `MaybeUninit<T>` carries no flag saying whether it holds a value. The unsafe code therefore has to **trust** that every write to `len` and `buf` preserved the invariant. ## Unsafety pollutes the whole module The Rustonomicon makes the uncomfortable point with a toy `Vec`: adding a perfectly safe method `make_room(&mut self) { self.cap += 1; }` makes the type unsound, because `push` trusts `cap`. Its conclusion is that unsafe code relying on a struct field's invariant "pollutes a whole module", and that "the only bullet-proof way to limit the scope of unsafe code is at the module boundary with privacy". Two consequences follow: 1. **Audit scope is the module, not the `unsafe` block.** Any safe line that writes `len` is part of the safety proof. 2. **Visibility decides who is inside that scope.** The Reference's rule is that a private item "may be accessed by the current module and its descendants", so a child `mod tests` can also write the field. ## What a `pub` field does Make `len` public and the audit scope becomes every crate that can name the type: ```rust let mut v: StackVec<u8, 4> = StackVec::new(); v.push(1).unwrap(); v.len = 3; // safe code, another module println!("{:?}", v.as_slice()); // reads two uninitialised bytes ``` No unsafe code changed, yet safe code now reaches undefined behaviour. On a native run the snippet printed `[1, 0, 0]`, which looks harmless; Miri reported "Undefined Behavior: reading memory ... but memory is uninitialized". Setting `v.len = 100` would make the slice run past the array. With the field private, the same assignment is rejected at compile time: "error[E0616]: field `len` of struct `StackVec` is private". The buffer is just as sensitive. A `pub buf` would let safe code write `v.buf[0] = MaybeUninit::uninit()` while `len` still counts that slot, de-initialising a value that `as_slice` and `Drop` will later read. Write access does not have to come from a field either: a safe method that returns `&mut usize` for the length, or `&mut [MaybeUninit<T>; N]` for the whole buffer, hands out exactly the same power as a `pub` field and breaks soundness the same way. ## How std draws the line std follows the same rule throughout: - `Vec<T>` stores `buf` and `len` in private fields; safe methods such as `push`, `truncate` and `clear` maintain the invariant. - `Vec::set_len` exists, but as an `unsafe fn` whose docs require that `new_len` is at most `capacity()` and that the elements at `old_len..new_len` are initialised. Writing an integer is harmless; writing *this* integer is a promise about memory. - Constructors such as `Vec::from_raw_parts` are `unsafe fn` for the same reason: they let the caller supply state the type will trust. | Who can write `len` | With a private field | With `pub len` | |---|---|---| | Methods in the defining module | Yes, and they are audited | Yes | | Child modules such as `mod tests` | Yes, also inside the audit | Yes | | Other modules in the crate | No | Yes | | Downstream crates | No | Yes, unaudited | ## A checklist for a sound container module - Keep every field that an unsafe block trusts **private**; `pub(crate)` widens the audit scope to the whole crate. - Establish the invariant in **every constructor**, including `Default`, `Clone` and `From` impls. - Re-check it in **every method of the module**, safe ones included. - Never return `&mut` to a trusted field from a safe method; that is a `pub` field by another name. - Expose raw-state setters only as `unsafe fn` with a `# Safety` section. - Document the invariant once, next to the struct, and point each `// SAFETY:` comment at it.
- Does a private field protect the invariant from code in the same module?No. Privacy only limits who can write the field to the defining module and its descendants, including a child `mod tests`. Every safe method there is part of the safety proof: the Rustonomicon's `make_room` example adds one safe line that bumps capacity and makes the whole type unsound. So the audit covers the module, not just the `unsafe` blocks.
- Why is `Vec::set_len` an `unsafe fn` when all it does is store a `usize`?Because that `usize` is the invariant other unsafe code trusts. Its docs require `new_len <= capacity()` and that the elements at `old_len..new_len` are initialised; a wrong value lets safe methods such as indexing, iteration or `Drop` touch uninitialised or out-of-bounds memory. Marking it `unsafe` moves that proof to the caller.
- Is `pub(crate)` on the invariant field acceptable?It can be sound, but the audit scope becomes every module in the crate, and any future safe write anywhere in it can break the type. Prefer a private field plus narrowly scoped methods, or an `unsafe fn` setter, so the code that must be reviewed stays in one module.
A pharmacy's controlled-drug register: every pharmacist trusts the count written in it. If anyone walking past can edit the register, the count means nothing, however careful the pharmacists are, so only staff behind the counter may write in it.
- Only the lines inside unsafe blocks need review for soundness.
- A pub field is fine if its documentation says not to change it.
- Private fields are hidden from child modules such as mod tests.
- pub(crate) keeps the audit scope to the defining module.
- Writing an integer field from safe code can never matter for memory safety.