1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! The string Pattern API.
13 //! For more details, see the traits `Pattern`, `Searcher`,
14 //! `ReverseSearcher` and `DoubleEndedSearcher`.
16 #![unstable(feature = "pattern",
17 reason = "API not fully fleshed out and ready to be stabilized",
29 /// A `Pattern<'a>` expresses that the implementing type
30 /// can be used as a string pattern for searching in a `&'a str`.
32 /// For example, both `'a'` and `"aa"` are patterns that
33 /// would match at index `1` in the string `"baaaab"`.
35 /// The trait itself acts as a builder for an associated
36 /// `Searcher` type, which does the actual work of finding
37 /// occurrences of the pattern in a string.
38 pub trait Pattern<'a>: Sized {
39 /// Associated searcher for this pattern
40 type Searcher: Searcher<'a>;
42 /// Constructs the associated searcher from
43 /// `self` and the `haystack` to search in.
44 fn into_searcher(self, haystack: &'a str) -> Self::Searcher;
46 /// Checks whether the pattern matches anywhere in the haystack
48 fn is_contained_in(self, haystack: &'a str) -> bool {
49 self.into_searcher(haystack).next_match().is_some()
52 /// Checks whether the pattern matches at the front of the haystack
54 fn is_prefix_of(self, haystack: &'a str) -> bool {
55 match self.into_searcher(haystack).next() {
56 SearchStep::Match(0, _) => true,
61 /// Checks whether the pattern matches at the back of the haystack
63 fn is_suffix_of(self, haystack: &'a str) -> bool
64 where Self::Searcher: ReverseSearcher<'a>
66 match self.into_searcher(haystack).next_back() {
67 SearchStep::Match(_, j) if haystack.len() == j => true,
75 /// Result of calling `Searcher::next()` or `ReverseSearcher::next_back()`.
76 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
78 /// Expresses that a match of the pattern has been found at
81 /// Expresses that `haystack[a..b]` has been rejected as a possible match
84 /// Note that there might be more than one `Reject` between two `Match`es,
85 /// there is no requirement for them to be combined into one.
87 /// Expresses that every byte of the haystack has been visited, ending
92 /// A searcher for a string pattern.
94 /// This trait provides methods for searching for non-overlapping
95 /// matches of a pattern starting from the front (left) of a string.
97 /// It will be implemented by associated `Searcher`
98 /// types of the `Pattern` trait.
100 /// The trait is marked unsafe because the indices returned by the
101 /// `next()` methods are required to lie on valid utf8 boundaries in
102 /// the haystack. This enables consumers of this trait to
103 /// slice the haystack without additional runtime checks.
104 pub unsafe trait Searcher<'a> {
105 /// Getter for the underlying string to be searched in
107 /// Will always return the same `&str`
108 fn haystack(&self) -> &'a str;
110 /// Performs the next search step starting from the front.
112 /// - Returns `Match(a, b)` if `haystack[a..b]` matches the pattern.
113 /// - Returns `Reject(a, b)` if `haystack[a..b]` can not match the
114 /// pattern, even partially.
115 /// - Returns `Done` if every byte of the haystack has been visited
117 /// The stream of `Match` and `Reject` values up to a `Done`
118 /// will contain index ranges that are adjacent, non-overlapping,
119 /// covering the whole haystack, and laying on utf8 boundaries.
121 /// A `Match` result needs to contain the whole matched pattern,
122 /// however `Reject` results may be split up into arbitrary
123 /// many adjacent fragments. Both ranges may have zero length.
125 /// As an example, the pattern `"aaa"` and the haystack `"cbaaaaab"`
126 /// might produce the stream
127 /// `[Reject(0, 1), Reject(1, 2), Match(2, 5), Reject(5, 8)]`
128 fn next(&mut self) -> SearchStep;
130 /// Find the next `Match` result. See `next()`
132 /// Unlike next(), there is no guarantee that the returned ranges
133 /// of this and next_reject will overlap. This will return (start_match, end_match),
134 /// where start_match is the index of where the match begins, and end_match is
135 /// the index after the end of the match.
137 fn next_match(&mut self) -> Option<(usize, usize)> {
140 SearchStep::Match(a, b) => return Some((a, b)),
141 SearchStep::Done => return None,
147 /// Find the next `Reject` result. See `next()` and `next_match()`
149 /// Unlike next(), there is no guarantee that the returned ranges
150 /// of this and next_match will overlap.
152 fn next_reject(&mut self) -> Option<(usize, usize)> {
155 SearchStep::Reject(a, b) => return Some((a, b)),
156 SearchStep::Done => return None,
163 /// A reverse searcher for a string pattern.
165 /// This trait provides methods for searching for non-overlapping
166 /// matches of a pattern starting from the back (right) of a string.
168 /// It will be implemented by associated `Searcher`
169 /// types of the `Pattern` trait if the pattern supports searching
170 /// for it from the back.
172 /// The index ranges returned by this trait are not required
173 /// to exactly match those of the forward search in reverse.
175 /// For the reason why this trait is marked unsafe, see them
176 /// parent trait `Searcher`.
177 pub unsafe trait ReverseSearcher<'a>: Searcher<'a> {
178 /// Performs the next search step starting from the back.
180 /// - Returns `Match(a, b)` if `haystack[a..b]` matches the pattern.
181 /// - Returns `Reject(a, b)` if `haystack[a..b]` can not match the
182 /// pattern, even partially.
183 /// - Returns `Done` if every byte of the haystack has been visited
185 /// The stream of `Match` and `Reject` values up to a `Done`
186 /// will contain index ranges that are adjacent, non-overlapping,
187 /// covering the whole haystack, and laying on utf8 boundaries.
189 /// A `Match` result needs to contain the whole matched pattern,
190 /// however `Reject` results may be split up into arbitrary
191 /// many adjacent fragments. Both ranges may have zero length.
193 /// As an example, the pattern `"aaa"` and the haystack `"cbaaaaab"`
194 /// might produce the stream
195 /// `[Reject(7, 8), Match(4, 7), Reject(1, 4), Reject(0, 1)]`
196 fn next_back(&mut self) -> SearchStep;
198 /// Find the next `Match` result. See `next_back()`
200 fn next_match_back(&mut self) -> Option<(usize, usize)>{
202 match self.next_back() {
203 SearchStep::Match(a, b) => return Some((a, b)),
204 SearchStep::Done => return None,
210 /// Find the next `Reject` result. See `next_back()`
212 fn next_reject_back(&mut self) -> Option<(usize, usize)>{
214 match self.next_back() {
215 SearchStep::Reject(a, b) => return Some((a, b)),
216 SearchStep::Done => return None,
223 /// A marker trait to express that a `ReverseSearcher`
224 /// can be used for a `DoubleEndedIterator` implementation.
226 /// For this, the impl of `Searcher` and `ReverseSearcher` need
227 /// to follow these conditions:
229 /// - All results of `next()` need to be identical
230 /// to the results of `next_back()` in reverse order.
231 /// - `next()` and `next_back()` need to behave as
232 /// the two ends of a range of values, that is they
233 /// can not "walk past each other".
237 /// `char::Searcher` is a `DoubleEndedSearcher` because searching for a
238 /// `char` only requires looking at one at a time, which behaves the same
241 /// `(&str)::Searcher` is not a `DoubleEndedSearcher` because
242 /// the pattern `"aa"` in the haystack `"aaa"` matches as either
243 /// `"[aa]a"` or `"a[aa]"`, depending from which side it is searched.
244 pub trait DoubleEndedSearcher<'a>: ReverseSearcher<'a> {}
247 /////////////////////////////////////////////////////////////////////////////
249 /////////////////////////////////////////////////////////////////////////////
251 /// Associated type for `<char as Pattern<'a>>::Searcher`.
252 #[derive(Clone, Debug)]
253 pub struct CharSearcher<'a> {
255 // safety invariant: `finger`/`finger_back` must be a valid utf8 byte index of `haystack`
256 // This invariant can be broken *within* next_match and next_match_back, however
257 // they must exit with fingers on valid code point boundaries.
259 /// `finger` is the current byte index of the forward search.
260 /// Imagine that it exists before the byte at its index, i.e.
261 /// `haystack[finger]` is the first byte of the slice we must inspect during
262 /// forward searching
264 /// `finger_back` is the current byte index of the reverse search.
265 /// Imagine that it exists after the byte at its index, i.e.
266 /// haystack[finger_back - 1] is the last byte of the slice we must inspect during
267 /// forward searching (and thus the first byte to be inspected when calling next_back())
269 /// The character being searched for
272 // safety invariant: `utf8_size` must be less than 5
273 /// The number of bytes `needle` takes up when encoded in utf8
275 /// A utf8 encoded copy of the `needle`
276 utf8_encoded: [u8; 4],
279 unsafe impl<'a> Searcher<'a> for CharSearcher<'a> {
281 fn haystack(&self) -> &'a str {
285 fn next(&mut self) -> SearchStep {
286 let old_finger = self.finger;
287 let slice = unsafe { self.haystack.get_unchecked(old_finger..self.finger_back) };
288 let mut iter = slice.chars();
289 let old_len = iter.iter.len();
290 if let Some(ch) = iter.next() {
291 // add byte offset of current character
292 // without re-encoding as utf-8
293 self.finger += old_len - iter.iter.len();
294 if ch == self.needle {
295 SearchStep::Match(old_finger, self.finger)
297 SearchStep::Reject(old_finger, self.finger)
304 fn next_match(&mut self) -> Option<(usize, usize)> {
306 // get the haystack after the last character found
307 let bytes = if let Some(slice) = self.haystack.as_bytes()
308 .get(self.finger..self.finger_back) {
313 // the last byte of the utf8 encoded needle
314 let last_byte = unsafe { *self.utf8_encoded.get_unchecked(self.utf8_size - 1) };
315 if let Some(index) = memchr::memchr(last_byte, bytes) {
316 // The new finger is the index of the byte we found,
317 // plus one, since we memchr'd for the last byte of the character.
319 // Note that this doesn't always give us a finger on a UTF8 boundary.
320 // If we *didn't* find our character
321 // we may have indexed to the non-last byte of a 3-byte or 4-byte character.
322 // We can't just skip to the next valid starting byte because a character like
323 // ꁁ (U+A041 YI SYLLABLE PA), utf-8 `EA 81 81` will have us always find
324 // the second byte when searching for the third.
326 // However, this is totally okay. While we have the invariant that
327 // self.finger is on a UTF8 boundary, this invariant is not relied upon
328 // within this method (it is relied upon in CharSearcher::next()).
330 // We only exit this method when we reach the end of the string, or if we
331 // find something. When we find something the `finger` will be set
332 // to a UTF8 boundary.
333 self.finger += index + 1;
334 if self.finger >= self.utf8_size {
335 let found_char = self.finger - self.utf8_size;
336 if let Some(slice) = self.haystack.as_bytes().get(found_char..self.finger) {
337 if slice == &self.utf8_encoded[0..self.utf8_size] {
338 return Some((found_char, self.finger));
343 // found nothing, exit
344 self.finger = self.finger_back;
350 // let next_reject use the default implementation from the Searcher trait
353 unsafe impl<'a> ReverseSearcher<'a> for CharSearcher<'a> {
355 fn next_back(&mut self) -> SearchStep {
356 let old_finger = self.finger_back;
357 let slice = unsafe { self.haystack.get_unchecked(self.finger..old_finger) };
358 let mut iter = slice.chars();
359 let old_len = iter.iter.len();
360 if let Some(ch) = iter.next_back() {
361 // subtract byte offset of current character
362 // without re-encoding as utf-8
363 self.finger_back -= old_len - iter.iter.len();
364 if ch == self.needle {
365 SearchStep::Match(self.finger_back, old_finger)
367 SearchStep::Reject(self.finger_back, old_finger)
374 fn next_match_back(&mut self) -> Option<(usize, usize)> {
375 let haystack = self.haystack.as_bytes();
377 // get the haystack up to but not including the last character searched
378 let bytes = if let Some(slice) = haystack.get(self.finger..self.finger_back) {
383 // the last byte of the utf8 encoded needle
384 let last_byte = unsafe { *self.utf8_encoded.get_unchecked(self.utf8_size - 1) };
385 if let Some(index) = memchr::memrchr(last_byte, bytes) {
386 // we searched a slice that was offset by self.finger,
387 // add self.finger to recoup the original index
388 let index = self.finger + index;
389 // memrchr will return the index of the byte we wish to
390 // find. In case of an ASCII character, this is indeed
391 // were we wish our new finger to be ("after" the found
392 // char in the paradigm of reverse iteration). For
393 // multibyte chars we need to skip down by the number of more
394 // bytes they have than ASCII
395 let shift = self.utf8_size - 1;
397 let found_char = index - shift;
398 if let Some(slice) = haystack.get(found_char..(found_char + self.utf8_size)) {
399 if slice == &self.utf8_encoded[0..self.utf8_size] {
400 // move finger to before the character found (i.e. at its start index)
401 self.finger_back = found_char;
402 return Some((self.finger_back, self.finger_back + self.utf8_size));
406 // We can't use finger_back = index - size + 1 here. If we found the last char
407 // of a different-sized character (or the middle byte of a different character)
408 // we need to bump the finger_back down to `index`. This similarly makes
409 // `finger_back` have the potential to no longer be on a boundary,
410 // but this is OK since we only exit this function on a boundary
411 // or when the haystack has been searched completely.
413 // Unlike next_match this does not
414 // have the problem of repeated bytes in utf-8 because
415 // we're searching for the last byte, and we can only have
416 // found the last byte when searching in reverse.
417 self.finger_back = index;
419 self.finger_back = self.finger;
420 // found nothing, exit
426 // let next_reject_back use the default implementation from the Searcher trait
429 impl<'a> DoubleEndedSearcher<'a> for CharSearcher<'a> {}
431 /// Searches for chars that are equal to a given char
432 impl<'a> Pattern<'a> for char {
433 type Searcher = CharSearcher<'a>;
436 fn into_searcher(self, haystack: &'a str) -> Self::Searcher {
437 let mut utf8_encoded = [0; 4];
438 self.encode_utf8(&mut utf8_encoded);
439 let utf8_size = self.len_utf8();
443 finger_back: haystack.len(),
451 fn is_contained_in(self, haystack: &'a str) -> bool {
452 if (self as u32) < 128 {
453 haystack.as_bytes().contains(&(self as u8))
455 let mut buffer = [0u8; 4];
456 self.encode_utf8(&mut buffer).is_contained_in(haystack)
461 fn is_prefix_of(self, haystack: &'a str) -> bool {
462 if let Some(ch) = haystack.chars().next() {
470 fn is_suffix_of(self, haystack: &'a str) -> bool where Self::Searcher: ReverseSearcher<'a>
472 if let Some(ch) = haystack.chars().next_back() {
480 /////////////////////////////////////////////////////////////////////////////
481 // Impl for a MultiCharEq wrapper
482 /////////////////////////////////////////////////////////////////////////////
486 fn matches(&mut self, c: char) -> bool;
489 impl<F> MultiCharEq for F where F: FnMut(char) -> bool {
491 fn matches(&mut self, c: char) -> bool { (*self)(c) }
494 impl MultiCharEq for &[char] {
496 fn matches(&mut self, c: char) -> bool {
497 self.iter().any(|&m| { m == c })
501 struct MultiCharEqPattern<C: MultiCharEq>(C);
503 #[derive(Clone, Debug)]
504 struct MultiCharEqSearcher<'a, C: MultiCharEq> {
507 char_indices: super::CharIndices<'a>,
510 impl<'a, C: MultiCharEq> Pattern<'a> for MultiCharEqPattern<C> {
511 type Searcher = MultiCharEqSearcher<'a, C>;
514 fn into_searcher(self, haystack: &'a str) -> MultiCharEqSearcher<'a, C> {
515 MultiCharEqSearcher {
518 char_indices: haystack.char_indices(),
523 unsafe impl<'a, C: MultiCharEq> Searcher<'a> for MultiCharEqSearcher<'a, C> {
525 fn haystack(&self) -> &'a str {
530 fn next(&mut self) -> SearchStep {
531 let s = &mut self.char_indices;
532 // Compare lengths of the internal byte slice iterator
533 // to find length of current char
534 let pre_len = s.iter.iter.len();
535 if let Some((i, c)) = s.next() {
536 let len = s.iter.iter.len();
537 let char_len = pre_len - len;
538 if self.char_eq.matches(c) {
539 return SearchStep::Match(i, i + char_len);
541 return SearchStep::Reject(i, i + char_len);
548 unsafe impl<'a, C: MultiCharEq> ReverseSearcher<'a> for MultiCharEqSearcher<'a, C> {
550 fn next_back(&mut self) -> SearchStep {
551 let s = &mut self.char_indices;
552 // Compare lengths of the internal byte slice iterator
553 // to find length of current char
554 let pre_len = s.iter.iter.len();
555 if let Some((i, c)) = s.next_back() {
556 let len = s.iter.iter.len();
557 let char_len = pre_len - len;
558 if self.char_eq.matches(c) {
559 return SearchStep::Match(i, i + char_len);
561 return SearchStep::Reject(i, i + char_len);
568 impl<'a, C: MultiCharEq> DoubleEndedSearcher<'a> for MultiCharEqSearcher<'a, C> {}
570 /////////////////////////////////////////////////////////////////////////////
572 macro_rules! pattern_methods {
573 ($t:ty, $pmap:expr, $smap:expr) => {
577 fn into_searcher(self, haystack: &'a str) -> $t {
578 ($smap)(($pmap)(self).into_searcher(haystack))
582 fn is_contained_in(self, haystack: &'a str) -> bool {
583 ($pmap)(self).is_contained_in(haystack)
587 fn is_prefix_of(self, haystack: &'a str) -> bool {
588 ($pmap)(self).is_prefix_of(haystack)
592 fn is_suffix_of(self, haystack: &'a str) -> bool
593 where $t: ReverseSearcher<'a>
595 ($pmap)(self).is_suffix_of(haystack)
600 macro_rules! searcher_methods {
603 fn haystack(&self) -> &'a str {
607 fn next(&mut self) -> SearchStep {
611 fn next_match(&mut self) -> Option<(usize, usize)> {
615 fn next_reject(&mut self) -> Option<(usize, usize)> {
621 fn next_back(&mut self) -> SearchStep {
625 fn next_match_back(&mut self) -> Option<(usize, usize)> {
626 self.0.next_match_back()
629 fn next_reject_back(&mut self) -> Option<(usize, usize)> {
630 self.0.next_reject_back()
635 /////////////////////////////////////////////////////////////////////////////
637 /////////////////////////////////////////////////////////////////////////////
639 // Todo: Change / Remove due to ambiguity in meaning.
641 /// Associated type for `<&[char] as Pattern<'a>>::Searcher`.
642 #[derive(Clone, Debug)]
643 pub struct CharSliceSearcher<'a, 'b>(<MultiCharEqPattern<&'b [char]> as Pattern<'a>>::Searcher);
645 unsafe impl<'a, 'b> Searcher<'a> for CharSliceSearcher<'a, 'b> {
646 searcher_methods!(forward);
649 unsafe impl<'a, 'b> ReverseSearcher<'a> for CharSliceSearcher<'a, 'b> {
650 searcher_methods!(reverse);
653 impl<'a, 'b> DoubleEndedSearcher<'a> for CharSliceSearcher<'a, 'b> {}
655 /// Searches for chars that are equal to any of the chars in the array
656 impl<'a, 'b> Pattern<'a> for &'b [char] {
657 pattern_methods!(CharSliceSearcher<'a, 'b>, MultiCharEqPattern, CharSliceSearcher);
660 /////////////////////////////////////////////////////////////////////////////
661 // Impl for F: FnMut(char) -> bool
662 /////////////////////////////////////////////////////////////////////////////
664 /// Associated type for `<F as Pattern<'a>>::Searcher`.
666 pub struct CharPredicateSearcher<'a, F>(<MultiCharEqPattern<F> as Pattern<'a>>::Searcher)
667 where F: FnMut(char) -> bool;
669 impl<F> fmt::Debug for CharPredicateSearcher<'_, F>
670 where F: FnMut(char) -> bool
672 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
673 f.debug_struct("CharPredicateSearcher")
674 .field("haystack", &self.0.haystack)
675 .field("char_indices", &self.0.char_indices)
679 unsafe impl<'a, F> Searcher<'a> for CharPredicateSearcher<'a, F>
680 where F: FnMut(char) -> bool
682 searcher_methods!(forward);
685 unsafe impl<'a, F> ReverseSearcher<'a> for CharPredicateSearcher<'a, F>
686 where F: FnMut(char) -> bool
688 searcher_methods!(reverse);
691 impl<'a, F> DoubleEndedSearcher<'a> for CharPredicateSearcher<'a, F>
692 where F: FnMut(char) -> bool {}
694 /// Searches for chars that match the given predicate
695 impl<'a, F> Pattern<'a> for F where F: FnMut(char) -> bool {
696 pattern_methods!(CharPredicateSearcher<'a, F>, MultiCharEqPattern, CharPredicateSearcher);
699 /////////////////////////////////////////////////////////////////////////////
701 /////////////////////////////////////////////////////////////////////////////
703 /// Delegates to the `&str` impl.
704 impl<'a, 'b, 'c> Pattern<'a> for &'c &'b str {
705 pattern_methods!(StrSearcher<'a, 'b>, |&s| s, |s| s);
708 /////////////////////////////////////////////////////////////////////////////
710 /////////////////////////////////////////////////////////////////////////////
712 /// Non-allocating substring search.
714 /// Will handle the pattern `""` as returning empty matches at each character
716 impl<'a, 'b> Pattern<'a> for &'b str {
717 type Searcher = StrSearcher<'a, 'b>;
720 fn into_searcher(self, haystack: &'a str) -> StrSearcher<'a, 'b> {
721 StrSearcher::new(haystack, self)
724 /// Checks whether the pattern matches at the front of the haystack
726 fn is_prefix_of(self, haystack: &'a str) -> bool {
727 haystack.is_char_boundary(self.len()) &&
728 self == &haystack[..self.len()]
731 /// Checks whether the pattern matches at the back of the haystack
733 fn is_suffix_of(self, haystack: &'a str) -> bool {
734 self.len() <= haystack.len() &&
735 haystack.is_char_boundary(haystack.len() - self.len()) &&
736 self == &haystack[haystack.len() - self.len()..]
741 /////////////////////////////////////////////////////////////////////////////
742 // Two Way substring searcher
743 /////////////////////////////////////////////////////////////////////////////
745 #[derive(Clone, Debug)]
746 /// Associated type for `<&str as Pattern<'a>>::Searcher`.
747 pub struct StrSearcher<'a, 'b> {
751 searcher: StrSearcherImpl,
754 #[derive(Clone, Debug)]
755 enum StrSearcherImpl {
757 TwoWay(TwoWaySearcher),
760 #[derive(Clone, Debug)]
768 impl<'a, 'b> StrSearcher<'a, 'b> {
769 fn new(haystack: &'a str, needle: &'b str) -> StrSearcher<'a, 'b> {
770 if needle.is_empty() {
774 searcher: StrSearcherImpl::Empty(EmptyNeedle {
785 searcher: StrSearcherImpl::TwoWay(
786 TwoWaySearcher::new(needle.as_bytes(), haystack.len())
793 unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> {
795 fn haystack(&self) -> &'a str {
800 fn next(&mut self) -> SearchStep {
801 match self.searcher {
802 StrSearcherImpl::Empty(ref mut searcher) => {
803 // empty needle rejects every char and matches every empty string between them
804 let is_match = searcher.is_match_fw;
805 searcher.is_match_fw = !searcher.is_match_fw;
806 let pos = searcher.position;
807 match self.haystack[pos..].chars().next() {
808 _ if is_match => SearchStep::Match(pos, pos),
809 None => SearchStep::Done,
811 searcher.position += ch.len_utf8();
812 SearchStep::Reject(pos, searcher.position)
816 StrSearcherImpl::TwoWay(ref mut searcher) => {
817 // TwoWaySearcher produces valid *Match* indices that split at char boundaries
818 // as long as it does correct matching and that haystack and needle are
820 // *Rejects* from the algorithm can fall on any indices, but we will walk them
821 // manually to the next character boundary, so that they are utf-8 safe.
822 if searcher.position == self.haystack.len() {
823 return SearchStep::Done;
825 let is_long = searcher.memory == usize::MAX;
826 match searcher.next::<RejectAndMatch>(self.haystack.as_bytes(),
827 self.needle.as_bytes(),
830 SearchStep::Reject(a, mut b) => {
831 // skip to next char boundary
832 while !self.haystack.is_char_boundary(b) {
835 searcher.position = cmp::max(b, searcher.position);
836 SearchStep::Reject(a, b)
838 otherwise => otherwise,
845 fn next_match(&mut self) -> Option<(usize, usize)> {
846 match self.searcher {
847 StrSearcherImpl::Empty(..) => {
850 SearchStep::Match(a, b) => return Some((a, b)),
851 SearchStep::Done => return None,
852 SearchStep::Reject(..) => { }
856 StrSearcherImpl::TwoWay(ref mut searcher) => {
857 let is_long = searcher.memory == usize::MAX;
858 // write out `true` and `false` cases to encourage the compiler
859 // to specialize the two cases separately.
861 searcher.next::<MatchOnly>(self.haystack.as_bytes(),
862 self.needle.as_bytes(),
865 searcher.next::<MatchOnly>(self.haystack.as_bytes(),
866 self.needle.as_bytes(),
874 unsafe impl<'a, 'b> ReverseSearcher<'a> for StrSearcher<'a, 'b> {
876 fn next_back(&mut self) -> SearchStep {
877 match self.searcher {
878 StrSearcherImpl::Empty(ref mut searcher) => {
879 let is_match = searcher.is_match_bw;
880 searcher.is_match_bw = !searcher.is_match_bw;
881 let end = searcher.end;
882 match self.haystack[..end].chars().next_back() {
883 _ if is_match => SearchStep::Match(end, end),
884 None => SearchStep::Done,
886 searcher.end -= ch.len_utf8();
887 SearchStep::Reject(searcher.end, end)
891 StrSearcherImpl::TwoWay(ref mut searcher) => {
892 if searcher.end == 0 {
893 return SearchStep::Done;
895 let is_long = searcher.memory == usize::MAX;
896 match searcher.next_back::<RejectAndMatch>(self.haystack.as_bytes(),
897 self.needle.as_bytes(),
900 SearchStep::Reject(mut a, b) => {
901 // skip to next char boundary
902 while !self.haystack.is_char_boundary(a) {
905 searcher.end = cmp::min(a, searcher.end);
906 SearchStep::Reject(a, b)
908 otherwise => otherwise,
915 fn next_match_back(&mut self) -> Option<(usize, usize)> {
916 match self.searcher {
917 StrSearcherImpl::Empty(..) => {
919 match self.next_back() {
920 SearchStep::Match(a, b) => return Some((a, b)),
921 SearchStep::Done => return None,
922 SearchStep::Reject(..) => { }
926 StrSearcherImpl::TwoWay(ref mut searcher) => {
927 let is_long = searcher.memory == usize::MAX;
928 // write out `true` and `false`, like `next_match`
930 searcher.next_back::<MatchOnly>(self.haystack.as_bytes(),
931 self.needle.as_bytes(),
934 searcher.next_back::<MatchOnly>(self.haystack.as_bytes(),
935 self.needle.as_bytes(),
943 /// The internal state of the two-way substring search algorithm.
944 #[derive(Clone, Debug)]
945 struct TwoWaySearcher {
947 /// critical factorization index
949 /// critical factorization index for reversed needle
950 crit_pos_back: usize,
952 /// `byteset` is an extension (not part of the two way algorithm);
953 /// it's a 64-bit "fingerprint" where each set bit `j` corresponds
954 /// to a (byte & 63) == j present in the needle.
960 /// index into needle before which we have already matched
962 /// index into needle after which we have already matched
967 This is the Two-Way search algorithm, which was introduced in the paper:
968 Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.
970 Here's some background information.
972 A *word* is a string of symbols. The *length* of a word should be a familiar
973 notion, and here we denote it for any word x by |x|.
974 (We also allow for the possibility of the *empty word*, a word of length zero).
976 If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
977 *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
978 For example, both 1 and 2 are periods for the string "aa". As another example,
979 the only period of the string "abcd" is 4.
981 We denote by period(x) the *smallest* period of x (provided that x is non-empty).
982 This is always well-defined since every non-empty word x has at least one period,
983 |x|. We sometimes call this *the period* of x.
985 If u, v and x are words such that x = uv, where uv is the concatenation of u and
986 v, then we say that (u, v) is a *factorization* of x.
988 Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
989 that both of the following hold
991 - either w is a suffix of u or u is a suffix of w
992 - either w is a prefix of v or v is a prefix of w
994 then w is said to be a *repetition* for the factorization (u, v).
996 Just to unpack this, there are four possibilities here. Let w = "abc". Then we
999 - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
1000 - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
1001 - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
1002 - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")
1004 Note that the word vu is a repetition for any factorization (u,v) of x = uv,
1005 so every factorization has at least one repetition.
1007 If x is a string and (u, v) is a factorization for x, then a *local period* for
1008 (u, v) is an integer r such that there is some word w such that |w| = r and w is
1009 a repetition for (u, v).
1011 We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
1012 call this *the local period* of (u, v). Provided that x = uv is non-empty, this
1013 is well-defined (because each non-empty word has at least one factorization, as
1016 It can be proven that the following is an equivalent definition of a local period
1017 for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
1018 all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
1019 defined. (i.e. i > 0 and i + r < |x|).
1021 Using the above reformulation, it is easy to prove that
1023 1 <= local_period(u, v) <= period(uv)
1025 A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
1026 *critical factorization*.
1028 The algorithm hinges on the following theorem, which is stated without proof:
1030 **Critical Factorization Theorem** Any word x has at least one critical
1031 factorization (u, v) such that |u| < period(x).
1033 The purpose of maximal_suffix is to find such a critical factorization.
1035 If the period is short, compute another factorization x = u' v' to use
1036 for reverse search, chosen instead so that |v'| < period(x).
1039 impl TwoWaySearcher {
1040 fn new(needle: &[u8], end: usize) -> TwoWaySearcher {
1041 let (crit_pos_false, period_false) = TwoWaySearcher::maximal_suffix(needle, false);
1042 let (crit_pos_true, period_true) = TwoWaySearcher::maximal_suffix(needle, true);
1044 let (crit_pos, period) =
1045 if crit_pos_false > crit_pos_true {
1046 (crit_pos_false, period_false)
1048 (crit_pos_true, period_true)
1051 // A particularly readable explanation of what's going on here can be found
1052 // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
1053 // see the code for "Algorithm CP" on p. 323.
1055 // What's going on is we have some critical factorization (u, v) of the
1056 // needle, and we want to determine whether u is a suffix of
1057 // &v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
1058 // "Algorithm CP2", which is optimized for when the period of the needle
1060 if &needle[..crit_pos] == &needle[period.. period + crit_pos] {
1061 // short period case -- the period is exact
1062 // compute a separate critical factorization for the reversed needle
1063 // x = u' v' where |v'| < period(x).
1065 // This is sped up by the period being known already.
1066 // Note that a case like x = "acba" may be factored exactly forwards
1067 // (crit_pos = 1, period = 3) while being factored with approximate
1068 // period in reverse (crit_pos = 2, period = 2). We use the given
1069 // reverse factorization but keep the exact period.
1070 let crit_pos_back = needle.len() - cmp::max(
1071 TwoWaySearcher::reverse_maximal_suffix(needle, period, false),
1072 TwoWaySearcher::reverse_maximal_suffix(needle, period, true));
1078 byteset: Self::byteset_create(&needle[..period]),
1083 memory_back: needle.len(),
1086 // long period case -- we have an approximation to the actual period,
1087 // and don't use memorization.
1089 // Approximate the period by lower bound max(|u|, |v|) + 1.
1090 // The critical factorization is efficient to use for both forward and
1095 crit_pos_back: crit_pos,
1096 period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
1097 byteset: Self::byteset_create(needle),
1101 memory: usize::MAX, // Dummy value to signify that the period is long
1102 memory_back: usize::MAX,
1108 fn byteset_create(bytes: &[u8]) -> u64 {
1109 bytes.iter().fold(0, |a, &b| (1 << (b & 0x3f)) | a)
1113 fn byteset_contains(&self, byte: u8) -> bool {
1114 (self.byteset >> ((byte & 0x3f) as usize)) & 1 != 0
1117 // One of the main ideas of Two-Way is that we factorize the needle into
1118 // two halves, (u, v), and begin trying to find v in the haystack by scanning
1119 // left to right. If v matches, we try to match u by scanning right to left.
1120 // How far we can jump when we encounter a mismatch is all based on the fact
1121 // that (u, v) is a critical factorization for the needle.
1123 fn next<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool)
1125 where S: TwoWayStrategy
1127 // `next()` uses `self.position` as its cursor
1128 let old_pos = self.position;
1129 let needle_last = needle.len() - 1;
1131 // Check that we have room to search in
1132 // position + needle_last can not overflow if we assume slices
1133 // are bounded by isize's range.
1134 let tail_byte = match haystack.get(self.position + needle_last) {
1137 self.position = haystack.len();
1138 return S::rejecting(old_pos, self.position);
1142 if S::use_early_reject() && old_pos != self.position {
1143 return S::rejecting(old_pos, self.position);
1146 // Quickly skip by large portions unrelated to our substring
1147 if !self.byteset_contains(tail_byte) {
1148 self.position += needle.len();
1155 // See if the right part of the needle matches
1156 let start = if long_period { self.crit_pos }
1157 else { cmp::max(self.crit_pos, self.memory) };
1158 for i in start..needle.len() {
1159 if needle[i] != haystack[self.position + i] {
1160 self.position += i - self.crit_pos + 1;
1168 // See if the left part of the needle matches
1169 let start = if long_period { 0 } else { self.memory };
1170 for i in (start..self.crit_pos).rev() {
1171 if needle[i] != haystack[self.position + i] {
1172 self.position += self.period;
1174 self.memory = needle.len() - self.period;
1180 // We have found a match!
1181 let match_pos = self.position;
1183 // Note: add self.period instead of needle.len() to have overlapping matches
1184 self.position += needle.len();
1186 self.memory = 0; // set to needle.len() - self.period for overlapping matches
1189 return S::matching(match_pos, match_pos + needle.len());
1193 // Follows the ideas in `next()`.
1195 // The definitions are symmetrical, with period(x) = period(reverse(x))
1196 // and local_period(u, v) = local_period(reverse(v), reverse(u)), so if (u, v)
1197 // is a critical factorization, so is (reverse(v), reverse(u)).
1199 // For the reverse case we have computed a critical factorization x = u' v'
1200 // (field `crit_pos_back`). We need |u| < period(x) for the forward case and
1201 // thus |v'| < period(x) for the reverse.
1203 // To search in reverse through the haystack, we search forward through
1204 // a reversed haystack with a reversed needle, matching first u' and then v'.
1206 fn next_back<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool)
1208 where S: TwoWayStrategy
1210 // `next_back()` uses `self.end` as its cursor -- so that `next()` and `next_back()`
1212 let old_end = self.end;
1214 // Check that we have room to search in
1215 // end - needle.len() will wrap around when there is no more room,
1216 // but due to slice length limits it can never wrap all the way back
1217 // into the length of haystack.
1218 let front_byte = match haystack.get(self.end.wrapping_sub(needle.len())) {
1222 return S::rejecting(0, old_end);
1226 if S::use_early_reject() && old_end != self.end {
1227 return S::rejecting(self.end, old_end);
1230 // Quickly skip by large portions unrelated to our substring
1231 if !self.byteset_contains(front_byte) {
1232 self.end -= needle.len();
1234 self.memory_back = needle.len();
1239 // See if the left part of the needle matches
1240 let crit = if long_period { self.crit_pos_back }
1241 else { cmp::min(self.crit_pos_back, self.memory_back) };
1242 for i in (0..crit).rev() {
1243 if needle[i] != haystack[self.end - needle.len() + i] {
1244 self.end -= self.crit_pos_back - i;
1246 self.memory_back = needle.len();
1252 // See if the right part of the needle matches
1253 let needle_end = if long_period { needle.len() }
1254 else { self.memory_back };
1255 for i in self.crit_pos_back..needle_end {
1256 if needle[i] != haystack[self.end - needle.len() + i] {
1257 self.end -= self.period;
1259 self.memory_back = self.period;
1265 // We have found a match!
1266 let match_pos = self.end - needle.len();
1267 // Note: sub self.period instead of needle.len() to have overlapping matches
1268 self.end -= needle.len();
1270 self.memory_back = needle.len();
1273 return S::matching(match_pos, match_pos + needle.len());
1277 // Compute the maximal suffix of `arr`.
1279 // The maximal suffix is a possible critical factorization (u, v) of `arr`.
1281 // Returns (`i`, `p`) where `i` is the starting index of v and `p` is the
1284 // `order_greater` determines if lexical order is `<` or `>`. Both
1285 // orders must be computed -- the ordering with the largest `i` gives
1286 // a critical factorization.
1288 // For long period cases, the resulting period is not exact (it is too short).
1290 fn maximal_suffix(arr: &[u8], order_greater: bool) -> (usize, usize) {
1291 let mut left = 0; // Corresponds to i in the paper
1292 let mut right = 1; // Corresponds to j in the paper
1293 let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1294 // to match 0-based indexing.
1295 let mut period = 1; // Corresponds to p in the paper
1297 while let Some(&a) = arr.get(right + offset) {
1298 // `left` will be inbounds when `right` is.
1299 let b = arr[left + offset];
1300 if (a < b && !order_greater) || (a > b && order_greater) {
1301 // Suffix is smaller, period is entire prefix so far.
1302 right += offset + 1;
1304 period = right - left;
1306 // Advance through repetition of the current period.
1307 if offset + 1 == period {
1308 right += offset + 1;
1314 // Suffix is larger, start over from current location.
1324 // Compute the maximal suffix of the reverse of `arr`.
1326 // The maximal suffix is a possible critical factorization (u', v') of `arr`.
1328 // Returns `i` where `i` is the starting index of v', from the back;
1329 // returns immediately when a period of `known_period` is reached.
1331 // `order_greater` determines if lexical order is `<` or `>`. Both
1332 // orders must be computed -- the ordering with the largest `i` gives
1333 // a critical factorization.
1335 // For long period cases, the resulting period is not exact (it is too short).
1336 fn reverse_maximal_suffix(arr: &[u8], known_period: usize,
1337 order_greater: bool) -> usize
1339 let mut left = 0; // Corresponds to i in the paper
1340 let mut right = 1; // Corresponds to j in the paper
1341 let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1342 // to match 0-based indexing.
1343 let mut period = 1; // Corresponds to p in the paper
1346 while right + offset < n {
1347 let a = arr[n - (1 + right + offset)];
1348 let b = arr[n - (1 + left + offset)];
1349 if (a < b && !order_greater) || (a > b && order_greater) {
1350 // Suffix is smaller, period is entire prefix so far.
1351 right += offset + 1;
1353 period = right - left;
1355 // Advance through repetition of the current period.
1356 if offset + 1 == period {
1357 right += offset + 1;
1363 // Suffix is larger, start over from current location.
1369 if period == known_period {
1373 debug_assert!(period <= known_period);
1378 // TwoWayStrategy allows the algorithm to either skip non-matches as quickly
1379 // as possible, or to work in a mode where it emits Rejects relatively quickly.
1380 trait TwoWayStrategy {
1382 fn use_early_reject() -> bool;
1383 fn rejecting(a: usize, b: usize) -> Self::Output;
1384 fn matching(a: usize, b: usize) -> Self::Output;
1387 /// Skip to match intervals as quickly as possible
1390 impl TwoWayStrategy for MatchOnly {
1391 type Output = Option<(usize, usize)>;
1394 fn use_early_reject() -> bool { false }
1396 fn rejecting(_a: usize, _b: usize) -> Self::Output { None }
1398 fn matching(a: usize, b: usize) -> Self::Output { Some((a, b)) }
1401 /// Emit Rejects regularly
1402 enum RejectAndMatch { }
1404 impl TwoWayStrategy for RejectAndMatch {
1405 type Output = SearchStep;
1408 fn use_early_reject() -> bool { true }
1410 fn rejecting(a: usize, b: usize) -> Self::Output { SearchStep::Reject(a, b) }
1412 fn matching(a: usize, b: usize) -> Self::Output { SearchStep::Match(a, b) }