Skip to content

Commit a6dd203

Browse files
author
Ulrik Sverdrup
committed
StrSearcher: Specialize is_prefix_of/is_suffix_of for &str
1 parent b890b7b commit a6dd203

File tree

1 file changed

+33
-17
lines changed

1 file changed

+33
-17
lines changed

src/libcore/str/pattern.rs

+33-17
Original file line numberDiff line numberDiff line change
@@ -343,23 +343,6 @@ unsafe impl<'a, C: CharEq> ReverseSearcher<'a> for CharEqSearcher<'a, C> {
343343

344344
impl<'a, C: CharEq> DoubleEndedSearcher<'a> for CharEqSearcher<'a, C> {}
345345

346-
/////////////////////////////////////////////////////////////////////////////
347-
// Impl for &str
348-
/////////////////////////////////////////////////////////////////////////////
349-
350-
/// Non-allocating substring search.
351-
///
352-
/// Will handle the pattern `""` as returning empty matches at each character
353-
/// boundary.
354-
impl<'a, 'b> Pattern<'a> for &'b str {
355-
type Searcher = StrSearcher<'a, 'b>;
356-
357-
#[inline]
358-
fn into_searcher(self, haystack: &'a str) -> StrSearcher<'a, 'b> {
359-
StrSearcher::new(haystack, self)
360-
}
361-
}
362-
363346
/////////////////////////////////////////////////////////////////////////////
364347

365348
macro_rules! pattern_methods {
@@ -511,6 +494,39 @@ impl<'a, 'b> Pattern<'a> for &'b &'b str {
511494
pattern_methods!(StrSearcher<'a, 'b>, |&s| s, |s| s);
512495
}
513496

497+
/////////////////////////////////////////////////////////////////////////////
498+
// Impl for &str
499+
/////////////////////////////////////////////////////////////////////////////
500+
501+
/// Non-allocating substring search.
502+
///
503+
/// Will handle the pattern `""` as returning empty matches at each character
504+
/// boundary.
505+
impl<'a, 'b> Pattern<'a> for &'b str {
506+
type Searcher = StrSearcher<'a, 'b>;
507+
508+
#[inline]
509+
fn into_searcher(self, haystack: &'a str) -> StrSearcher<'a, 'b> {
510+
StrSearcher::new(haystack, self)
511+
}
512+
513+
/// Checks whether the pattern matches at the front of the haystack
514+
#[inline]
515+
fn is_prefix_of(self, haystack: &'a str) -> bool {
516+
// Use `as_bytes` so that we can slice through a character in the haystack.
517+
// Since self is always valid UTF-8, this can't result in a false positive.
518+
self.len() <= haystack.len() &&
519+
self.as_bytes() == &haystack.as_bytes()[..self.len()]
520+
}
521+
522+
/// Checks whether the pattern matches at the back of the haystack
523+
#[inline]
524+
fn is_suffix_of(self, haystack: &'a str) -> bool {
525+
self.len() <= haystack.len() &&
526+
self.as_bytes() == &haystack.as_bytes()[haystack.len() - self.len()..]
527+
}
528+
}
529+
514530

515531
/////////////////////////////////////////////////////////////////////////////
516532
// Two Way substring searcher

0 commit comments

Comments
 (0)