Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Instruct LLVM that binary_search returns a valid index #81354

Merged
merged 2 commits into from
Mar 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions library/core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2204,6 +2204,8 @@ impl<T> [T] {
} else if cmp == Greater {
right = mid;
} else {
// SAFETY: same as the `get_unchecked` above
unsafe { crate::intrinsics::assume(mid < self.len()) };
return Ok(mid);
}

Expand Down
19 changes: 19 additions & 0 deletions src/test/codegen/binary-search-index-no-bound-check.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// min-llvm-version: 11.0.0
// compile-flags: -O
// ignore-debug: the debug assertions get in the way
#![crate_type = "lib"]

// Make sure no bounds checks are emitted when slicing or indexing
// with an index from `binary_search`.

// CHECK-LABEL: @binary_search_index_no_bounds_check
#[no_mangle]
pub fn binary_search_index_no_bounds_check(s: &[u8]) -> u8 {
// CHECK-NOT: panic
// CHECK-NOT: slice_index_len_fail
if let Ok(idx) = s.binary_search(&b'\\') {
s[idx]
} else {
42
}
}