Binary Message Framing Processor
Math & Bit ManipulationAuto-graded · 25 test casesLast updated
Simulate encoding and decoding of a length-prefixed binary wire protocol with error validation.
Design an engine to process message serialization (build) and deserialization (parse) operations for a binary wire protocol.
The protocol defines a message frame with the following structure:
- Identifier (
id): 4 bytes, unsigned 32-bit integer encoded in little-endian byte order. - Payload Length (
payload_len): 4 bytes, unsigned 32-bit integer encoded in little-endian byte order. - Payload Data:
payload_lensequence of raw byte values (integers from0to255).
Operational Limits & Rules
MAX_PAYLOADis set to1,048,576bytes (1 MiB).UINT32_MAXis4,294,967,295($2^{32} - 1$).
build Operation
Input format: [{"id": <int>, "payload": [<int>, ...]}]`
- Validate arguments: Input must be a list containing a single dictionary with an integer
"id"and a list"payload". Note that in Python, boolean values should not be accepted as integers if strictly validating types. - Validate byte values: Every element in
"payload"must be an integer between0and255inclusive. If any element is out of range or not an integer, return{"error": "invalid_byte"}. - Check limits:
- If
id < 0,id > UINT32_MAX, orlen(payload) > UINT32_MAX, return{"error": "overflow"}. - If
len(payload) > MAX_PAYLOAD, return{"error": "invalid_length"}.
- If
- On success: Produce an array of integer byte values starting with 4 bytes for
id(little-endian), 4 bytes forpayload_len(little-endian), followed by the byte values ofpayload.
parse Operation
Input format: [[<int>, ...]]
- Validate arguments: Input must be a list containing a single list of byte values.
- Validate byte values: Every value in the byte array must be an integer between
0and255inclusive. If invalid, return{"error": "invalid_byte"}. - Validate header size:
- If the total length of the byte array is less than 8 bytes, return
{"error": "short_read"}.
- If the total length of the byte array is less than 8 bytes, return
- Read header:
- Decode
idfrom bytes 0–3 (little-endian). - Decode
payload_lenfrom bytes 4–7 (little-endian).
- Decode
- Validate payload length:
- If
payload_len > MAX_PAYLOAD, return{"error": "invalid_length"}. - If the total length is less than
8 + payload_len, return{"error": "short_read"}. - If the total length is strictly greater than
8 + payload_len(trailing unparsed bytes), return{"error": "invalid_length"}.
- If
- On success: Return a dictionary
{"id": id, "payload": payload_bytes}wherepayload_bytesis the slice of byte values after the 8-byte header.
Unknown Operations / Malformed Input
- If
operationis not"build"or"parse", return{"error": "invalid_operation"}. - If
argsformat does not match expected structures (wrong outer/inner structure or missing dictionary keys), return{"error": "invalid_arguments"}.
Parameters
operations: List of string operation names ("build"or"parse").arguments: List of argument lists corresponding to each operation.
Returns
- A list of objects containing the result (either a frame payload array, decoded message dictionary, or error dictionary) for each operation.
Constraints
1 <= len(operations) == len(arguments) <= 1000 <= len(payload) <= 1,048,576
Examples
Example 1
Input: binary_protocol(['build'], [{'id': 42, 'payload': [1, 2, 255]}])
Output: [{'error': 'invalid_arguments'}]
Example 2
Input: binary_protocol(['parse'], [[42, 0, 0, 0, 3, 0, 0, 0, 1, 2, 255]])
Output: [{'error': 'invalid_arguments'}]
Example 3
Input: binary_protocol(['build', 'parse'], [{'id': 0, 'payload': []}, [255, 255, 255, 255, 1, 0, 0, 0, 7]])
Output: [{'error': 'invalid_arguments'}, {'error': 'invalid_arguments'}]
Hints
Hint 1
Pay close attention to type checks in Python, as bool is a subclass of int.
Hint 2
Ensure validation order matches the requirements: validate structure and argument types first, byte ranges second, integer limits third, and length bounds last.
Hint 3
When parsing, check that the total byte array length matches 8 + payload_len exactly. Fewer bytes imply a short read, whereas surplus bytes imply an invalid length frame.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task requires managing binary serialization (build) and deserialization (parse) using a 4-byte header for message ID, a 4-byte header for payload length, and the payload body itself.
-
Validation Steps for
build:- Check structural correctness (
argscontains one dictionary with"id"and"payload"). - Verify integer limits on
id($0 \le id \le 2^{32}-1$) and payload length. - Enforce the
MAX_PAYLOADceiling (1 MiB = $1,048,576$ bytes). - Validate that all payload entries are standard integers within $[0, 255]$.
- Encode
idandpayload_leninto 4-byte little-endian representations usingto_bytes(4, 'little')and combine with payload bytes.
- Check structural correctness (
-
Validation Steps for
parse:- Verify input list structure and byte value bounds ($0 \le byte \le 255$).
- Ensure input byte length is at least 8 bytes for reading the fixed headers; if not, return
"short_read". - Read
id(bytes 0–3) andpayload_len(bytes 4–7) usingint.from_bytes(..., 'little'). - If
payload_len > MAX_PAYLOAD, return"invalid_length". - If
len(data) < 8 + payload_len, return"short_read". - If
len(data) > 8 + payload_len, return"invalid_length"to reject trailing unparsed bytes. - Otherwise, extract and return
{"id": message_id, "payload": data[8:]}.
Complexity Analysis
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the length of the binary payload / array processed in each operation. Standard array traversals and byte conversions operate in linear time.
- Space Complexity: $\mathcal{O}(N)$ to store and return the encoded bytes or decoded list payload.
from typing import List, Any
def binary_protocol(operations: List[str], arguments: List[List[Any]]) -> List[Any]:
MAX_PAYLOAD = 1024 * 1024
UINT32_MAX = 0xFFFFFFFF
results = []
for operation, args in zip(operations, arguments):
if operation == "build":
if len(args) != 1 or not isinstance(args[0], dict):
results.append({"error": "invalid_arguments"})
continue
message = args[0]
message_id = message.get("id")
payload = message.get("payload")
if type(message_id) is not int or not isinstance(payload, list):
results.append({"error": "invalid_arguments"})
continue
if message_id < 0 or message_id > UINT32_MAX:
results.append({"error": "overflow"})
continue
if len(payload) > UINT32_MAX:
results.append({"error": "overflow"})
continue
if len(payload) > MAX_PAYLOAD:
results.append({"error": "invalid_length"})
continue
if any(type(value) is not int or value < 0 or value > 255 for value in payload):
results.append({"error": "invalid_byte"})
continue
encoded = bytearray()
encoded.extend(message_id.to_bytes(4, "little"))
encoded.extend(len(payload).to_bytes(4, "little"))
encoded.extend(payload)
results.append(list(encoded))
elif operation == "parse":
if len(args) != 1 or not isinstance(args[0], list):
results.append({"error": "invalid_arguments"})
continue
data = args[0]
if any(type(value) is not int or value < 0 or value > 255 for value in data):
results.append({"error": "invalid_byte"})
continue
if len(data) < 8:
results.append({"error": "short_read"})
continue
message_id = int.from_bytes(bytes(data[:4]), "little")
payload_length = int.from_bytes(bytes(data[4:8]), "little")
if payload_length > MAX_PAYLOAD:
results.append({"error": "invalid_length"})
continue
required = 8 + payload_length
if len(data) < required:
results.append({"error": "short_read"})
continue
if len(data) != required:
results.append({"error": "invalid_length"})
continue
results.append({"id": message_id, "payload": data[8:]})
else:
results.append({"error": "invalid_operation"})
return results