pub struct RingBuf<T: Copy, const N: usize> { /* private fields */ }Expand description
A ring buffer of N elements stored entirely on the stack.
Once full, new pushes overwrite the oldest entry. Iteration with
iter() yields elements from oldest to newest.
§Safety note
Slots are stored as MaybeUninit<T> so that T: Default is not required.
Exactly one invariant makes every read sound: the len entries ending at
head have all been written by push. Every read goes
through the private index helper, which addresses only that range, and
every public accessor checks len before calling it. A change that lets
len outrun the number of writes is undefined behaviour, not a logic bug.
Implementations§
Source§impl<T: Copy, const N: usize> RingBuf<T, N>
impl<T: Copy, const N: usize> RingBuf<T, N>
Sourcepub const fn new() -> Self
pub const fn new() -> Self
Create a new, empty ring buffer.
This is a const fn, so the buffer can be built in a const or
static initialiser. Note that push, pop, and clear take
&mut self, so a bare static RingBuf is read-only and of little use,
and static mut is a hard error to reference under edition 2024. The
pattern this actually enables is const-initialising the buffer inside
an interior-mutability wrapper, which is how a single-owner buffer is
reached from an interrupt context:
// with critical-section, cortex-m, or similar:
static LOG: Mutex<RefCell<RingBuf<u32, 64>>> =
Mutex::new(RefCell::new(RingBuf::new()));Without a const new that initialiser is impossible and you need a
StaticCell or a OnceCell and a runtime init step.
§Capacity 0 is a build failure
The N > 0 check is a const assertion, so a zero-capacity ring cannot
be constructed at all – there is no runtime panic left to catch, and
therefore no way to write the negative case as a #[test]
(zero_capacity_panics was deleted for exactly this reason). This
compile_fail doctest is that coverage, and pinning the error code
keeps it honest: a bare compile_fail would also pass on a typo.
let _ = ph_eventing::RingBuf::<u32, 0>::new();§Panics
Does not panic.
Sourcepub fn push(&mut self, val: T)
pub fn push(&mut self, val: T)
Append a value, overwriting the oldest entry once the ring is full.
This never fails and never blocks; if losing the oldest entry is not
acceptable, use crate::EventBuf, whose push reports when full.
Sourcepub fn is_full(&self) -> bool
pub fn is_full(&self) -> bool
Returns true if the ring is at capacity, so the next
push will overwrite the oldest entry.