LazyParse

Trait LazyParse 

Source
pub trait LazyParse: Send {
    // Required method
    fn try_parse_frame(
        &mut self,
        buf: &mut BytesMut,
    ) -> Result<(), Box<dyn Error>>;

    // Provided methods
    fn parse(
        &mut self,
        buf: &mut BytesMut,
        pattern: &[u8],
    ) -> Result<u8, Box<dyn Error>> { ... }
    fn bcc(&self, data: &[u8]) -> u8 { ... }
    fn find_first_two_matches(
        &self,
        buf: &[u8],
        pattern: &[u8],
    ) -> (Option<usize>, Option<usize>) { ... }
}
Expand description

A trait for parsing framed binary protocols with optional default implementations.

This trait defines a typical framing + checksum pattern for binary protocols. Types implementing this trait must provide try_parse_frame, and optionally override parse and helper methods.

Required Methods§

Source

fn try_parse_frame(&mut self, buf: &mut BytesMut) -> Result<(), Box<dyn Error>>

Attempts to parse one complete frame from the given buffer.

§Arguments
  • buf - A mutable reference to a BytesMut buffer containing the incoming stream data.
§Returns
  • Ok(()) if a frame was successfully parsed and processed.
  • Err if parsing fails or an incomplete frame is encountered.

Provided Methods§

Source

fn parse( &mut self, buf: &mut BytesMut, pattern: &[u8], ) -> Result<u8, Box<dyn Error>>

The default implementation for extracting and validating a frame.

This includes:

  • Searching for a valid header (pattern)
  • Calculating BCC (checksum)
  • Extracting length and validating buffer completeness
§Arguments
  • buf - The buffer to parse from.
  • pattern - A byte pattern representing the frame header, e.g., [0x55, 0xAA].
§Returns
  • Ok(bcc) if the frame is structurally valid and the buffer is large enough.
  • Err with a detailed error message otherwise.
Source

fn bcc(&self, data: &[u8]) -> u8

Computes XOR-based checksum (BCC) from a slice of bytes.

§Arguments
  • data - Byte slice to compute checksum for.
§Returns
  • A single-byte XOR checksum result.
Source

fn find_first_two_matches( &self, buf: &[u8], pattern: &[u8], ) -> (Option<usize>, Option<usize>)

Finds the positions of the first and second occurrences of a given byte pattern.

This is useful for detecting valid frame start boundaries and possibly the start of the next frame.

§Arguments
  • buf - The full buffer to search.
  • pattern - The byte pattern to match, e.g., [0x55, 0xAA].
§Returns
  • A tuple of (first_match_index, second_match_index); each is Option<usize>.

Implementors§