Skip to main content

encode_frame_with_max

Function encode_frame_with_max 

Source
pub fn encode_frame_with_max(
    frame: &Frame,
    max_frame_bytes: usize,
) -> Result<Vec<u8>, CodecError>
Expand description

Encode one frame against an explicit max_frame_bytes bound.

max_frame_bytes is PAYLOAD-ONLY: the maximum JSON payload length, not counting the 4-byte length prefix — the same bound decode_frame checks against.

Before serializing, the frame is validated against the same wire rules the decode side enforces (validate_frame_for_wire, private): an empty operation id in any id field (CodecError::InvalidFields), a handshake or handshake acknowledgment naming version 0 (CodecError::InvalidFields), an error frame whose id presence contradicts its code’s terminal scope (CodecError::InconsistentErrorScope), and a decoded unknown-code fallback error frame (CodecError::FallbackFrameNotEncodable) are all rejected here, so a frame this function accepts is one any conforming decoder accepts. This keeps encode and decode symmetric: a locally constructed frame that violates the grammar can never leave this crate as wire bytes.

Cost note: the size guard runs on the SERIALIZED payload, so the frame is fully serialized (and its bytes allocated) before the bound is checked; an oversized frame therefore pays one full serialization before CodecError::FrameTooLarge is returned. This is the accepted cost of a local, non-I/O encode: no cheaper pre-estimate of the serialized size exists without serializing.