Fix the checked align-up helper for network sizes
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
athat is at leastn, or-1when the request is not allowed.
Rules the tests check:
nmust be from 0 to 4294967295, andafrom 1 to 4294967295. Otherwise return-1.amust be a power of two: 1, 2, 4, 8 and so on. Otherwise return-1.- If
n + a - 1is greater than 4294967295, the rounded size does not fit in 32 bits: return-1. - Otherwise return
nrounded up to the next multiple ofa, ornitself when it already is one.
Examples
align_up_checked(n: int, a: int) -> intExample 1
Input
align_up_checked(17, 16)Output
32Example 2
Input
align_up_checked(4294967281, 16)Output
-1