Skip to content

fix(slice): guard last_one subtraction on Msb0 tail to avoid overflow#307

Open
SAY-5 wants to merge 1 commit into
ferrilab:mainfrom
SAY-5:fix/last-one-msb0-underflow
Open

fix(slice): guard last_one subtraction on Msb0 tail to avoid overflow#307
SAY-5 wants to merge 1 commit into
ferrilab:mainfrom
SAY-5:fix/last-one-msb0-underflow

Conversation

@SAY-5
Copy link
Copy Markdown

@SAY-5 SAY-5 commented May 24, 2026

Fixes #166.

sp_last_one for Msb0 subtracted from the output index in the tail-element branch before checking whether that element actually held a 1. On an all-zero slice the output starts at len() - 1 (0 for a single bit) and the unconditional subtraction underflowed usize, panicking with "attempt to subtract with overflow". Lsb0 was unaffected because it starts the counter one higher.

The fix moves the subtraction inside the has_one guard, matching the existing head-element and Enclave paths in the same function.

Repro from the issue now returns None instead of panicking:

let b = bits![usize, Msb0; 0];
assert_eq!(b.last_one(), None);

Added a regression test issue_166 covering all-zero, mixed, and single-bit Msb0 slices. Verified it fails before the change and passes after; full tests/issues.rs and cargo test --lib (142 tests) pass.

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.

Panic on subtract with overflow in last_one with Msb0

1 participant