Message Framing — length-prefix (C)
Topics: stream framing, length-prefix protocol, partial reads
Problem
A stream delivers bytes in arbitrary chunks. Frame messages with a 4-byte big-endian length
prefix, and reassemble them on the decode side.
size_t frame_encode(const unsigned char *payload, size_t len, unsigned char *out); // bytes written
typedef struct { unsigned char *buf; size_t cap; size_t len; } Decoder;
void dec_init(Decoder *d, unsigned char *buf, size_t cap);
void dec_push(Decoder *d, const unsigned char *data, size_t n,
void (*on_frame)(const unsigned char *frame, size_t len, void *ctx), void *ctx);
dec_push appends bytes into the scratch buffer and calls on_frame for each complete frame —
handling several frames in one chunk, a payload split across chunks, a header split across chunks,
and empty frames. The frame pointer is valid only during the callback.
Key concepts
- Buffer until complete: only emit a frame once both its 4-byte header and full payload have
arrived;
memmove the unconsumed tail to the front afterward.
- Big-endian length: assemble with
(b[0]<<24)|(b[1]<<16)|(b[2]<<8)|b[3] using uint32_t to
avoid sign issues.
- Callback to "yield many": C's stand-in for returning a list — one call per frame, with a
user
ctx.
Run
cc -std=c11 -O2 -Wall tests.c -o /tmp/fr && /tmp/fr
Sign in to submit your solution.