Counter in slice iter fails to eliminate bounds check
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
The following code (somewhat extracted from #126425) includes an unreachable bounds check panic
pub fn getnonzero(buf: &[u8; 128]) -> &[u8] {
let mut curr = 0;
for n in buf.iter() {
if *n == 0 { break; }
curr += 1;
}
&buf[..curr]
}
https://godbolt.org/z/vzooGexnj
This bounds check can be eliminated: Alive2
This also occurs with reverse iteration (like in the original) and iterating 0..buf.len() instead of direct slice iteration. Lowering the slice length to the point where the loop is fully unrolled does eliminate this, but the exact number depends on the specific code.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Compile the provided getnonzero reproducer and inspect its generated output through Godbolt, comparing direct, reverse, and range iteration variants. Trace the compiler optimization path responsible for the bounds check and validate changes against the Alive2 example. Done means the unreachable check is eliminated for the reported cases without regressing other cases.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers, performance
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100