PY-46

Encode and Decode One Variable-Byte Integer

  • Medium–Hard
  • Binary Encoding
  • Python

Task

Implement encode_varint(value) and decode_varint(data) for one non-negative integer. Use this complete byte rule:

  1. Each byte carries a value group from 0 through 127.
  2. Store the least-significant seven-bit group first.
  3. Add 128 to a group when another byte follows. A final byte remains below 128.
  4. Zero is encoded as b"\x00".

encode_varint returns a bytes value and raises ValueError("value must be non-negative") for a negative input.

decode_varint returns (value, status) using these exact statuses:

  • (value, "ok") for one canonical encoded integer;
  • (None, "empty") for b"";
  • (None, "truncated") when every supplied byte says another byte follows;
  • (None, "trailing bytes") when bytes remain after the final byte;
  • (None, "non-canonical") when a multi-byte encoding ends with a zero value group.

Check statuses in that order where applicable. Do not call int.to_bytes or int.from_bytes. You do not need bitwise operators: % 128 selects the next group, // 128 removes it, and a group at position p contributes group * (128 ** p) while decoding.

Example

300 has first group 44 and next group 2. The first byte is 44 + 128 because another group follows. b"\x80\x00" is rejected as non-canonical; zero already has the shorter encoding b"\x00".

Your implementation

Edit solution.py and keep both signatures:

Do not change data, print, or ask for input.