]> git.lizzy.rs Git - rust.git/commitdiff
StrSearcher: Specialize is_prefix_of/is_suffix_of for &str
authorUlrik Sverdrup <root@localhost>
Wed, 17 Jun 2015 16:35:43 +0000 (18:35 +0200)
committerUlrik Sverdrup <root@localhost>
Sun, 21 Jun 2015 17:58:56 +0000 (19:58 +0200)
src/libcore/str/pattern.rs

index de40a57fe9c17b2f6ba8e553f3b0d43aa14d1aad..048bcc0dce53f0a796f0ed42ef5d3cea16511c3a 100644 (file)
@@ -343,23 +343,6 @@ fn next_back(&mut self) -> SearchStep {
 
 impl<'a, C: CharEq> DoubleEndedSearcher<'a> for CharEqSearcher<'a, C> {}
 
-/////////////////////////////////////////////////////////////////////////////
-// Impl for &str
-/////////////////////////////////////////////////////////////////////////////
-
-/// Non-allocating substring search.
-///
-/// Will handle the pattern `""` as returning empty matches at each character
-/// boundary.
-impl<'a, 'b> Pattern<'a> for &'b str {
-    type Searcher = StrSearcher<'a, 'b>;
-
-    #[inline]
-    fn into_searcher(self, haystack: &'a str) -> StrSearcher<'a, 'b> {
-        StrSearcher::new(haystack, self)
-    }
-}
-
 /////////////////////////////////////////////////////////////////////////////
 
 macro_rules! pattern_methods {
@@ -511,6 +494,39 @@ impl<'a, 'b> Pattern<'a> for &'b &'b str {
     pattern_methods!(StrSearcher<'a, 'b>, |&s| s, |s| s);
 }
 
+/////////////////////////////////////////////////////////////////////////////
+// Impl for &str
+/////////////////////////////////////////////////////////////////////////////
+
+/// Non-allocating substring search.
+///
+/// Will handle the pattern `""` as returning empty matches at each character
+/// boundary.
+impl<'a, 'b> Pattern<'a> for &'b str {
+    type Searcher = StrSearcher<'a, 'b>;
+
+    #[inline]
+    fn into_searcher(self, haystack: &'a str) -> StrSearcher<'a, 'b> {
+        StrSearcher::new(haystack, self)
+    }
+
+    /// Checks whether the pattern matches at the front of the haystack
+    #[inline]
+    fn is_prefix_of(self, haystack: &'a str) -> bool {
+        // Use `as_bytes` so that we can slice through a character in the haystack.
+        // Since self is always valid UTF-8, this can't result in a false positive.
+        self.len() <= haystack.len() &&
+            self.as_bytes() == &haystack.as_bytes()[..self.len()]
+    }
+
+    /// Checks whether the pattern matches at the back of the haystack
+    #[inline]
+    fn is_suffix_of(self, haystack: &'a str) -> bool {
+        self.len() <= haystack.len() &&
+            self.as_bytes() == &haystack.as_bytes()[haystack.len() - self.len()..]
+    }
+}
+
 
 /////////////////////////////////////////////////////////////////////////////
 // Two Way substring searcher