Skip to content

Commit 2e0dad7

Browse files
committed
Rollup merge of rust-lang#32456 - bluss:str-zero, r=alexcrichton
Hardcode accepting 0 as a valid str char boundary If we check explicitly for index == 0, that removes the need to read the byte at index 0, so it avoids a trip to the string's memory, and it optimizes out the slicing index' bounds check whenever it is (a constant) zero.
2 parents f6001ce + f621193 commit 2e0dad7

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

src/libcore/str/mod.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -1953,7 +1953,10 @@ impl StrExt for str {
19531953

19541954
#[inline]
19551955
fn is_char_boundary(&self, index: usize) -> bool {
1956-
if index == self.len() { return true; }
1956+
// 0 and len are always ok.
1957+
// Test for 0 explicitly so that it can optimize out the check
1958+
// easily and skip reading string data for that case.
1959+
if index == 0 || index == self.len() { return true; }
19571960
match self.as_bytes().get(index) {
19581961
None => false,
19591962
Some(&b) => b < 128 || b >= 192,
@@ -2026,6 +2029,7 @@ impl StrExt for str {
20262029
self.find(pat)
20272030
}
20282031

2032+
#[inline]
20292033
fn split_at(&self, mid: usize) -> (&str, &str) {
20302034
// is_char_boundary checks that the index is in [0, .len()]
20312035
if self.is_char_boundary(mid) {

0 commit comments

Comments
 (0)