Reading Length-Prefixed Records
A length-prefixed format records the size of a payload before its bytes, so payload characters need not serve as delimiters.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace one record
A two-byte big-endian length of 0003 followed by bytes for abc yields one payload of three bytes. Read the next length only after those bytes. Unsigned length fields give the header its width and interpretation.
Check premature end
If the declaration is three and only ab arrives, report an incomplete record. An empty payload can be valid when length zero is supported. Boundary cases check both behaviors independently.[1]
Parse a stream whose first payload might contain separators
With a one-byte toy header, source 03 41 00 42 01 43 contains a three-byte payload and a one-byte payload. The zero in the first payload is ordinary data because its boundary comes from the count. The second header starts immediately after those three bytes. See reading a binary length.
Offset 0: length 3
Offsets 1–3: 41 00 42
Offset 4: length 1
Offset 5: 43
Use a clear check for truncated records
If the final byte is missing, the last header still declares one payload byte and cannot be silently dropped under a strict format. Reserve capacity only within documented limits. Test a short header for a multibyte format as well as a short payload.