PY-53
Read and Write a Versioned Binary Container
Task
Define this plain record, then write write_container(container) and
read_container(data, accepted_versions):
Its stored form uses this exact layout:
bytes 0..2 magic b"LMP"
byte 3 version, from 0 through 255
bytes 4..7 payload length as an unsigned four-byte big-endian integer
remaining payload bytes
write_container returns the complete bytes. Raise
ValueError("version out of range") unless container.version is an integer
from 0 through 255. Use length.to_bytes(4, "big") for the payload length.
read_container returns (container, status). Check failures in this order:
- fewer than eight bytes:
(None, "truncated header"); - wrong magic:
(None, "bad magic"); - version absent from
accepted_versions:(None, f"unsupported version {version}"); - too few payload bytes:
(None, "truncated payload"); - bytes after the declared payload:
(None, "trailing bytes").
On success return (BinaryContainer(version, payload), "ok"). Use
int.from_bytes(data[4:8], "big") to read the length. Do not silently accept
another layout.
Example
packet = write_container(BinaryContainer(2, b"cat"))
The result is b"LMP\x02\x00\x00\x00\x03cat". Reading it with {1, 2} as
the accepted versions returns the original record and status "ok".
Your implementation
Edit solution.py, keep the record definition above, and keep these function
signatures:
Do not modify an input, print, or ask for input. The complete format is given
above; you do not need to invent a binary format or use struct.