expression

Encapsulate a fixed-capacity initialized prefix

This small buffer hides raw slots from callers. Its invariant is that indices below len hold live values and all other slots are logically empty. push checks capacity before writing, pop removes ownership before returning a value, and Drop cleans remaining elements. No references to uninitialized slots escape. This is a teaching abstraction, not a production container; panicking element destructors may leak the remaining elements, and independent soundness review is required. Expected stdout (not executed): full=true last=b first=a empty=true Common mistake: Exposing the raw slots publicly or updating length before initialization.

Formal Syntax & Structure

rust syntaxrust
struct Buffer<T, const N: usize> { slots: [MaybeUninit<T>; N], len: usize }

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    use std::mem::MaybeUninit;    struct Buffer<T, const N: usize> { slots: [MaybeUninit<T>; N], len: usize }    impl<T, const N: usize> Buffer<T, N> {        fn new() -> Self { Self { slots: [const { MaybeUninit::uninit() }; N], len: 0 } }        fn push(&mut self, value: T) -> Result<(), T> {            if self.len == N { return Err(value); }            self.slots[self.len].write(value);            self.len += 1;            Ok(())        }        fn pop(&mut self) -> Option<T> {            if self.len == 0 { return None; }            self.len -= 1;            // SAFETY: the old last slot was initialized; it is now excluded from len.            Some(unsafe { self.slots[self.len].assume_init_read() })        }    }    impl<T, const N: usize> Drop for Buffer<T, N> {        fn drop(&mut self) {            while self.len > 0 {                self.len -= 1;                // SAFETY: this index was part of the live prefix and is now removed.                unsafe { self.slots[self.len].assume_init_drop(); }            }        }    }    let mut b = Buffer::<String, 2>::new();    b.push("a".into()).unwrap();    b.push("b".into()).unwrap();    println!("full={}", b.push("c".into()).is_err());    println!("last={}", b.pop().unwrap());    println!("first={}", b.pop().unwrap());    println!("empty={}", b.pop().is_none());}
Rust Reference