1 //! The string Pattern API.
3 //! For more details, see the traits `Pattern`, `Searcher`,
4 //! `ReverseSearcher` and `DoubleEndedSearcher`.
6 #![unstable(feature = "pattern",
7 reason = "API not fully fleshed out and ready to be stabilized",
19 /// A `Pattern<'a>` expresses that the implementing type
20 /// can be used as a string pattern for searching in a `&'a str`.
22 /// For example, both `'a'` and `"aa"` are patterns that
23 /// would match at index `1` in the string `"baaaab"`.
25 /// The trait itself acts as a builder for an associated
26 /// `Searcher` type, which does the actual work of finding
27 /// occurrences of the pattern in a string.
28 pub trait Pattern<'a>: Sized {
29 /// Associated searcher for this pattern
30 type Searcher: Searcher<'a>;
32 /// Constructs the associated searcher from
33 /// `self` and the `haystack` to search in.
34 fn into_searcher(self, haystack: &'a str) -> Self::Searcher;
36 /// Checks whether the pattern matches anywhere in the haystack
38 fn is_contained_in(self, haystack: &'a str) -> bool {
39 self.into_searcher(haystack).next_match().is_some()
42 /// Checks whether the pattern matches at the front of the haystack
44 fn is_prefix_of(self, haystack: &'a str) -> bool {
45 match self.into_searcher(haystack).next() {
46 SearchStep::Match(0, _) => true,
51 /// Checks whether the pattern matches at the back of the haystack
53 fn is_suffix_of(self, haystack: &'a str) -> bool
54 where Self::Searcher: ReverseSearcher<'a>
56 match self.into_searcher(haystack).next_back() {
57 SearchStep::Match(_, j) if haystack.len() == j => true,
65 /// Result of calling `Searcher::next()` or `ReverseSearcher::next_back()`.
66 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
68 /// Expresses that a match of the pattern has been found at
71 /// Expresses that `haystack[a..b]` has been rejected as a possible match
74 /// Note that there might be more than one `Reject` between two `Match`es,
75 /// there is no requirement for them to be combined into one.
77 /// Expresses that every byte of the haystack has been visited, ending
82 /// A searcher for a string pattern.
84 /// This trait provides methods for searching for non-overlapping
85 /// matches of a pattern starting from the front (left) of a string.
87 /// It will be implemented by associated `Searcher`
88 /// types of the `Pattern` trait.
90 /// The trait is marked unsafe because the indices returned by the
91 /// `next()` methods are required to lie on valid utf8 boundaries in
92 /// the haystack. This enables consumers of this trait to
93 /// slice the haystack without additional runtime checks.
94 pub unsafe trait Searcher<'a> {
95 /// Getter for the underlying string to be searched in
97 /// Will always return the same `&str`
98 fn haystack(&self) -> &'a str;
100 /// Performs the next search step starting from the front.
102 /// - Returns `Match(a, b)` if `haystack[a..b]` matches the pattern.
103 /// - Returns `Reject(a, b)` if `haystack[a..b]` can not match the
104 /// pattern, even partially.
105 /// - Returns `Done` if every byte of the haystack has been visited
107 /// The stream of `Match` and `Reject` values up to a `Done`
108 /// will contain index ranges that are adjacent, non-overlapping,
109 /// covering the whole haystack, and laying on utf8 boundaries.
111 /// A `Match` result needs to contain the whole matched pattern,
112 /// however `Reject` results may be split up into arbitrary
113 /// many adjacent fragments. Both ranges may have zero length.
115 /// As an example, the pattern `"aaa"` and the haystack `"cbaaaaab"`
116 /// might produce the stream
117 /// `[Reject(0, 1), Reject(1, 2), Match(2, 5), Reject(5, 8)]`
118 fn next(&mut self) -> SearchStep;
120 /// Find the next `Match` result. See `next()`
122 /// Unlike next(), there is no guarantee that the returned ranges
123 /// of this and next_reject will overlap. This will return (start_match, end_match),
124 /// where start_match is the index of where the match begins, and end_match is
125 /// the index after the end of the match.
127 fn next_match(&mut self) -> Option<(usize, usize)> {
130 SearchStep::Match(a, b) => return Some((a, b)),
131 SearchStep::Done => return None,
137 /// Find the next `Reject` result. See `next()` and `next_match()`
139 /// Unlike next(), there is no guarantee that the returned ranges
140 /// of this and next_match will overlap.
142 fn next_reject(&mut self) -> Option<(usize, usize)> {
145 SearchStep::Reject(a, b) => return Some((a, b)),
146 SearchStep::Done => return None,
153 /// A reverse searcher for a string pattern.
155 /// This trait provides methods for searching for non-overlapping
156 /// matches of a pattern starting from the back (right) of a string.
158 /// It will be implemented by associated `Searcher`
159 /// types of the `Pattern` trait if the pattern supports searching
160 /// for it from the back.
162 /// The index ranges returned by this trait are not required
163 /// to exactly match those of the forward search in reverse.
165 /// For the reason why this trait is marked unsafe, see them
166 /// parent trait `Searcher`.
167 pub unsafe trait ReverseSearcher<'a>: Searcher<'a> {
168 /// Performs the next search step starting from the back.
170 /// - Returns `Match(a, b)` if `haystack[a..b]` matches the pattern.
171 /// - Returns `Reject(a, b)` if `haystack[a..b]` can not match the
172 /// pattern, even partially.
173 /// - Returns `Done` if every byte of the haystack has been visited
175 /// The stream of `Match` and `Reject` values up to a `Done`
176 /// will contain index ranges that are adjacent, non-overlapping,
177 /// covering the whole haystack, and laying on utf8 boundaries.
179 /// A `Match` result needs to contain the whole matched pattern,
180 /// however `Reject` results may be split up into arbitrary
181 /// many adjacent fragments. Both ranges may have zero length.
183 /// As an example, the pattern `"aaa"` and the haystack `"cbaaaaab"`
184 /// might produce the stream
185 /// `[Reject(7, 8), Match(4, 7), Reject(1, 4), Reject(0, 1)]`
186 fn next_back(&mut self) -> SearchStep;
188 /// Find the next `Match` result. See `next_back()`
190 fn next_match_back(&mut self) -> Option<(usize, usize)>{
192 match self.next_back() {
193 SearchStep::Match(a, b) => return Some((a, b)),
194 SearchStep::Done => return None,
200 /// Find the next `Reject` result. See `next_back()`
202 fn next_reject_back(&mut self) -> Option<(usize, usize)>{
204 match self.next_back() {
205 SearchStep::Reject(a, b) => return Some((a, b)),
206 SearchStep::Done => return None,
213 /// A marker trait to express that a `ReverseSearcher`
214 /// can be used for a `DoubleEndedIterator` implementation.
216 /// For this, the impl of `Searcher` and `ReverseSearcher` need
217 /// to follow these conditions:
219 /// - All results of `next()` need to be identical
220 /// to the results of `next_back()` in reverse order.
221 /// - `next()` and `next_back()` need to behave as
222 /// the two ends of a range of values, that is they
223 /// can not "walk past each other".
227 /// `char::Searcher` is a `DoubleEndedSearcher` because searching for a
228 /// `char` only requires looking at one at a time, which behaves the same
231 /// `(&str)::Searcher` is not a `DoubleEndedSearcher` because
232 /// the pattern `"aa"` in the haystack `"aaa"` matches as either
233 /// `"[aa]a"` or `"a[aa]"`, depending from which side it is searched.
234 pub trait DoubleEndedSearcher<'a>: ReverseSearcher<'a> {}
237 /////////////////////////////////////////////////////////////////////////////
239 /////////////////////////////////////////////////////////////////////////////
241 /// Associated type for `<char as Pattern<'a>>::Searcher`.
242 #[derive(Clone, Debug)]
243 pub struct CharSearcher<'a> {
245 // safety invariant: `finger`/`finger_back` must be a valid utf8 byte index of `haystack`
246 // This invariant can be broken *within* next_match and next_match_back, however
247 // they must exit with fingers on valid code point boundaries.
249 /// `finger` is the current byte index of the forward search.
250 /// Imagine that it exists before the byte at its index, i.e.
251 /// `haystack[finger]` is the first byte of the slice we must inspect during
252 /// forward searching
254 /// `finger_back` is the current byte index of the reverse search.
255 /// Imagine that it exists after the byte at its index, i.e.
256 /// haystack[finger_back - 1] is the last byte of the slice we must inspect during
257 /// forward searching (and thus the first byte to be inspected when calling next_back())
259 /// The character being searched for
262 // safety invariant: `utf8_size` must be less than 5
263 /// The number of bytes `needle` takes up when encoded in utf8
265 /// A utf8 encoded copy of the `needle`
266 utf8_encoded: [u8; 4],
269 unsafe impl<'a> Searcher<'a> for CharSearcher<'a> {
271 fn haystack(&self) -> &'a str {
275 fn next(&mut self) -> SearchStep {
276 let old_finger = self.finger;
277 let slice = unsafe { self.haystack.get_unchecked(old_finger..self.finger_back) };
278 let mut iter = slice.chars();
279 let old_len = iter.iter.len();
280 if let Some(ch) = iter.next() {
281 // add byte offset of current character
282 // without re-encoding as utf-8
283 self.finger += old_len - iter.iter.len();
284 if ch == self.needle {
285 SearchStep::Match(old_finger, self.finger)
287 SearchStep::Reject(old_finger, self.finger)
294 fn next_match(&mut self) -> Option<(usize, usize)> {
296 // get the haystack after the last character found
297 let bytes = if let Some(slice) = self.haystack.as_bytes()
298 .get(self.finger..self.finger_back) {
303 // the last byte of the utf8 encoded needle
304 let last_byte = unsafe { *self.utf8_encoded.get_unchecked(self.utf8_size - 1) };
305 if let Some(index) = memchr::memchr(last_byte, bytes) {
306 // The new finger is the index of the byte we found,
307 // plus one, since we memchr'd for the last byte of the character.
309 // Note that this doesn't always give us a finger on a UTF8 boundary.
310 // If we *didn't* find our character
311 // we may have indexed to the non-last byte of a 3-byte or 4-byte character.
312 // We can't just skip to the next valid starting byte because a character like
313 // ꁁ (U+A041 YI SYLLABLE PA), utf-8 `EA 81 81` will have us always find
314 // the second byte when searching for the third.
316 // However, this is totally okay. While we have the invariant that
317 // self.finger is on a UTF8 boundary, this invariant is not relied upon
318 // within this method (it is relied upon in CharSearcher::next()).
320 // We only exit this method when we reach the end of the string, or if we
321 // find something. When we find something the `finger` will be set
322 // to a UTF8 boundary.
323 self.finger += index + 1;
324 if self.finger >= self.utf8_size {
325 let found_char = self.finger - self.utf8_size;
326 if let Some(slice) = self.haystack.as_bytes().get(found_char..self.finger) {
327 if slice == &self.utf8_encoded[0..self.utf8_size] {
328 return Some((found_char, self.finger));
333 // found nothing, exit
334 self.finger = self.finger_back;
340 // let next_reject use the default implementation from the Searcher trait
343 unsafe impl<'a> ReverseSearcher<'a> for CharSearcher<'a> {
345 fn next_back(&mut self) -> SearchStep {
346 let old_finger = self.finger_back;
347 let slice = unsafe { self.haystack.get_unchecked(self.finger..old_finger) };
348 let mut iter = slice.chars();
349 let old_len = iter.iter.len();
350 if let Some(ch) = iter.next_back() {
351 // subtract byte offset of current character
352 // without re-encoding as utf-8
353 self.finger_back -= old_len - iter.iter.len();
354 if ch == self.needle {
355 SearchStep::Match(self.finger_back, old_finger)
357 SearchStep::Reject(self.finger_back, old_finger)
364 fn next_match_back(&mut self) -> Option<(usize, usize)> {
365 let haystack = self.haystack.as_bytes();
367 // get the haystack up to but not including the last character searched
368 let bytes = if let Some(slice) = haystack.get(self.finger..self.finger_back) {
373 // the last byte of the utf8 encoded needle
374 let last_byte = unsafe { *self.utf8_encoded.get_unchecked(self.utf8_size - 1) };
375 if let Some(index) = memchr::memrchr(last_byte, bytes) {
376 // we searched a slice that was offset by self.finger,
377 // add self.finger to recoup the original index
378 let index = self.finger + index;
379 // memrchr will return the index of the byte we wish to
380 // find. In case of an ASCII character, this is indeed
381 // were we wish our new finger to be ("after" the found
382 // char in the paradigm of reverse iteration). For
383 // multibyte chars we need to skip down by the number of more
384 // bytes they have than ASCII
385 let shift = self.utf8_size - 1;
387 let found_char = index - shift;
388 if let Some(slice) = haystack.get(found_char..(found_char + self.utf8_size)) {
389 if slice == &self.utf8_encoded[0..self.utf8_size] {
390 // move finger to before the character found (i.e., at its start index)
391 self.finger_back = found_char;
392 return Some((self.finger_back, self.finger_back + self.utf8_size));
396 // We can't use finger_back = index - size + 1 here. If we found the last char
397 // of a different-sized character (or the middle byte of a different character)
398 // we need to bump the finger_back down to `index`. This similarly makes
399 // `finger_back` have the potential to no longer be on a boundary,
400 // but this is OK since we only exit this function on a boundary
401 // or when the haystack has been searched completely.
403 // Unlike next_match this does not
404 // have the problem of repeated bytes in utf-8 because
405 // we're searching for the last byte, and we can only have
406 // found the last byte when searching in reverse.
407 self.finger_back = index;
409 self.finger_back = self.finger;
410 // found nothing, exit
416 // let next_reject_back use the default implementation from the Searcher trait
419 impl<'a> DoubleEndedSearcher<'a> for CharSearcher<'a> {}
421 /// Searches for chars that are equal to a given char
422 impl<'a> Pattern<'a> for char {
423 type Searcher = CharSearcher<'a>;
426 fn into_searcher(self, haystack: &'a str) -> Self::Searcher {
427 let mut utf8_encoded = [0; 4];
428 let utf8_size = self.encode_utf8(&mut utf8_encoded).len();
432 finger_back: haystack.len(),
440 fn is_contained_in(self, haystack: &'a str) -> bool {
441 if (self as u32) < 128 {
442 haystack.as_bytes().contains(&(self as u8))
444 let mut buffer = [0u8; 4];
445 self.encode_utf8(&mut buffer).is_contained_in(haystack)
450 fn is_prefix_of(self, haystack: &'a str) -> bool {
451 if let Some(ch) = haystack.chars().next() {
459 fn is_suffix_of(self, haystack: &'a str) -> bool where Self::Searcher: ReverseSearcher<'a>
461 if let Some(ch) = haystack.chars().next_back() {
469 /////////////////////////////////////////////////////////////////////////////
470 // Impl for a MultiCharEq wrapper
471 /////////////////////////////////////////////////////////////////////////////
475 fn matches(&mut self, c: char) -> bool;
478 impl<F> MultiCharEq for F where F: FnMut(char) -> bool {
480 fn matches(&mut self, c: char) -> bool { (*self)(c) }
483 impl MultiCharEq for &[char] {
485 fn matches(&mut self, c: char) -> bool {
486 self.iter().any(|&m| { m == c })
490 struct MultiCharEqPattern<C: MultiCharEq>(C);
492 #[derive(Clone, Debug)]
493 struct MultiCharEqSearcher<'a, C: MultiCharEq> {
496 char_indices: super::CharIndices<'a>,
499 impl<'a, C: MultiCharEq> Pattern<'a> for MultiCharEqPattern<C> {
500 type Searcher = MultiCharEqSearcher<'a, C>;
503 fn into_searcher(self, haystack: &'a str) -> MultiCharEqSearcher<'a, C> {
504 MultiCharEqSearcher {
507 char_indices: haystack.char_indices(),
512 unsafe impl<'a, C: MultiCharEq> Searcher<'a> for MultiCharEqSearcher<'a, C> {
514 fn haystack(&self) -> &'a str {
519 fn next(&mut self) -> SearchStep {
520 let s = &mut self.char_indices;
521 // Compare lengths of the internal byte slice iterator
522 // to find length of current char
523 let pre_len = s.iter.iter.len();
524 if let Some((i, c)) = s.next() {
525 let len = s.iter.iter.len();
526 let char_len = pre_len - len;
527 if self.char_eq.matches(c) {
528 return SearchStep::Match(i, i + char_len);
530 return SearchStep::Reject(i, i + char_len);
537 unsafe impl<'a, C: MultiCharEq> ReverseSearcher<'a> for MultiCharEqSearcher<'a, C> {
539 fn next_back(&mut self) -> SearchStep {
540 let s = &mut self.char_indices;
541 // Compare lengths of the internal byte slice iterator
542 // to find length of current char
543 let pre_len = s.iter.iter.len();
544 if let Some((i, c)) = s.next_back() {
545 let len = s.iter.iter.len();
546 let char_len = pre_len - len;
547 if self.char_eq.matches(c) {
548 return SearchStep::Match(i, i + char_len);
550 return SearchStep::Reject(i, i + char_len);
557 impl<'a, C: MultiCharEq> DoubleEndedSearcher<'a> for MultiCharEqSearcher<'a, C> {}
559 /////////////////////////////////////////////////////////////////////////////
561 macro_rules! pattern_methods {
562 ($t:ty, $pmap:expr, $smap:expr) => {
566 fn into_searcher(self, haystack: &'a str) -> $t {
567 ($smap)(($pmap)(self).into_searcher(haystack))
571 fn is_contained_in(self, haystack: &'a str) -> bool {
572 ($pmap)(self).is_contained_in(haystack)
576 fn is_prefix_of(self, haystack: &'a str) -> bool {
577 ($pmap)(self).is_prefix_of(haystack)
581 fn is_suffix_of(self, haystack: &'a str) -> bool
582 where $t: ReverseSearcher<'a>
584 ($pmap)(self).is_suffix_of(haystack)
589 macro_rules! searcher_methods {
592 fn haystack(&self) -> &'a str {
596 fn next(&mut self) -> SearchStep {
600 fn next_match(&mut self) -> Option<(usize, usize)> {
604 fn next_reject(&mut self) -> Option<(usize, usize)> {
610 fn next_back(&mut self) -> SearchStep {
614 fn next_match_back(&mut self) -> Option<(usize, usize)> {
615 self.0.next_match_back()
618 fn next_reject_back(&mut self) -> Option<(usize, usize)> {
619 self.0.next_reject_back()
624 /////////////////////////////////////////////////////////////////////////////
626 /////////////////////////////////////////////////////////////////////////////
628 // Todo: Change / Remove due to ambiguity in meaning.
630 /// Associated type for `<&[char] as Pattern<'a>>::Searcher`.
631 #[derive(Clone, Debug)]
632 pub struct CharSliceSearcher<'a, 'b>(<MultiCharEqPattern<&'b [char]> as Pattern<'a>>::Searcher);
634 unsafe impl<'a, 'b> Searcher<'a> for CharSliceSearcher<'a, 'b> {
635 searcher_methods!(forward);
638 unsafe impl<'a, 'b> ReverseSearcher<'a> for CharSliceSearcher<'a, 'b> {
639 searcher_methods!(reverse);
642 impl<'a, 'b> DoubleEndedSearcher<'a> for CharSliceSearcher<'a, 'b> {}
644 /// Searches for chars that are equal to any of the chars in the array
645 impl<'a, 'b> Pattern<'a> for &'b [char] {
646 pattern_methods!(CharSliceSearcher<'a, 'b>, MultiCharEqPattern, CharSliceSearcher);
649 /////////////////////////////////////////////////////////////////////////////
650 // Impl for F: FnMut(char) -> bool
651 /////////////////////////////////////////////////////////////////////////////
653 /// Associated type for `<F as Pattern<'a>>::Searcher`.
655 pub struct CharPredicateSearcher<'a, F>(<MultiCharEqPattern<F> as Pattern<'a>>::Searcher)
656 where F: FnMut(char) -> bool;
658 impl<F> fmt::Debug for CharPredicateSearcher<'_, F>
659 where F: FnMut(char) -> bool
661 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
662 f.debug_struct("CharPredicateSearcher")
663 .field("haystack", &self.0.haystack)
664 .field("char_indices", &self.0.char_indices)
668 unsafe impl<'a, F> Searcher<'a> for CharPredicateSearcher<'a, F>
669 where F: FnMut(char) -> bool
671 searcher_methods!(forward);
674 unsafe impl<'a, F> ReverseSearcher<'a> for CharPredicateSearcher<'a, F>
675 where F: FnMut(char) -> bool
677 searcher_methods!(reverse);
680 impl<'a, F> DoubleEndedSearcher<'a> for CharPredicateSearcher<'a, F>
681 where F: FnMut(char) -> bool {}
683 /// Searches for chars that match the given predicate
684 impl<'a, F> Pattern<'a> for F where F: FnMut(char) -> bool {
685 pattern_methods!(CharPredicateSearcher<'a, F>, MultiCharEqPattern, CharPredicateSearcher);
688 /////////////////////////////////////////////////////////////////////////////
690 /////////////////////////////////////////////////////////////////////////////
692 /// Delegates to the `&str` impl.
693 impl<'a, 'b, 'c> Pattern<'a> for &'c &'b str {
694 pattern_methods!(StrSearcher<'a, 'b>, |&s| s, |s| s);
697 /////////////////////////////////////////////////////////////////////////////
699 /////////////////////////////////////////////////////////////////////////////
701 /// Non-allocating substring search.
703 /// Will handle the pattern `""` as returning empty matches at each character
705 impl<'a, 'b> Pattern<'a> for &'b str {
706 type Searcher = StrSearcher<'a, 'b>;
709 fn into_searcher(self, haystack: &'a str) -> StrSearcher<'a, 'b> {
710 StrSearcher::new(haystack, self)
713 /// Checks whether the pattern matches at the front of the haystack
715 fn is_prefix_of(self, haystack: &'a str) -> bool {
716 haystack.is_char_boundary(self.len()) &&
717 self == &haystack[..self.len()]
720 /// Checks whether the pattern matches at the back of the haystack
722 fn is_suffix_of(self, haystack: &'a str) -> bool {
723 self.len() <= haystack.len() &&
724 haystack.is_char_boundary(haystack.len() - self.len()) &&
725 self == &haystack[haystack.len() - self.len()..]
730 /////////////////////////////////////////////////////////////////////////////
731 // Two Way substring searcher
732 /////////////////////////////////////////////////////////////////////////////
734 #[derive(Clone, Debug)]
735 /// Associated type for `<&str as Pattern<'a>>::Searcher`.
736 pub struct StrSearcher<'a, 'b> {
740 searcher: StrSearcherImpl,
743 #[derive(Clone, Debug)]
744 enum StrSearcherImpl {
746 TwoWay(TwoWaySearcher),
749 #[derive(Clone, Debug)]
757 impl<'a, 'b> StrSearcher<'a, 'b> {
758 fn new(haystack: &'a str, needle: &'b str) -> StrSearcher<'a, 'b> {
759 if needle.is_empty() {
763 searcher: StrSearcherImpl::Empty(EmptyNeedle {
774 searcher: StrSearcherImpl::TwoWay(
775 TwoWaySearcher::new(needle.as_bytes(), haystack.len())
782 unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> {
784 fn haystack(&self) -> &'a str {
789 fn next(&mut self) -> SearchStep {
790 match self.searcher {
791 StrSearcherImpl::Empty(ref mut searcher) => {
792 // empty needle rejects every char and matches every empty string between them
793 let is_match = searcher.is_match_fw;
794 searcher.is_match_fw = !searcher.is_match_fw;
795 let pos = searcher.position;
796 match self.haystack[pos..].chars().next() {
797 _ if is_match => SearchStep::Match(pos, pos),
798 None => SearchStep::Done,
800 searcher.position += ch.len_utf8();
801 SearchStep::Reject(pos, searcher.position)
805 StrSearcherImpl::TwoWay(ref mut searcher) => {
806 // TwoWaySearcher produces valid *Match* indices that split at char boundaries
807 // as long as it does correct matching and that haystack and needle are
809 // *Rejects* from the algorithm can fall on any indices, but we will walk them
810 // manually to the next character boundary, so that they are utf-8 safe.
811 if searcher.position == self.haystack.len() {
812 return SearchStep::Done;
814 let is_long = searcher.memory == usize::MAX;
815 match searcher.next::<RejectAndMatch>(self.haystack.as_bytes(),
816 self.needle.as_bytes(),
819 SearchStep::Reject(a, mut b) => {
820 // skip to next char boundary
821 while !self.haystack.is_char_boundary(b) {
824 searcher.position = cmp::max(b, searcher.position);
825 SearchStep::Reject(a, b)
827 otherwise => otherwise,
834 fn next_match(&mut self) -> Option<(usize, usize)> {
835 match self.searcher {
836 StrSearcherImpl::Empty(..) => {
839 SearchStep::Match(a, b) => return Some((a, b)),
840 SearchStep::Done => return None,
841 SearchStep::Reject(..) => { }
845 StrSearcherImpl::TwoWay(ref mut searcher) => {
846 let is_long = searcher.memory == usize::MAX;
847 // write out `true` and `false` cases to encourage the compiler
848 // to specialize the two cases separately.
850 searcher.next::<MatchOnly>(self.haystack.as_bytes(),
851 self.needle.as_bytes(),
854 searcher.next::<MatchOnly>(self.haystack.as_bytes(),
855 self.needle.as_bytes(),
863 unsafe impl<'a, 'b> ReverseSearcher<'a> for StrSearcher<'a, 'b> {
865 fn next_back(&mut self) -> SearchStep {
866 match self.searcher {
867 StrSearcherImpl::Empty(ref mut searcher) => {
868 let is_match = searcher.is_match_bw;
869 searcher.is_match_bw = !searcher.is_match_bw;
870 let end = searcher.end;
871 match self.haystack[..end].chars().next_back() {
872 _ if is_match => SearchStep::Match(end, end),
873 None => SearchStep::Done,
875 searcher.end -= ch.len_utf8();
876 SearchStep::Reject(searcher.end, end)
880 StrSearcherImpl::TwoWay(ref mut searcher) => {
881 if searcher.end == 0 {
882 return SearchStep::Done;
884 let is_long = searcher.memory == usize::MAX;
885 match searcher.next_back::<RejectAndMatch>(self.haystack.as_bytes(),
886 self.needle.as_bytes(),
889 SearchStep::Reject(mut a, b) => {
890 // skip to next char boundary
891 while !self.haystack.is_char_boundary(a) {
894 searcher.end = cmp::min(a, searcher.end);
895 SearchStep::Reject(a, b)
897 otherwise => otherwise,
904 fn next_match_back(&mut self) -> Option<(usize, usize)> {
905 match self.searcher {
906 StrSearcherImpl::Empty(..) => {
908 match self.next_back() {
909 SearchStep::Match(a, b) => return Some((a, b)),
910 SearchStep::Done => return None,
911 SearchStep::Reject(..) => { }
915 StrSearcherImpl::TwoWay(ref mut searcher) => {
916 let is_long = searcher.memory == usize::MAX;
917 // write out `true` and `false`, like `next_match`
919 searcher.next_back::<MatchOnly>(self.haystack.as_bytes(),
920 self.needle.as_bytes(),
923 searcher.next_back::<MatchOnly>(self.haystack.as_bytes(),
924 self.needle.as_bytes(),
932 /// The internal state of the two-way substring search algorithm.
933 #[derive(Clone, Debug)]
934 struct TwoWaySearcher {
936 /// critical factorization index
938 /// critical factorization index for reversed needle
939 crit_pos_back: usize,
941 /// `byteset` is an extension (not part of the two way algorithm);
942 /// it's a 64-bit "fingerprint" where each set bit `j` corresponds
943 /// to a (byte & 63) == j present in the needle.
949 /// index into needle before which we have already matched
951 /// index into needle after which we have already matched
956 This is the Two-Way search algorithm, which was introduced in the paper:
957 Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.
959 Here's some background information.
961 A *word* is a string of symbols. The *length* of a word should be a familiar
962 notion, and here we denote it for any word x by |x|.
963 (We also allow for the possibility of the *empty word*, a word of length zero).
965 If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
966 *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
967 For example, both 1 and 2 are periods for the string "aa". As another example,
968 the only period of the string "abcd" is 4.
970 We denote by period(x) the *smallest* period of x (provided that x is non-empty).
971 This is always well-defined since every non-empty word x has at least one period,
972 |x|. We sometimes call this *the period* of x.
974 If u, v and x are words such that x = uv, where uv is the concatenation of u and
975 v, then we say that (u, v) is a *factorization* of x.
977 Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
978 that both of the following hold
980 - either w is a suffix of u or u is a suffix of w
981 - either w is a prefix of v or v is a prefix of w
983 then w is said to be a *repetition* for the factorization (u, v).
985 Just to unpack this, there are four possibilities here. Let w = "abc". Then we
988 - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
989 - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
990 - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
991 - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")
993 Note that the word vu is a repetition for any factorization (u,v) of x = uv,
994 so every factorization has at least one repetition.
996 If x is a string and (u, v) is a factorization for x, then a *local period* for
997 (u, v) is an integer r such that there is some word w such that |w| = r and w is
998 a repetition for (u, v).
1000 We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
1001 call this *the local period* of (u, v). Provided that x = uv is non-empty, this
1002 is well-defined (because each non-empty word has at least one factorization, as
1005 It can be proven that the following is an equivalent definition of a local period
1006 for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
1007 all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
1008 defined. (i.e., i > 0 and i + r < |x|).
1010 Using the above reformulation, it is easy to prove that
1012 1 <= local_period(u, v) <= period(uv)
1014 A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
1015 *critical factorization*.
1017 The algorithm hinges on the following theorem, which is stated without proof:
1019 **Critical Factorization Theorem** Any word x has at least one critical
1020 factorization (u, v) such that |u| < period(x).
1022 The purpose of maximal_suffix is to find such a critical factorization.
1024 If the period is short, compute another factorization x = u' v' to use
1025 for reverse search, chosen instead so that |v'| < period(x).
1028 impl TwoWaySearcher {
1029 fn new(needle: &[u8], end: usize) -> TwoWaySearcher {
1030 let (crit_pos_false, period_false) = TwoWaySearcher::maximal_suffix(needle, false);
1031 let (crit_pos_true, period_true) = TwoWaySearcher::maximal_suffix(needle, true);
1033 let (crit_pos, period) =
1034 if crit_pos_false > crit_pos_true {
1035 (crit_pos_false, period_false)
1037 (crit_pos_true, period_true)
1040 // A particularly readable explanation of what's going on here can be found
1041 // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
1042 // see the code for "Algorithm CP" on p. 323.
1044 // What's going on is we have some critical factorization (u, v) of the
1045 // needle, and we want to determine whether u is a suffix of
1046 // &v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
1047 // "Algorithm CP2", which is optimized for when the period of the needle
1049 if &needle[..crit_pos] == &needle[period.. period + crit_pos] {
1050 // short period case -- the period is exact
1051 // compute a separate critical factorization for the reversed needle
1052 // x = u' v' where |v'| < period(x).
1054 // This is sped up by the period being known already.
1055 // Note that a case like x = "acba" may be factored exactly forwards
1056 // (crit_pos = 1, period = 3) while being factored with approximate
1057 // period in reverse (crit_pos = 2, period = 2). We use the given
1058 // reverse factorization but keep the exact period.
1059 let crit_pos_back = needle.len() - cmp::max(
1060 TwoWaySearcher::reverse_maximal_suffix(needle, period, false),
1061 TwoWaySearcher::reverse_maximal_suffix(needle, period, true));
1067 byteset: Self::byteset_create(&needle[..period]),
1072 memory_back: needle.len(),
1075 // long period case -- we have an approximation to the actual period,
1076 // and don't use memorization.
1078 // Approximate the period by lower bound max(|u|, |v|) + 1.
1079 // The critical factorization is efficient to use for both forward and
1084 crit_pos_back: crit_pos,
1085 period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
1086 byteset: Self::byteset_create(needle),
1090 memory: usize::MAX, // Dummy value to signify that the period is long
1091 memory_back: usize::MAX,
1097 fn byteset_create(bytes: &[u8]) -> u64 {
1098 bytes.iter().fold(0, |a, &b| (1 << (b & 0x3f)) | a)
1102 fn byteset_contains(&self, byte: u8) -> bool {
1103 (self.byteset >> ((byte & 0x3f) as usize)) & 1 != 0
1106 // One of the main ideas of Two-Way is that we factorize the needle into
1107 // two halves, (u, v), and begin trying to find v in the haystack by scanning
1108 // left to right. If v matches, we try to match u by scanning right to left.
1109 // How far we can jump when we encounter a mismatch is all based on the fact
1110 // that (u, v) is a critical factorization for the needle.
1112 fn next<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool)
1114 where S: TwoWayStrategy
1116 // `next()` uses `self.position` as its cursor
1117 let old_pos = self.position;
1118 let needle_last = needle.len() - 1;
1120 // Check that we have room to search in
1121 // position + needle_last can not overflow if we assume slices
1122 // are bounded by isize's range.
1123 let tail_byte = match haystack.get(self.position + needle_last) {
1126 self.position = haystack.len();
1127 return S::rejecting(old_pos, self.position);
1131 if S::use_early_reject() && old_pos != self.position {
1132 return S::rejecting(old_pos, self.position);
1135 // Quickly skip by large portions unrelated to our substring
1136 if !self.byteset_contains(tail_byte) {
1137 self.position += needle.len();
1144 // See if the right part of the needle matches
1145 let start = if long_period { self.crit_pos }
1146 else { cmp::max(self.crit_pos, self.memory) };
1147 for i in start..needle.len() {
1148 if needle[i] != haystack[self.position + i] {
1149 self.position += i - self.crit_pos + 1;
1157 // See if the left part of the needle matches
1158 let start = if long_period { 0 } else { self.memory };
1159 for i in (start..self.crit_pos).rev() {
1160 if needle[i] != haystack[self.position + i] {
1161 self.position += self.period;
1163 self.memory = needle.len() - self.period;
1169 // We have found a match!
1170 let match_pos = self.position;
1172 // Note: add self.period instead of needle.len() to have overlapping matches
1173 self.position += needle.len();
1175 self.memory = 0; // set to needle.len() - self.period for overlapping matches
1178 return S::matching(match_pos, match_pos + needle.len());
1182 // Follows the ideas in `next()`.
1184 // The definitions are symmetrical, with period(x) = period(reverse(x))
1185 // and local_period(u, v) = local_period(reverse(v), reverse(u)), so if (u, v)
1186 // is a critical factorization, so is (reverse(v), reverse(u)).
1188 // For the reverse case we have computed a critical factorization x = u' v'
1189 // (field `crit_pos_back`). We need |u| < period(x) for the forward case and
1190 // thus |v'| < period(x) for the reverse.
1192 // To search in reverse through the haystack, we search forward through
1193 // a reversed haystack with a reversed needle, matching first u' and then v'.
1195 fn next_back<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool)
1197 where S: TwoWayStrategy
1199 // `next_back()` uses `self.end` as its cursor -- so that `next()` and `next_back()`
1201 let old_end = self.end;
1203 // Check that we have room to search in
1204 // end - needle.len() will wrap around when there is no more room,
1205 // but due to slice length limits it can never wrap all the way back
1206 // into the length of haystack.
1207 let front_byte = match haystack.get(self.end.wrapping_sub(needle.len())) {
1211 return S::rejecting(0, old_end);
1215 if S::use_early_reject() && old_end != self.end {
1216 return S::rejecting(self.end, old_end);
1219 // Quickly skip by large portions unrelated to our substring
1220 if !self.byteset_contains(front_byte) {
1221 self.end -= needle.len();
1223 self.memory_back = needle.len();
1228 // See if the left part of the needle matches
1229 let crit = if long_period { self.crit_pos_back }
1230 else { cmp::min(self.crit_pos_back, self.memory_back) };
1231 for i in (0..crit).rev() {
1232 if needle[i] != haystack[self.end - needle.len() + i] {
1233 self.end -= self.crit_pos_back - i;
1235 self.memory_back = needle.len();
1241 // See if the right part of the needle matches
1242 let needle_end = if long_period { needle.len() }
1243 else { self.memory_back };
1244 for i in self.crit_pos_back..needle_end {
1245 if needle[i] != haystack[self.end - needle.len() + i] {
1246 self.end -= self.period;
1248 self.memory_back = self.period;
1254 // We have found a match!
1255 let match_pos = self.end - needle.len();
1256 // Note: sub self.period instead of needle.len() to have overlapping matches
1257 self.end -= needle.len();
1259 self.memory_back = needle.len();
1262 return S::matching(match_pos, match_pos + needle.len());
1266 // Compute the maximal suffix of `arr`.
1268 // The maximal suffix is a possible critical factorization (u, v) of `arr`.
1270 // Returns (`i`, `p`) where `i` is the starting index of v and `p` is the
1273 // `order_greater` determines if lexical order is `<` or `>`. Both
1274 // orders must be computed -- the ordering with the largest `i` gives
1275 // a critical factorization.
1277 // For long period cases, the resulting period is not exact (it is too short).
1279 fn maximal_suffix(arr: &[u8], order_greater: bool) -> (usize, usize) {
1280 let mut left = 0; // Corresponds to i in the paper
1281 let mut right = 1; // Corresponds to j in the paper
1282 let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1283 // to match 0-based indexing.
1284 let mut period = 1; // Corresponds to p in the paper
1286 while let Some(&a) = arr.get(right + offset) {
1287 // `left` will be inbounds when `right` is.
1288 let b = arr[left + offset];
1289 if (a < b && !order_greater) || (a > b && order_greater) {
1290 // Suffix is smaller, period is entire prefix so far.
1291 right += offset + 1;
1293 period = right - left;
1295 // Advance through repetition of the current period.
1296 if offset + 1 == period {
1297 right += offset + 1;
1303 // Suffix is larger, start over from current location.
1313 // Compute the maximal suffix of the reverse of `arr`.
1315 // The maximal suffix is a possible critical factorization (u', v') of `arr`.
1317 // Returns `i` where `i` is the starting index of v', from the back;
1318 // returns immediately when a period of `known_period` is reached.
1320 // `order_greater` determines if lexical order is `<` or `>`. Both
1321 // orders must be computed -- the ordering with the largest `i` gives
1322 // a critical factorization.
1324 // For long period cases, the resulting period is not exact (it is too short).
1325 fn reverse_maximal_suffix(arr: &[u8], known_period: usize,
1326 order_greater: bool) -> usize
1328 let mut left = 0; // Corresponds to i in the paper
1329 let mut right = 1; // Corresponds to j in the paper
1330 let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1331 // to match 0-based indexing.
1332 let mut period = 1; // Corresponds to p in the paper
1335 while right + offset < n {
1336 let a = arr[n - (1 + right + offset)];
1337 let b = arr[n - (1 + left + offset)];
1338 if (a < b && !order_greater) || (a > b && order_greater) {
1339 // Suffix is smaller, period is entire prefix so far.
1340 right += offset + 1;
1342 period = right - left;
1344 // Advance through repetition of the current period.
1345 if offset + 1 == period {
1346 right += offset + 1;
1352 // Suffix is larger, start over from current location.
1358 if period == known_period {
1362 debug_assert!(period <= known_period);
1367 // TwoWayStrategy allows the algorithm to either skip non-matches as quickly
1368 // as possible, or to work in a mode where it emits Rejects relatively quickly.
1369 trait TwoWayStrategy {
1371 fn use_early_reject() -> bool;
1372 fn rejecting(a: usize, b: usize) -> Self::Output;
1373 fn matching(a: usize, b: usize) -> Self::Output;
1376 /// Skip to match intervals as quickly as possible
1379 impl TwoWayStrategy for MatchOnly {
1380 type Output = Option<(usize, usize)>;
1383 fn use_early_reject() -> bool { false }
1385 fn rejecting(_a: usize, _b: usize) -> Self::Output { None }
1387 fn matching(a: usize, b: usize) -> Self::Output { Some((a, b)) }
1390 /// Emit Rejects regularly
1391 enum RejectAndMatch { }
1393 impl TwoWayStrategy for RejectAndMatch {
1394 type Output = SearchStep;
1397 fn use_early_reject() -> bool { true }
1399 fn rejecting(a: usize, b: usize) -> Self::Output { SearchStep::Reject(a, b) }
1401 fn matching(a: usize, b: usize) -> Self::Output { SearchStep::Match(a, b) }