Skip to content

Indexing with slice::binary_search_by's result should not produce panicking branch #146789

@yotamofek

Description

@yotamofek

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:

unsafe { hint::assert_unchecked(base < self.len()) };

Godbolt: https://rust.godbolt.org/z/8zqq8vrrv

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing such

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions