Message Framing — length-prefix (Go)
Topics: stream framing, length-prefix protocol, partial reads
Problem
TCP is a byte stream, not a message stream: one Read can return several messages, half a message,
or even half of a message's header. Implement length-prefixed framing so a stream of bytes can
be split back into discrete messages.
Each frame is a 4-byte big-endian length followed by that many payload bytes.
func Encode(payload []byte) []byte
type Decoder struct { /* … */ }
func (d *Decoder) Push(data []byte) [][]byte
Encode prefixes the payload with its length.
Push feeds an arbitrary chunk into the decoder and returns every frame that is now complete,
in order. Incomplete trailing bytes are buffered for the next Push. It must handle:
- several frames in one chunk,
- a payload split across chunks,
- a header (the 4 length bytes) split across chunks,
- empty frames (length 0).
Push(Encode("a") + Encode("bb")) → ["a", "bb"]
Push(half) → [] ; Push(rest) → ["whole"]
Key concepts
- Buffer until complete: keep leftover bytes; only emit a frame once both its 4-byte header and
full payload have arrived.
encoding/binary: binary.BigEndian.Uint32 / PutUint32 for the prefix.
- Copy emitted frames out of the rolling buffer so later appends don't alias them.
Run
go test -v ./challenges/message-framing/go/
Sign in to submit your solution.