progress

~/problems / Streams & durability / Serialization and durability

Length-prefixed encoding of a list of strings

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

To save a list of strings as bytes and get exactly the same list back, joining with a separator fails: a string might contain it. Instead, write each string's length first.

Implement encode(strings: list[str]) -> bytes and decode(data: bytes) -> list[str] with decode(encode(xs)) == xs for any strings (empty, newlines, NULs, non-ASCII). For each string, in order, write:

  1. its UTF-8 byte count as a 4-byte big-endian unsigned int: struct.pack(">I", n);
  2. its UTF-8 bytes.

Nothing else: no header, no count.

encode(["hi", ""])        # b"\x00\x00\x00\x02hi" + b"\x00\x00\x00\x00"
encode(["é"])             # b"\x00\x00\x00\x02\xc3\xa9"   ("é" is 1 character but 2 bytes)
decode(encode(["a,b", "line\nbreak"]))   # ["a,b", "line\nbreak"]
decode(b"")               # []

If data ends mid-length or mid-string, decode raises ValueError.

Show hint

walk an offset: struct.unpack_from(">I", data, offset), then slice exactly that many bytes, checking they're all there.

Topic: Serialization and durability. Length-prefixed encodings, write-ahead logs, checkpoints and recovery.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc