Indexing with `slice::binary_search_by`'s result should not produce panicking branch
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
In this code:
fn binary_search_repro(needle: &str) -> Option<&str> {
let haystack = &["a", "b"];
haystack.binary_search(&needle).ok().map(|i| haystack[i])
}
the compiler should be able to use the hint from slice::binary_search_by in order to elide the length check in the index operation (haystack[i]).
Seems the knowledge from this assert_unchecked is lost somehow:
https://github.com/rust-lang/rust/blob/e10aa8891182378de002bd71bf4d04181fb8231d/library/core/src/slice/mod.rs#L2975
Godbolt: https://rust.godbolt.org/z/8zqq8vrrv
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 binary_search_repro example and the linked assert_unchecked in library/core/src/slice/mod.rs. Inspect how the compiler carries the binary-search result into the haystack[i] indexing operation, using the linked Godbolt reproduction to compare generated code. Done means the bounds check is eliminated for this pattern without changing behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100