[][src]Crate const_buffer

A fixed-capacity memory buffer allocated on the stack using const generics.

This is a low-level utility, useful for implementing higher-level data structures such as fixed-capacity vectors and ring buffers. Since ConstBuffer's main purpose is to build safe abstractions on top of, almost its entire API surface is unsafe.

ConstBuffer does not keep track of which elements are in an initialized state. Furthermore, in order to ensure optimal performance, no bounds checks are performed unless debug assertions are enabled. Any misuse of this crate leads to undefined behavior.

Building a fixed-capacity vector on top of ConstBuffer is pretty straightforward:

struct ConstVec<T, const N: usize> {
    buffer: ConstBuffer<T, N>,
    len: usize,
}

impl<T, const N: usize> ConstVec<T, N> {
    fn new() -> Self {
        Self { buffer: ConstBuffer::new(), len: 0 }
    }

    fn push(&mut self, value: T) {
        assert!(self.len < N);
        unsafe {
            self.buffer.write(self.len, value);
            self.len += 1;
        }
    }

    fn pop(&mut self) -> Option<T> {
        if self.len > 0 {
            unsafe {
                self.len -= 1;
                Some(self.buffer.read(self.len))
            }
        } else {
            None
        }
    }

    fn as_slice(&self) -> &[T] {
        unsafe { self.buffer.get(..self.len) }
    }

    fn get(&self, index: usize) -> Option<T> {
        if index < self.len { Some(unsafe { self.buffer.read(index) }) } else { None }
    }
}

Structs

ConstBuffer

A fixed-capacity buffer allocated on the stack using const generics.

Traits

BufferIndex

A helper trait that generalizes over positions and ranges to be used as a trait bound for get and get_mut.

UninitWrapper

A helper trait that generalizes over MaybeUninit<T> and [MaybeUninit<T>] for the purpose of making get and get_mut work with both positions and ranges.