Fix the allocation plan for a length-prefixed blob

Review the AI's codeEasy10 min

Your task

Your service reads a blob from the network: a 4-byte big-endian length, then that many bytes. The first version allocated a buffer of the declared length straight away, so one 4-byte packet claiming 4 GB could exhaust memory. The fix decides, before any allocation, how much memory to set aside now.

An assistant wrote planned_allocation(header_bytes, max_blob, chunk_cap). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • header_bytes: the bytes read so far, as a list of integers from 0 to 255. The first 4 are the length.
  • max_blob: the largest blob the protocol allows.
  • chunk_cap: the most memory to set aside up front. The buffer grows later as bytes really arrive.
  • Return the number of bytes to allocate now, or -1 to reject the blob and drop the connection.

Rules the tests check:

  • If fewer than 4 bytes have arrived, return -1. Bytes after the first 4 are ignored.
  • The claimed length is big-endian: the first byte is the most significant.
  • If the claimed length is greater than max_blob, return -1.
  • Otherwise allocate the claimed length or chunk_cap, whichever is smaller. A legal claim is still only the sender's word, so never set aside more than one chunk up front.

Examples

planned_allocation(header_bytes: list[int], max_blob: int, chunk_cap: int) -> int
Example 1
Inputplanned_allocation([0, 0, 4, 0], 1048576, 65536)
Output1024
Example 2
Inputplanned_allocation([255, 255, 255, 255], 1048576, 65536)
Output-1
Example 3
Inputplanned_allocation([0, 1, 0, 0], 1048576, 65536)
Output65536