expression
Collect UART bytes in a bounded line buffer
UART supplies a byte stream, not text messages. This fixed-capacity collector treats LF as a delimiter and returns an error on overflow. After overflow it discards bytes until the next LF so the suffix of an oversized record cannot become a new valid message. Returned data is borrowed until the next mutable operation; UTF-8 is a separate concern. Expected host stdout (not executed): overflow line: ok Common mistake: Accepting the trailing fragment of a discarded oversized line or allocating without a bound.
Formal Syntax & Structure
rust syntaxrust
push(byte) -> Result<Option<&[u8]>, ()>Working Example
Example Snippetrust
#![no_std]pub struct Lines { buf: [u8; 4], len: usize, discard: bool }impl Lines { pub const fn new() -> Self { Self { buf: [0; 4], len: 0, discard: false } } pub fn push(&mut self, byte: u8) -> Result<Option<&[u8]>, ()> { if self.discard { if byte == b'\n' { self.discard = false; } return Ok(None); } if byte == b'\n' { let end = self.len; self.len = 0; return Ok(Some(&self.buf[..end])); } if self.len == self.buf.len() { self.len = 0; self.discard = true; return Err(()); } self.buf[self.len] = byte; self.len += 1; Ok(None) }}