Fix the frame reader for an agent's wire protocol
Your task
An agent wrote the parser for your service's binary wire protocol, and you are building the checks to trust it. The protocol is length-prefixed: one length byte, then that many payload bytes, repeated to the end of the buffer. A bad length here means memory corruption or a denial of service, so the parser must reject a frame before it trusts its length.
An assistant wrote parse_length_prefixed_frames(payload_bytes, max_frame_len). It is in the editor. It has a bug. Find it and fix it.
Input and output:
payload_bytes: the buffer, as a list of integers.max_frame_len: the largest payload length a frame may declare.- Return one string per frame, or a list holding a single error string.
Rules the tests check:
- First, if any value is below 0 or above 255, return
["error:invalid_byte@<i>"], whereiis the index of the first such value. - A negative
max_frame_lencounts as 0. - Read frames from index 0 until the buffer ends. For each frame, with its length byte at index
s:- If the length is above
max_frame_len, return["error:oversize@<s>"]. - If fewer bytes remain after the length byte than the length says, return
["error:truncated@<s>"]. - Otherwise the frame's string is its payload bytes in decimal, joined by
,. A length of 0 gives"".
- If the length is above
- On an error, return only the error, never the frames read before it.
Examples
parse_length_prefixed_frames(payload_bytes: list[int], max_frame_len: int) -> list[str]Example 1
Input
parse_length_prefixed_frames([3, 10, 20, 30, 1, 99], 4)Output
["10,20,30", "99"]Example 2
Input
parse_length_prefixed_frames([5, 1, 2], 8)Output
["error:truncated@0"]Example 3
Input
parse_length_prefixed_frames([0, 0], 4)Output
["", ""]