Skip to main content

encode

Function encode 

Source
pub fn encode(payload: &[u8], output: &mut [u8]) -> Result<usize, SerialError>
Expand description

Encodes a payload into a COBS frame, terminated by the DELIMITER byte.

The encoded bytes are guaranteed to contain no zero except the trailing delimiter, so a receiver can split a stream into frames on the zero byte alone.

§Arguments

  • payload - the bytes to frame.
  • output - the buffer the frame is written into; size it with max_encoded_len.

§Returns

The number of bytes written to output, including the trailing DELIMITER.

§Errors

Returns SerialError::BufferTooSmall if output cannot hold the whole frame.

§Examples

use pamoja_serial::cobs;

// The canonical example: a single zero byte encodes to 01 01, then the 00 delimiter.
let mut frame = [0u8; 4];
let n = cobs::encode(&[0x00], &mut frame)?;
assert_eq!(&frame[..n], &[0x01, 0x01, 0x00]);