expression

Build a fixed-capacity FIFO ring queue

A ring queue reuses array slots as items are removed. This small single-owner byte queue has an explicit full condition and rejects a new item without overwriting existing data. Capacity zero is supported as always full. It is not a concurrent ISR queue; concurrent access requires a reviewed synchronization protocol. Expected host stdout (not executed): first: Some(4) remaining: Some(5) Some(6) None Common mistake: Silently discarding an existing item when the queue is full or sharing the queue between an ISR and main without synchronization.

Formal Syntax & Structure

rust syntaxrust
push(&mut self, value: u8) -> Result<(), u8>; pop(&mut self) -> Option<u8>

Working Example

Example Snippetrust
#![no_std]pub struct Queue<const N: usize> { data: [u8; N], head: usize, len: usize }impl<const N: usize> Queue<N> {    pub const fn new() -> Self { Self { data: [0; N], head: 0, len: 0 } }    pub fn push(&mut self, value: u8) -> Result<(), u8> {        if self.len == N { return Err(value); }        let remaining = N - self.head;        let tail = if self.len < remaining { self.head + self.len } else { self.len - remaining };        self.data[tail] = value; self.len += 1; Ok(())    }    pub fn pop(&mut self) -> Option<u8> {        if self.len == 0 { return None; }        let value = self.data[self.head];        self.head = if self.head == N - 1 { 0 } else { self.head + 1 };        self.len -= 1; Some(value)    }}
Rust Reference