Skip to content

Commit cc863f0

Browse files
committed
Improve str prefix/suffix comparison
The comparison can be performed on the raw bytes, as the chars can only match if their UTF8 encoding matches. This avoids the `is_char_boundary` checks and translates to a straight `u8` slice comparison which is optimized to a memcmp or inline comparison where appropriate.
1 parent ddca1e0 commit cc863f0

File tree

1 file changed

+2
-5
lines changed

1 file changed

+2
-5
lines changed

src/libcore/str/pattern.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -715,16 +715,13 @@ impl<'a, 'b> Pattern<'a> for &'b str {
715715
/// Checks whether the pattern matches at the front of the haystack
716716
#[inline]
717717
fn is_prefix_of(self, haystack: &'a str) -> bool {
718-
haystack.is_char_boundary(self.len()) &&
719-
self == &haystack[..self.len()]
718+
haystack.as_bytes().starts_with(self.as_bytes())
720719
}
721720

722721
/// Checks whether the pattern matches at the back of the haystack
723722
#[inline]
724723
fn is_suffix_of(self, haystack: &'a str) -> bool {
725-
self.len() <= haystack.len() &&
726-
haystack.is_char_boundary(haystack.len() - self.len()) &&
727-
self == &haystack[haystack.len() - self.len()..]
724+
haystack.as_bytes().ends_with(self.as_bytes())
728725
}
729726
}
730727

0 commit comments

Comments
 (0)