Redundant length check needed to optimize out panicking bounds check in loop
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
While working on https://github.com/rust-lang/rust/pull/147436, I noticed the following code has a panicking bounds check in the loop body that is removed when both slice lengths received from as_chunks are checked.
The slices are checked to be equal length at the start of the function, so the number of chunks and loop iterations is known to be equal.
I tried this code, which manually zips two instances of as_chunks array slices together with a while-loop:
#[inline(never)]
pub const fn all_less_than(s: &[u8], other: &[u8]) -> bool {
if s.len() != other.len() {
return false;
}
const N: usize = 16;
let (a, _) = s.as_chunks::<N>();
let (b, _) = other.as_chunks::<N>();
let mut i = 0;
while i < a.len() {
let mut less_than = true;
let mut j = 0;
while j < N {
less_than &= a[i][j] < b[i][j];
j += 1;
}
if !less_than {
return false;
}
i += 1;
}
true
}
I expected to not need to check the length for b since it's known to be equal.
When I change the loop condition from while i < a.len() to while i < a.len() && i < b.len(), the panic branch is removed.
https://rust.godbolt.org/z/azrbYq4Gv
while i < a.len() | while i < a.len() && i < b.len() |
|
|
Meta
Playground nightly
Nightly channel
Build using the Nightly version: 1.92.0-nightly
(2025-10-20 4068bafedd8ba724e332)
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
Start with the all_less_than reproducer on the linked Rust Playground using the reported nightly version, then compare the two generated assembly outputs. Investigate why the loop retains a panicking bounds check unless both as_chunks slice lengths are tested; done when the redundant length condition is no longer needed for the check to be optimized out.
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
- 38/100