Skip to content

Fix signed integer min/max bounds in PrimitiveType - #556

Open
arpitjain099 wants to merge 1 commit into
NASA-AMMOS:masterfrom
arpitjain099:chore/dtype-signed-bounds
Open

Fix signed integer min/max bounds in PrimitiveType#556
arpitjain099 wants to merge 1 commit into
NASA-AMMOS:masterfrom
arpitjain099:chore/dtype-signed-bounds

Conversation

@arpitjain099

Copy link
Copy Markdown

I do supply-chain security work and was reading through the dtype module when the signed-integer bounds in PrimitiveType.__init__ looked off by one:

self._max = 2 ** (self.nbits - 1)
self._min = -1 * (self.max - 1)

For an n-bit two's complement integer the range is [-2**(n-1), 2**(n-1) - 1], so for I8 this reports [-127, 128] instead of [-128, 127] (and likewise for the 16/32/64-bit signed types).

validate() uses these bounds directly, so today:

  • validate(128) on I8 returns True, but encode(128) then fails in struct.pack (the b format requires -128..127). validate is meant to catch that.
  • validate(-128) on I8 returns False, even though -128 is a legal int8 that encodes fine.

The fix sets max to 2**(n-1) - 1 and derives min as -(max + 1). The unsigned and float branches are unchanged.

I added tests/ait/core/test_dtype.py::testSignedRange, which checks the bounds for each signed type and confirms the true min and max both validate and round-trip through encode/decode, while one past each end is rejected. Nothing in the existing dtype tests asserts these bounds, so this does not change any current expectation. pytest tests/ait/core/test_dtype.py is green with the new test included.

For an n-bit two's complement integer the valid range is
[-2**(n-1), 2**(n-1) - 1], but the signed branch of
PrimitiveType.__init__ set max to 2**(n-1) and min to -(2**(n-1) - 1),
which is one step too high on both ends (I8 reported [-127, 128] instead
of [-128, 127], and likewise for the 16/32/64-bit signed types).

Since validate() uses these bounds, validate(128) on I8 returned True
even though encode(128) then fails in struct.pack, and validate(-128)
returned False even though -128 is a legal int8. Set max to
2**(n-1) - 1 and derive min as -(max + 1). Added testSignedRange to
cover the bounds, validate(), and encode/decode round-trip for each
signed type.

Signed-off-by: Arpit Jain <arpitjain099@gmail.com>
@arpitjain099
arpitjain099 requested review from a team as code owners July 24, 2026 18:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant