Fix the checked align-up helper for network sizes

Review the AI's codeEasy10 min

Your task

Firmware code rounds sizes up with (n + a - 1) & ~(a - 1) on 32-bit unsigned integers. An AI called it standard, safe alignment math, but it is only correct when a is a power of two and the sum fits in 32 bits. The sizes now come from network input, so the replacement checks both and refuses anything else.

An assistant wrote align_up_checked(n, a). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • n: the size to round up.
  • a: the alignment.
  • Return the smallest multiple of a that is at least n, or -1 when the request is not allowed.

Rules the tests check:

  • n must be from 0 to 4294967295, and a from 1 to 4294967295. Otherwise return -1.
  • a must be a power of two: 1, 2, 4, 8 and so on. Otherwise return -1.
  • If n + a - 1 is greater than 4294967295, the rounded size does not fit in 32 bits: return -1.
  • Otherwise return n rounded up to the next multiple of a, or n itself when it already is one.

Examples

align_up_checked(n: int, a: int) -> int
Example 1
Inputalign_up_checked(17, 16)
Output32
Example 2
Inputalign_up_checked(4294967281, 16)
Output-1