Skip to content

Commit 922c7b5

Browse files
authored
memchr: let compiler know that indexes returned by memchr fns are in bounds
For example, in code like: ``` let len = memchr::memchr(b'\0', slice).unwrap_or(slice.len()); &slice[..len] ``` Without this change, there is a potential panic at `&slice[..len]`, but with this change, rustc knows the len must be valid, and no longer adds the potential panic. Closes #195, Closes #196, PR #228
1 parent e21e9fb commit 922c7b5

1 file changed

Lines changed: 7 additions & 1 deletion

File tree

src/arch/generic/memchr.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1132,7 +1132,13 @@ pub(crate) unsafe fn search_slice_with_raw(
11321132
let start = haystack.as_ptr();
11331133
let end = start.add(haystack.len());
11341134
let found = find_raw(start, end)?;
1135-
Some(found.distance(start))
1135+
let idx = found.distance(start);
1136+
// Required by safety invariant required for find_raw
1137+
// this lets the compiler know the returned index is in bounds for the slice
1138+
if idx >= haystack.len() {
1139+
core::hint::unreachable_unchecked();
1140+
}
1141+
Some(idx)
11361142
}
11371143

11381144
/// Performs a forward byte-at-a-time loop until either `ptr >= end_ptr` or

0 commit comments

Comments
 (0)