Skip to content

Reject negative explicit lengths in Bits - #604

Closed
boogu2005 wants to merge 1 commit into
mahmoud:masterfrom
boogu2005:codex/reject-negative-bits-length
Closed

boogu2005 wants to merge 1 commit into
mahmoud:masterfrom
boogu2005:codex/reject-negative-bits-length

Conversation

@boogu2005

@boogu2005 boogu2005 commented Oct 25, 2026 •

Copy link
Copy Markdown

The change

Reject negative explicit lengths in Bits.__init__ before calculating the value bound or storing the object's state. Currently, Bits(0, -1) succeeds with len == -1; len(bits) then raises ValueError: __len__() should return >= 0, and as_bin() fails on its format specification. Zero-valued binary/hex strings and lists can produce the same invalid object.

The constructor now raises ValueError("Bits length must be non-negative"). Zero-length empty bit strings and valid positive lengths keep their behavior. Add a short docstring clarification and regression tests across the accepted input representations and from_int.

Related open PRs #495 and #533 address oversized right shifts by clamping their resulting width. This patch validates direct constructor input; those shift changes would remain useful alongside it.

Validation on Windows, CPython 3.12.13:

  • Before the fix: the 22 newly collected regression tests fail because negative lengths are accepted.
  • After the fix: python -m pytest tests/test_mathutils.py -q — 36 passed.
  • python -m pytest --doctest-modules boltons tests -q — 700 passed, 12 subtests passed.
  • git diff --check — passed.

Other Python versions and operating systems were not tested locally.

The backstory

This came from reviewing boundary handling in the Bits constructor. An explicitly negative length could create an invalid object that only failed later during ordinary operations such as len() and as_bin(). The change rejects that invalid input at construction time and adds regression coverage for the supported input representations.

@mahmoud

mahmoud commented Oct 25, 2026

Copy link
Copy Markdown
Owner

Folded into #609 (see the PR description for credit). Thanks for the report and the repro.

@mahmoud mahmoud closed this Oct 25, 2026
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.

2 participants