Fix the frame walker in a binary protocol parser
Your task
An agent wrote a C++ parser for a binary network protocol, and it parses every captured sample packet. But it reads bytes an attacker controls, and sample packets are always well formed. Before it ships, you model its first step, splitting the stream into frames, and test it on broken input.
An assistant wrote parse_frame_lengths(byte_stream). It is in the editor. It has a bug. Find it and fix it.
Input and output:
byte_stream: the received bytes, as integers.- Each frame on the wire is one length byte L followed by L payload bytes. Frames repeat until the stream ends.
- Return the length of each frame, in order. Return
[-1]when the stream is malformed.
Rules the tests check:
- If any value is below 0 or above 255, it is not a byte: return
[-1]. - Read frames from the start. A frame is valid only when all L of its payload bytes are in the stream after its length byte.
- If any frame runs past the end of the stream, return
[-1], not the frames read so far. - A frame with length 0 is valid and has no payload.
- An empty stream returns
[].
Examples
parse_frame_lengths(byte_stream: list[int]) -> list[int]Example 1
Input
parse_frame_lengths([3, 1, 2, 3, 0, 2, 9, 9])Output
[3, 0, 2]Example 2
Input
parse_frame_lengths([4, 1, 2])Output
[-1]Example 3
Input
parse_frame_lengths([])Output
[]