Length-Prefixed Records and Incremental Parsing
Recover records from partial stream reads and bound the memory retained while an incomplete message arrives.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 2
- Reading time
- 1 min
In this article2 chapters
Parse a header before collecting the body
Suppose records start with a fixed-size unsigned length field followed by that many bytes. A receiver may obtain half the length field in one read and the rest later. Keep a small header state, decode under the specified byte order, and check the length against the protocol’s supported bounds. Then accumulate the body and pass it onward only once the complete record is available.
One read can cross several logical boundaries
Extra bytes after a body belong to the next header and must remain available. At end-of-stream, distinguish clean completion at a boundary from incomplete data. Retained buffers and waiting time should follow application limits. TCP stream semantics explains the independence of reads and sends. Canonical message parsing specifies which complete byte sequences represent a valid structured record.[1]