No. 36medium20 min12 tests

Delimited Stream Parser

Description

A socket or HTTP body hands you bytes in chunks of whatever size the network felt like. The protocol on top is message-oriented: messages are separated by a delimiter. Write the layer in between.

def parse_stream(chunks, delimiter: bytes = b"\n"):
    ...

chunks is any iterable of bytes. parse_stream is a generator that yields each message as bytes, without the delimiter.

  • A message or the delimiter itself may be split across any number of chunks. Chunks may be empty.
  • The delimiter may be several bytes long, such as b"<END>" or b"\r\n".
  • Consecutive delimiters produce empty messages. A delimiter at the very start produces a leading empty message.
  • After the input ends, yield any leftover bytes as a final message. If the input ends right after a delimiter, there is no final empty message.
  • ValueError if delimiter is empty (raised when iteration starts).

It must be lazy. Yield every complete message as soon as its delimiter arrives, and do not pull the next chunk from chunks until the caller asks for a message that needs it.

Example

list(parse_stream([b"hel", b"lo\nwor", b"ld\n", b"python"]))
# [b"hello", b"world", b"python"]

list(parse_stream([b"hello<E", b"N", b"D>wor", b"ld<", b"END", b">"], delimiter=b"<END>"))
# [b"hello", b"world"]

list(parse_stream([b"\nhello\n\nworld\n\n"]))
# [b"", b"hello", b"", b"world", b""]

Constraints

  • The stream can be unbounded. Memory should hold one chunk plus one incomplete message, never the whole stream.
  • Total work is linear in the input size. One message can be megabytes long and arrive in thousands of small chunks, and one chunk can hold thousands of messages. Do not rebuild or rescan the whole buffer for every chunk or every message.
  • Messages are arbitrary bytes. Do not decode them.

Solution

Reference solution and explanationTry it first. The explanation covers the approach, complexity, pitfalls and follow-ups.
Reveal solution

Approach

Keep a bytearray buffer of the bytes after the last delimiter seen. For each chunk, append it to the buffer and search for the delimiter with buffer.find(delimiter, start). Each hit is a complete message: yield the bytes before it and delete it plus the delimiter from the front of the buffer. When no delimiter is left, whatever remains waits for the next chunk.

The interesting part is start. The old buffer had no delimiter in it, so there is no point scanning it again, except for its last len(delimiter) - 1 bytes. Those may be the first half of a delimiter whose second half is in the new chunk: b"hello<E" plus b"N" plus b"D>" only matches once the last chunk arrives. So start = max(0, len(buffer) - len(delimiter) + 1) is computed before appending. After a hit the buffer starts fresh, so start goes back to 0.

At the end, a non-empty buffer is the final message. When the stream ends with a delimiter the buffer is empty, which is exactly the "no final empty message" rule.

Laziness comes from the generator. The inner while yields every complete message in the buffer before the for loop asks chunks for the next one.

Complexity

O(n) total work. Each new byte is scanned a constant number of times. bytearray += grows in place, and CPython deletes from the front of a bytearray by moving its start offset, not by shifting the rest. Memory is one chunk plus the current incomplete message.

Pitfalls

  • Searching for the delimiter in each chunk on its own, or resuming the search at the old buffer length. Both miss a delimiter split across chunks.
  • *messages, pending = (pending + chunk).split(delimiter). Correct and short, but every chunk copies and rescans the whole pending message. A 2 MB message in 256-byte chunks takes seconds.
  • buffer = buffer[end + len(delimiter):] on bytes. Every message copies the rest of the chunk, so one big chunk of small messages is quadratic.
  • Yielding a trailing b"" when the stream ends with a delimiter, or dropping a real final message that has no delimiter.
  • Treating an empty chunk as end of stream. Only exhausting the iterator ends it.
  • No cap on message size. A peer that never sends a delimiter grows the buffer without bound.

Follow-ups interviewers ask

  • Add max_message_size and raise once the buffer exceeds it, so a misbehaving peer cannot exhaust memory.
  • Make it async: async for chunk in chunks, and the body stays the same. asyncio.StreamReader.readuntil does this for sockets.
  • Decode UTF-8 text lines. Decode only complete messages, or use codecs.getincrementaldecoder, because a multi-byte character can straddle chunks.
  • How does this compare with length-prefixed framing? A length prefix lets you read exactly n bytes and allows the delimiter inside payloads.

Reference solution

def parse_stream(chunks, delimiter: bytes = b"\n"):
    if not delimiter:
        raise ValueError("delimiter must not be empty")

    buffer = bytearray()
    for chunk in chunks:
        # Only bytes that could complete a delimiter straddling the old tail need rescanning.
        start = max(0, len(buffer) - len(delimiter) + 1)
        buffer += chunk
        while (end := buffer.find(delimiter, start)) != -1:
            yield bytes(buffer[:end])
            # Deleting from the front of a bytearray is cheap: CPython just moves its start offset.
            del buffer[:end + len(delimiter)]
            start = 0
    if buffer:
        yield bytes(buffer)

Notes

solution.pySaved
def parse_stream(chunks, delimiter: bytes = b"\n"):
    """
    Yield the messages in an iterable of byte chunks, split on delimiter (not included).
    Leftover bytes at the end form a final message. ValueError if delimiter is empty.
    """
    raise NotImplementedError
Python loads on first run

Run checks the 2 example tests. Submit runs all 12 and marks the problem solved when they pass.