Skip to content

Commit

Permalink
Rollup merge of rust-lang#32456 - bluss:str-zero, r=alexcrichton
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Manishearth committed Mar 26, 2016
2 parents f6001ce + f621193 commit 2e0dad7
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/libcore/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1953,7 +1953,10 @@ impl StrExt for str {

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

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

0 comments on commit 2e0dad7

Please sign in to comment.