Fix the packet parser for a telemetry collector

Review the AI's codeEasy10 min

Your task

You are an application engineer with no networking background, and an AI wrote the packet parser for your telemetry collector. It ran fine against your test capture, but you cannot judge parsing code in this field by eye. So the team reviews it against the packet format, rule by rule.

An assistant wrote parse_telemetry_packet(packet_bytes). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • packet_bytes: the packet, one integer per byte.
  • Return ["version=<v>", "type=<t>", "length=<n>", "checksum=<c>"] for a valid packet, or a one item list with an error: ["error=<reason>"].

Rules the tests check. Check in this order and return the first error that applies:

  1. byte_out_of_range when any value is below 0 or above 255.
  2. truncated_header when there are fewer than 3 bytes.
  3. bad_version when byte 0, the version, is not 1.
  4. unknown_type when byte 1, the type, is not 1, 2 or 3.
  5. length_mismatch when byte 2, the declared payload length, is not exactly the number of bytes after the first 3. Those bytes are the payload.

For a valid packet, <n> is the payload length and <c> is the sum of the payload bytes modulo 256. An empty payload has checksum 0.

Examples

parse_telemetry_packet(packet_bytes: list[int]) -> list[str]
Example 1
Inputparse_telemetry_packet([1, 2, 3, 10, 20, 30])
Output["version=1", "type=2", "length=3", "checksum=60"]
Example 2
Inputparse_telemetry_packet([1, 2, 5, 10, 20, 30])
Output["error=length_mismatch"]