Lines
100 %
Functions
93.75 %
Branches
use thiserror::Error;
mod scan;
use scan::{Scan, Scanner};
#[derive(Debug, Error, PartialEq, Eq)]
pub enum FrameError {
#[error("frame contains invalid UTF-8")]
InvalidUtf8,
#[error("frame exceeds {MAX_FRAME_BYTES} bytes")]
TooLong,
#[error("malformed frame: {0}")]
Malformed(String),
}
/// Largest frame the decoder buffers. The decoder holds at most this plus one
/// fed chunk; after [`FrameError::TooLong`] it cannot resync.
pub const MAX_FRAME_BYTES: usize = 1_048_576;
#[derive(Debug, Default)]
pub struct FrameDecoder {
buf: String,
/// Tail of a UTF-8 character that the last chunk ended in the middle of.
pending: Vec<u8>,
/// A between-frame comment runs on into the next chunk.
in_comment: bool,
scanner: Option<Scanner>,
impl FrameDecoder {
#[must_use]
pub fn new() -> Self {
Self::default()
/// # Errors
/// `bytes` contain an invalid UTF-8 sequence; one cut off by the chunk end is kept for the next feed.
pub fn feed(&mut self, bytes: &[u8]) -> Result<(), FrameError> {
self.pending.extend_from_slice(bytes);
let valid = match std::str::from_utf8(&self.pending) {
Ok(_) => self.pending.len(),
Err(err) if err.error_len().is_none() => err.valid_up_to(),
Err(_) => {
self.pending.clear();
return Err(FrameError::InvalidUtf8);
};
let text =
std::str::from_utf8(&self.pending[..valid]).map_err(|_| FrameError::InvalidUtf8)?;
self.buf.push_str(text);
self.pending.drain(..valid);
Ok(())
pub fn next_frame(&mut self) -> Option<Result<String, FrameError>> {
if self.scanner.is_none() {
self.skip_leading();
if self.buf.is_empty() {
return None;
let scan = self
.scanner
.get_or_insert_with(Scanner::new)
.advance(self.buf.as_bytes());
match scan {
Scan::Complete(end) if end > MAX_FRAME_BYTES => Some(Err(self.overflow())),
Scan::Incomplete if self.buf.len() > MAX_FRAME_BYTES => Some(Err(self.overflow())),
Scan::Complete(end) => {
self.scanner = None;
let frame = self.buf[..end].to_string();
self.buf.drain(..end);
Some(Ok(frame))
Scan::Incomplete => None,
Scan::Invalid(msg) => {
self.reset();
Some(Err(FrameError::Malformed(msg)))
fn overflow(&mut self) -> FrameError {
FrameError::TooLong
fn reset(&mut self) {
self.buf.clear();
/// Drops whitespace and `;` comments before the next frame.
fn skip_leading(&mut self) {
let bytes = self.buf.as_bytes();
let mut i = 0;
while i < bytes.len() {
if self.in_comment {
match bytes[i..].iter().position(|&b| b == b'\n') {
Some(n) => i += n,
None => i = bytes.len(),
self.in_comment = i == bytes.len();
continue;
match bytes[i] {
b' ' | b'\t' | b'\n' | b'\r' => i += 1,
b';' => {
self.in_comment = true;
i += 1;
_ => break,
self.buf.drain(..i);
/// Byte length of the complete form that starts `s`, or `None` when it is incomplete or malformed.
pub(crate) fn form_len(s: &str) -> Option<usize> {
match Scanner::new().finish(s.as_bytes()) {
Scan::Complete(len) => Some(len),
Scan::Incomplete | Scan::Invalid(_) => None,
#[cfg(test)]
mod tests;