Reassemble Framed Messages from Chunked Byte Streams
StringsAuto-graded · 20 test casesLast updated
Join byte chunks from a simulated stream and split them into complete messages, using either a 4-byte length prefix or newline delimiters, while ignoring any incomplete tail.
Reassemble Framed Messages from Chunked Byte Streams
A network connection delivers a continuous stream of bytes, and the receiver sees that stream cut into arbitrary pieces. A piece can be empty, can end in the middle of a message, or can contain several messages. You are given the pieces in arrival order and must recover the complete messages they carry.
Bytes are represented as integers from 0 to 255.
Task
Implement a function that takes:
chunks: a list of pieces, in arrival order. Each piece is a list of byte values (possibly empty).mode: a string naming the framing rule.
It returns the list of complete messages in stream order. Each message is a list of byte values.
Conceptually, concatenate all pieces into one stream, then parse it from the start according to mode.
Framing modes
"length_prefixed"
- Each message begins with a 4-byte header: an unsigned integer in big-endian order giving the payload length
n. - The
npayload bytes follow the header immediately. - The returned message is the payload only, without the header.
- A message with
n = 0is valid and yields an empty list[]. - Parsing stops at the first message that is not fully present. That means either fewer than 4 header bytes remain, or fewer than
npayload bytes follow the header. That incomplete tail is ignored and produces no output.
"newline"
- A message is the run of bytes ending at a newline byte (value
10). - The newline is a delimiter and is not part of the message.
- Consecutive newlines produce empty messages
[]. - No other byte, including carriage return (
13), is treated specially. - Bytes after the last newline form an unfinished line. It is ignored and produces no output.
Other rules
- If
modeis neither"length_prefixed"nor"newline", raise aValueError. - If the stream is empty, or contains no complete message, return an empty list.
- The boundaries between pieces carry no meaning. Only the concatenated stream matters.
Constraints
0 <= len(chunks), and each piece may have length0.- Every byte value is an integer in
[0, 255]. - The total number of bytes is small enough to hold in memory.
- In
"length_prefixed"mode, the header is always read as a 4-byte big-endian unsigned integer. - The returned list contains messages in the order they appear in the stream.
Examples
Example 1
Input: reassemble_frames([[0, 0, 0, 3, 97], [98, 99, 0, 0, 0, 1, 120]], 'length_prefixed')
Output: [[97, 98, 99], [120]]
Example 2
Input: reassemble_frames([[104, 105, 10, 98], [121, 101, 10]], 'newline')
Output: [[104, 105], [98, 121, 101]]
Hints
Hint 1
Pieces only matter as a way to deliver bytes. Start by concatenating them into one buffer, then parse that buffer from the front.
Hint 2
Keep a read position. For length-prefixed mode, read 4 bytes at the position as a big-endian integer, check that the whole payload is present, and then advance the position past header plus payload. If it is not present, stop.
Hint 3
For newline mode, repeatedly search for byte 10 starting at the read position. If none is found, the rest is an unfinished line and is dropped. Remember that empty lines still count as messages.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The way the stream was split into pieces has no effect on the answer, so the first step is to concatenate every piece into a single bytearray. After that, parse the buffer from the front with a read position pos.
Length-prefixed mode
- While at least 4 bytes remain after
pos, decode them as a big-endian unsigned integern. - If fewer than
nbytes follow the header, the message is incomplete, so stop. - Otherwise, append the
npayload bytes as one message and movepospast the header and payload.
A zero-length payload is valid and gives [].
Newline mode
- Search for byte
10starting atpos. - If none is found, the remaining bytes are an unfinished line, so stop.
- Otherwise, append the bytes from
posup to (not including) the newline, and setposjust past the newline.
Consecutive newlines naturally produce empty messages.
An unknown mode raises ValueError before any parsing.
Why it is correct
- Concatenation reproduces the exact byte stream, so partial reads, coalesced messages and empty pieces are all handled uniformly.
- Each loop iteration consumes exactly one complete frame and leaves
posat the start of the next, so frames are emitted in stream order with no overlap. - Stopping at the first incomplete frame is correct because everything after an incomplete frame cannot be located.
Complexity
- Time: O(B), where B is the total number of bytes. Each byte is copied into the buffer once, scanned at most once, and copied into an output message once.
- Space: O(B) for the buffer and the output.
Reference solution
from typing import List
def reassemble_frames(chunks: List[List[int]], mode: str) -> List[List[int]]:
if mode not in ("length_prefixed", "newline"):
raise ValueError("mode must be 'length_prefixed' or 'newline'")
stream = bytearray()
for piece in chunks:
stream.extend(piece)
messages: List[List[int]] = []
pos = 0
if mode == "length_prefixed":
while len(stream) - pos >= 4:
n = int.from_bytes(stream[pos:pos + 4], "big")
body_start = pos + 4
if len(stream) - body_start < n:
break
messages.append(list(stream[body_start:body_start + n]))
pos = body_start + n
else:
while True:
end = stream.find(b"\n", pos)
if end == -1:
break
messages.append(list(stream[pos:end]))
pos = end + 1
return messages