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",
28 /// A `Pattern<'a>` expresses that the implementing type
29 /// can be used as a string pattern for searching in a `&'a str`.
31 /// For example, both `'a'` and `"aa"` are patterns that
32 /// would match at index `1` in the string `"baaaab"`.
34 /// The trait itself acts as a builder for an associated
35 /// `Searcher` type, which does the actual work of finding
36 /// occurrences of the pattern in a string.
37 pub trait Pattern<'a>: Sized {
38 /// Associated searcher for this pattern
39 type Searcher: Searcher<'a>;
41 /// Constructs the associated searcher from
42 /// `self` and the `haystack` to search in.
43 fn into_searcher(self, haystack: &'a str) -> Self::Searcher;
45 /// Checks whether the pattern matches anywhere in the haystack
47 fn is_contained_in(self, haystack: &'a str) -> bool {
48 self.into_searcher(haystack).next_match().is_some()
51 /// Checks whether the pattern matches at the front of the haystack
53 fn is_prefix_of(self, haystack: &'a str) -> bool {
54 match self.into_searcher(haystack).next() {
55 SearchStep::Match(0, _) => true,
60 /// Checks whether the pattern matches at the back of the haystack
62 fn is_suffix_of(self, haystack: &'a str) -> bool
63 where Self::Searcher: ReverseSearcher<'a>
65 match self.into_searcher(haystack).next_back() {
66 SearchStep::Match(_, j) if haystack.len() == j => true,
74 /// Result of calling `Searcher::next()` or `ReverseSearcher::next_back()`.
75 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
77 /// Expresses that a match of the pattern has been found at
80 /// Expresses that `haystack[a..b]` has been rejected as a possible match
83 /// Note that there might be more than one `Reject` between two `Match`es,
84 /// there is no requirement for them to be combined into one.
86 /// Expresses that every byte of the haystack has been visted, ending
91 /// A searcher for a string pattern.
93 /// This trait provides methods for searching for non-overlapping
94 /// matches of a pattern starting from the front (left) of a string.
96 /// It will be implemented by associated `Searcher`
97 /// types of the `Pattern` trait.
99 /// The trait is marked unsafe because the indices returned by the
100 /// `next()` methods are required to lie on valid utf8 boundaries in
101 /// the haystack. This enables consumers of this trait to
102 /// slice the haystack without additional runtime checks.
103 pub unsafe trait Searcher<'a> {
104 /// Getter for the underlaying string to be searched in
106 /// Will always return the same `&str`
107 fn haystack(&self) -> &'a str;
109 /// Performs the next search step starting from the front.
111 /// - Returns `Match(a, b)` if `haystack[a..b]` matches the pattern.
112 /// - Returns `Reject(a, b)` if `haystack[a..b]` can not match the
113 /// pattern, even partially.
114 /// - Returns `Done` if every byte of the haystack has been visited
116 /// The stream of `Match` and `Reject` values up to a `Done`
117 /// will contain index ranges that are adjacent, non-overlapping,
118 /// covering the whole haystack, and laying on utf8 boundaries.
120 /// A `Match` result needs to contain the whole matched pattern,
121 /// however `Reject` results may be split up into arbitrary
122 /// many adjacent fragments. Both ranges may have zero length.
124 /// As an example, the pattern `"aaa"` and the haystack `"cbaaaaab"`
125 /// might produce the stream
126 /// `[Reject(0, 1), Reject(1, 2), Match(2, 5), Reject(5, 8)]`
127 fn next(&mut self) -> SearchStep;
129 /// Find the next `Match` result. See `next()`
131 fn next_match(&mut self) -> Option<(usize, usize)> {
134 SearchStep::Match(a, b) => return Some((a, b)),
135 SearchStep::Done => return None,
141 /// Find the next `Reject` result. See `next()`
143 fn next_reject(&mut self) -> Option<(usize, usize)> {
146 SearchStep::Reject(a, b) => return Some((a, b)),
147 SearchStep::Done => return None,
154 /// A reverse searcher for a string pattern.
156 /// This trait provides methods for searching for non-overlapping
157 /// matches of a pattern starting from the back (right) of a string.
159 /// It will be implemented by associated `Searcher`
160 /// types of the `Pattern` trait if the pattern supports searching
161 /// for it from the back.
163 /// The index ranges returned by this trait are not required
164 /// to exactly match those of the forward search in reverse.
166 /// For the reason why this trait is marked unsafe, see them
167 /// parent trait `Searcher`.
168 pub unsafe trait ReverseSearcher<'a>: Searcher<'a> {
169 /// Performs the next search step starting from the back.
171 /// - Returns `Match(a, b)` if `haystack[a..b]` matches the pattern.
172 /// - Returns `Reject(a, b)` if `haystack[a..b]` can not match the
173 /// pattern, even partially.
174 /// - Returns `Done` if every byte of the haystack has been visited
176 /// The stream of `Match` and `Reject` values up to a `Done`
177 /// will contain index ranges that are adjacent, non-overlapping,
178 /// covering the whole haystack, and laying on utf8 boundaries.
180 /// A `Match` result needs to contain the whole matched pattern,
181 /// however `Reject` results may be split up into arbitrary
182 /// many adjacent fragments. Both ranges may have zero length.
184 /// As an example, the pattern `"aaa"` and the haystack `"cbaaaaab"`
185 /// might produce the stream
186 /// `[Reject(7, 8), Match(4, 7), Reject(1, 4), Reject(0, 1)]`
187 fn next_back(&mut self) -> SearchStep;
189 /// Find the next `Match` result. See `next_back()`
191 fn next_match_back(&mut self) -> Option<(usize, usize)>{
193 match self.next_back() {
194 SearchStep::Match(a, b) => return Some((a, b)),
195 SearchStep::Done => return None,
201 /// Find the next `Reject` result. See `next_back()`
203 fn next_reject_back(&mut self) -> Option<(usize, usize)>{
205 match self.next_back() {
206 SearchStep::Reject(a, b) => return Some((a, b)),
207 SearchStep::Done => return None,
214 /// A marker trait to express that a `ReverseSearcher`
215 /// can be used for a `DoubleEndedIterator` implementation.
217 /// For this, the impl of `Searcher` and `ReverseSearcher` need
218 /// to follow these conditions:
220 /// - All results of `next()` need to be identical
221 /// to the results of `next_back()` in reverse order.
222 /// - `next()` and `next_back()` need to behave as
223 /// the two ends of a range of values, that is they
224 /// can not "walk past each other".
228 /// `char::Searcher` is a `DoubleEndedSearcher` because searching for a
229 /// `char` only requires looking at one at a time, which behaves the same
232 /// `(&str)::Searcher` is not a `DoubleEndedSearcher` because
233 /// the pattern `"aa"` in the haystack `"aaa"` matches as either
234 /// `"[aa]a"` or `"a[aa]"`, depending from which side it is searched.
235 pub trait DoubleEndedSearcher<'a>: ReverseSearcher<'a> {}
237 /////////////////////////////////////////////////////////////////////////////
238 // Impl for a CharEq wrapper
239 /////////////////////////////////////////////////////////////////////////////
243 fn matches(&mut self, char) -> bool;
244 fn only_ascii(&self) -> bool;
247 impl CharEq for char {
249 fn matches(&mut self, c: char) -> bool { *self == c }
252 fn only_ascii(&self) -> bool { (*self as u32) < 128 }
255 impl<F> CharEq for F where F: FnMut(char) -> bool {
257 fn matches(&mut self, c: char) -> bool { (*self)(c) }
260 fn only_ascii(&self) -> bool { false }
263 impl<'a> CharEq for &'a [char] {
265 fn matches(&mut self, c: char) -> bool {
266 self.iter().any(|&m| { let mut m = m; m.matches(c) })
270 fn only_ascii(&self) -> bool {
271 self.iter().all(|m| m.only_ascii())
275 struct CharEqPattern<C: CharEq>(C);
277 #[derive(Clone, Debug)]
278 struct CharEqSearcher<'a, C: CharEq> {
281 char_indices: super::CharIndices<'a>,
286 impl<'a, C: CharEq> Pattern<'a> for CharEqPattern<C> {
287 type Searcher = CharEqSearcher<'a, C>;
290 fn into_searcher(self, haystack: &'a str) -> CharEqSearcher<'a, C> {
292 ascii_only: self.0.only_ascii(),
295 char_indices: haystack.char_indices(),
300 unsafe impl<'a, C: CharEq> Searcher<'a> for CharEqSearcher<'a, C> {
302 fn haystack(&self) -> &'a str {
307 fn next(&mut self) -> SearchStep {
308 let s = &mut self.char_indices;
309 // Compare lengths of the internal byte slice iterator
310 // to find length of current char
311 let pre_len = s.iter.iter.len();
312 if let Some((i, c)) = s.next() {
313 let len = s.iter.iter.len();
314 let char_len = pre_len - len;
315 if self.char_eq.matches(c) {
316 return SearchStep::Match(i, i + char_len);
318 return SearchStep::Reject(i, i + char_len);
325 unsafe impl<'a, C: CharEq> ReverseSearcher<'a> for CharEqSearcher<'a, C> {
327 fn next_back(&mut self) -> SearchStep {
328 let s = &mut self.char_indices;
329 // Compare lengths of the internal byte slice iterator
330 // to find length of current char
331 let pre_len = s.iter.iter.len();
332 if let Some((i, c)) = s.next_back() {
333 let len = s.iter.iter.len();
334 let char_len = pre_len - len;
335 if self.char_eq.matches(c) {
336 return SearchStep::Match(i, i + char_len);
338 return SearchStep::Reject(i, i + char_len);
345 impl<'a, C: CharEq> DoubleEndedSearcher<'a> for CharEqSearcher<'a, C> {}
347 /////////////////////////////////////////////////////////////////////////////
349 macro_rules! pattern_methods {
350 ($t:ty, $pmap:expr, $smap:expr) => {
354 fn into_searcher(self, haystack: &'a str) -> $t {
355 ($smap)(($pmap)(self).into_searcher(haystack))
359 fn is_contained_in(self, haystack: &'a str) -> bool {
360 ($pmap)(self).is_contained_in(haystack)
364 fn is_prefix_of(self, haystack: &'a str) -> bool {
365 ($pmap)(self).is_prefix_of(haystack)
369 fn is_suffix_of(self, haystack: &'a str) -> bool
370 where $t: ReverseSearcher<'a>
372 ($pmap)(self).is_suffix_of(haystack)
377 macro_rules! searcher_methods {
380 fn haystack(&self) -> &'a str {
384 fn next(&mut self) -> SearchStep {
388 fn next_match(&mut self) -> Option<(usize, usize)> {
392 fn next_reject(&mut self) -> Option<(usize, usize)> {
398 fn next_back(&mut self) -> SearchStep {
402 fn next_match_back(&mut self) -> Option<(usize, usize)> {
403 self.0.next_match_back()
406 fn next_reject_back(&mut self) -> Option<(usize, usize)> {
407 self.0.next_reject_back()
412 /////////////////////////////////////////////////////////////////////////////
414 /////////////////////////////////////////////////////////////////////////////
416 /// Associated type for `<char as Pattern<'a>>::Searcher`.
417 #[derive(Clone, Debug)]
418 pub struct CharSearcher<'a>(<CharEqPattern<char> as Pattern<'a>>::Searcher);
420 unsafe impl<'a> Searcher<'a> for CharSearcher<'a> {
421 searcher_methods!(forward);
424 unsafe impl<'a> ReverseSearcher<'a> for CharSearcher<'a> {
425 searcher_methods!(reverse);
428 impl<'a> DoubleEndedSearcher<'a> for CharSearcher<'a> {}
430 /// Searches for chars that are equal to a given char
431 impl<'a> Pattern<'a> for char {
432 pattern_methods!(CharSearcher<'a>, CharEqPattern, CharSearcher);
435 /////////////////////////////////////////////////////////////////////////////
437 /////////////////////////////////////////////////////////////////////////////
439 // Todo: Change / Remove due to ambiguity in meaning.
441 /// Associated type for `<&[char] as Pattern<'a>>::Searcher`.
442 #[derive(Clone, Debug)]
443 pub struct CharSliceSearcher<'a, 'b>(<CharEqPattern<&'b [char]> as Pattern<'a>>::Searcher);
445 unsafe impl<'a, 'b> Searcher<'a> for CharSliceSearcher<'a, 'b> {
446 searcher_methods!(forward);
449 unsafe impl<'a, 'b> ReverseSearcher<'a> for CharSliceSearcher<'a, 'b> {
450 searcher_methods!(reverse);
453 impl<'a, 'b> DoubleEndedSearcher<'a> for CharSliceSearcher<'a, 'b> {}
455 /// Searches for chars that are equal to any of the chars in the array
456 impl<'a, 'b> Pattern<'a> for &'b [char] {
457 pattern_methods!(CharSliceSearcher<'a, 'b>, CharEqPattern, CharSliceSearcher);
460 /////////////////////////////////////////////////////////////////////////////
461 // Impl for F: FnMut(char) -> bool
462 /////////////////////////////////////////////////////////////////////////////
464 /// Associated type for `<F as Pattern<'a>>::Searcher`.
466 pub struct CharPredicateSearcher<'a, F>(<CharEqPattern<F> as Pattern<'a>>::Searcher)
467 where F: FnMut(char) -> bool;
469 impl<'a, F> fmt::Debug for CharPredicateSearcher<'a, F>
470 where F: FnMut(char) -> bool
472 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
473 f.debug_struct("CharPredicateSearcher")
474 .field("haystack", &self.0.haystack)
475 .field("char_indices", &self.0.char_indices)
476 .field("ascii_only", &self.0.ascii_only)
480 unsafe impl<'a, F> Searcher<'a> for CharPredicateSearcher<'a, F>
481 where F: FnMut(char) -> bool
483 searcher_methods!(forward);
486 unsafe impl<'a, F> ReverseSearcher<'a> for CharPredicateSearcher<'a, F>
487 where F: FnMut(char) -> bool
489 searcher_methods!(reverse);
492 impl<'a, F> DoubleEndedSearcher<'a> for CharPredicateSearcher<'a, F>
493 where F: FnMut(char) -> bool {}
495 /// Searches for chars that match the given predicate
496 impl<'a, F> Pattern<'a> for F where F: FnMut(char) -> bool {
497 pattern_methods!(CharPredicateSearcher<'a, F>, CharEqPattern, CharPredicateSearcher);
500 /////////////////////////////////////////////////////////////////////////////
502 /////////////////////////////////////////////////////////////////////////////
504 /// Delegates to the `&str` impl.
505 impl<'a, 'b, 'c> Pattern<'a> for &'c &'b str {
506 pattern_methods!(StrSearcher<'a, 'b>, |&s| s, |s| s);
509 /////////////////////////////////////////////////////////////////////////////
511 /////////////////////////////////////////////////////////////////////////////
513 /// Non-allocating substring search.
515 /// Will handle the pattern `""` as returning empty matches at each character
517 impl<'a, 'b> Pattern<'a> for &'b str {
518 type Searcher = StrSearcher<'a, 'b>;
521 fn into_searcher(self, haystack: &'a str) -> StrSearcher<'a, 'b> {
522 StrSearcher::new(haystack, self)
525 /// Checks whether the pattern matches at the front of the haystack
527 fn is_prefix_of(self, haystack: &'a str) -> bool {
528 haystack.is_char_boundary(self.len()) &&
529 self == &haystack[..self.len()]
532 /// Checks whether the pattern matches at the back of the haystack
534 fn is_suffix_of(self, haystack: &'a str) -> bool {
535 self.len() <= haystack.len() &&
536 haystack.is_char_boundary(haystack.len() - self.len()) &&
537 self == &haystack[haystack.len() - self.len()..]
542 /////////////////////////////////////////////////////////////////////////////
543 // Two Way substring searcher
544 /////////////////////////////////////////////////////////////////////////////
546 #[derive(Clone, Debug)]
547 /// Associated type for `<&str as Pattern<'a>>::Searcher`.
548 pub struct StrSearcher<'a, 'b> {
552 searcher: StrSearcherImpl,
555 #[derive(Clone, Debug)]
556 enum StrSearcherImpl {
558 TwoWay(TwoWaySearcher),
561 #[derive(Clone, Debug)]
569 impl<'a, 'b> StrSearcher<'a, 'b> {
570 fn new(haystack: &'a str, needle: &'b str) -> StrSearcher<'a, 'b> {
571 if needle.is_empty() {
575 searcher: StrSearcherImpl::Empty(EmptyNeedle {
586 searcher: StrSearcherImpl::TwoWay(
587 TwoWaySearcher::new(needle.as_bytes(), haystack.len())
594 unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> {
595 fn haystack(&self) -> &'a str { self.haystack }
598 fn next(&mut self) -> SearchStep {
599 match self.searcher {
600 StrSearcherImpl::Empty(ref mut searcher) => {
601 // empty needle rejects every char and matches every empty string between them
602 let is_match = searcher.is_match_fw;
603 searcher.is_match_fw = !searcher.is_match_fw;
604 let pos = searcher.position;
605 match self.haystack[pos..].chars().next() {
606 _ if is_match => SearchStep::Match(pos, pos),
607 None => SearchStep::Done,
609 searcher.position += ch.len_utf8();
610 SearchStep::Reject(pos, searcher.position)
614 StrSearcherImpl::TwoWay(ref mut searcher) => {
615 // TwoWaySearcher produces valid *Match* indices that split at char boundaries
616 // as long as it does correct matching and that haystack and needle are
618 // *Rejects* from the algorithm can fall on any indices, but we will walk them
619 // manually to the next character boundary, so that they are utf-8 safe.
620 if searcher.position == self.haystack.len() {
621 return SearchStep::Done;
623 let is_long = searcher.memory == usize::MAX;
624 match searcher.next::<RejectAndMatch>(self.haystack.as_bytes(),
625 self.needle.as_bytes(),
628 SearchStep::Reject(a, mut b) => {
629 // skip to next char boundary
630 while !self.haystack.is_char_boundary(b) {
633 searcher.position = cmp::max(b, searcher.position);
634 SearchStep::Reject(a, b)
636 otherwise => otherwise,
643 fn next_match(&mut self) -> Option<(usize, usize)> {
644 match self.searcher {
645 StrSearcherImpl::Empty(..) => {
648 SearchStep::Match(a, b) => return Some((a, b)),
649 SearchStep::Done => return None,
650 SearchStep::Reject(..) => { }
654 StrSearcherImpl::TwoWay(ref mut searcher) => {
655 let is_long = searcher.memory == usize::MAX;
656 // write out `true` and `false` cases to encourage the compiler
657 // to specialize the two cases separately.
659 searcher.next::<MatchOnly>(self.haystack.as_bytes(),
660 self.needle.as_bytes(),
663 searcher.next::<MatchOnly>(self.haystack.as_bytes(),
664 self.needle.as_bytes(),
672 unsafe impl<'a, 'b> ReverseSearcher<'a> for StrSearcher<'a, 'b> {
674 fn next_back(&mut self) -> SearchStep {
675 match self.searcher {
676 StrSearcherImpl::Empty(ref mut searcher) => {
677 let is_match = searcher.is_match_bw;
678 searcher.is_match_bw = !searcher.is_match_bw;
679 let end = searcher.end;
680 match self.haystack[..end].chars().next_back() {
681 _ if is_match => SearchStep::Match(end, end),
682 None => SearchStep::Done,
684 searcher.end -= ch.len_utf8();
685 SearchStep::Reject(searcher.end, end)
689 StrSearcherImpl::TwoWay(ref mut searcher) => {
690 if searcher.end == 0 {
691 return SearchStep::Done;
693 let is_long = searcher.memory == usize::MAX;
694 match searcher.next_back::<RejectAndMatch>(self.haystack.as_bytes(),
695 self.needle.as_bytes(),
698 SearchStep::Reject(mut a, b) => {
699 // skip to next char boundary
700 while !self.haystack.is_char_boundary(a) {
703 searcher.end = cmp::min(a, searcher.end);
704 SearchStep::Reject(a, b)
706 otherwise => otherwise,
713 fn next_match_back(&mut self) -> Option<(usize, usize)> {
714 match self.searcher {
715 StrSearcherImpl::Empty(..) => {
717 match self.next_back() {
718 SearchStep::Match(a, b) => return Some((a, b)),
719 SearchStep::Done => return None,
720 SearchStep::Reject(..) => { }
724 StrSearcherImpl::TwoWay(ref mut searcher) => {
725 let is_long = searcher.memory == usize::MAX;
726 // write out `true` and `false`, like `next_match`
728 searcher.next_back::<MatchOnly>(self.haystack.as_bytes(),
729 self.needle.as_bytes(),
732 searcher.next_back::<MatchOnly>(self.haystack.as_bytes(),
733 self.needle.as_bytes(),
741 /// The internal state of the two-way substring search algorithm.
742 #[derive(Clone, Debug)]
743 struct TwoWaySearcher {
745 /// critical factorization index
747 /// critical factorization index for reversed needle
748 crit_pos_back: usize,
750 /// `byteset` is an extension (not part of the two way algorithm);
751 /// it's a 64-bit "fingerprint" where each set bit `j` corresponds
752 /// to a (byte & 63) == j present in the needle.
758 /// index into needle before which we have already matched
760 /// index into needle after which we have already matched
765 This is the Two-Way search algorithm, which was introduced in the paper:
766 Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.
768 Here's some background information.
770 A *word* is a string of symbols. The *length* of a word should be a familiar
771 notion, and here we denote it for any word x by |x|.
772 (We also allow for the possibility of the *empty word*, a word of length zero).
774 If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
775 *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
776 For example, both 1 and 2 are periods for the string "aa". As another example,
777 the only period of the string "abcd" is 4.
779 We denote by period(x) the *smallest* period of x (provided that x is non-empty).
780 This is always well-defined since every non-empty word x has at least one period,
781 |x|. We sometimes call this *the period* of x.
783 If u, v and x are words such that x = uv, where uv is the concatenation of u and
784 v, then we say that (u, v) is a *factorization* of x.
786 Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
787 that both of the following hold
789 - either w is a suffix of u or u is a suffix of w
790 - either w is a prefix of v or v is a prefix of w
792 then w is said to be a *repetition* for the factorization (u, v).
794 Just to unpack this, there are four possibilities here. Let w = "abc". Then we
797 - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
798 - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
799 - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
800 - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")
802 Note that the word vu is a repetition for any factorization (u,v) of x = uv,
803 so every factorization has at least one repetition.
805 If x is a string and (u, v) is a factorization for x, then a *local period* for
806 (u, v) is an integer r such that there is some word w such that |w| = r and w is
807 a repetition for (u, v).
809 We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
810 call this *the local period* of (u, v). Provided that x = uv is non-empty, this
811 is well-defined (because each non-empty word has at least one factorization, as
814 It can be proven that the following is an equivalent definition of a local period
815 for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
816 all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
817 defined. (i.e. i > 0 and i + r < |x|).
819 Using the above reformulation, it is easy to prove that
821 1 <= local_period(u, v) <= period(uv)
823 A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
824 *critical factorization*.
826 The algorithm hinges on the following theorem, which is stated without proof:
828 **Critical Factorization Theorem** Any word x has at least one critical
829 factorization (u, v) such that |u| < period(x).
831 The purpose of maximal_suffix is to find such a critical factorization.
833 If the period is short, compute another factorization x = u' v' to use
834 for reverse search, chosen instead so that |v'| < period(x).
837 impl TwoWaySearcher {
838 fn new(needle: &[u8], end: usize) -> TwoWaySearcher {
839 let (crit_pos_false, period_false) = TwoWaySearcher::maximal_suffix(needle, false);
840 let (crit_pos_true, period_true) = TwoWaySearcher::maximal_suffix(needle, true);
842 let (crit_pos, period) =
843 if crit_pos_false > crit_pos_true {
844 (crit_pos_false, period_false)
846 (crit_pos_true, period_true)
849 // A particularly readable explanation of what's going on here can be found
850 // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
851 // see the code for "Algorithm CP" on p. 323.
853 // What's going on is we have some critical factorization (u, v) of the
854 // needle, and we want to determine whether u is a suffix of
855 // &v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
856 // "Algorithm CP2", which is optimized for when the period of the needle
858 if &needle[..crit_pos] == &needle[period.. period + crit_pos] {
859 // short period case -- the period is exact
860 // compute a separate critical factorization for the reversed needle
861 // x = u' v' where |v'| < period(x).
863 // This is sped up by the period being known already.
864 // Note that a case like x = "acba" may be factored exactly forwards
865 // (crit_pos = 1, period = 3) while being factored with approximate
866 // period in reverse (crit_pos = 2, period = 2). We use the given
867 // reverse factorization but keep the exact period.
868 let crit_pos_back = needle.len() - cmp::max(
869 TwoWaySearcher::reverse_maximal_suffix(needle, period, false),
870 TwoWaySearcher::reverse_maximal_suffix(needle, period, true));
874 crit_pos_back: crit_pos_back,
876 byteset: Self::byteset_create(&needle[..period]),
881 memory_back: needle.len(),
884 // long period case -- we have an approximation to the actual period,
885 // and don't use memorization.
887 // Approximate the period by lower bound max(|u|, |v|) + 1.
888 // The critical factorization is efficient to use for both forward and
893 crit_pos_back: crit_pos,
894 period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
895 byteset: Self::byteset_create(needle),
899 memory: usize::MAX, // Dummy value to signify that the period is long
900 memory_back: usize::MAX,
906 fn byteset_create(bytes: &[u8]) -> u64 {
907 bytes.iter().fold(0, |a, &b| (1 << (b & 0x3f)) | a)
911 fn byteset_contains(&self, byte: u8) -> bool {
912 (self.byteset >> ((byte & 0x3f) as usize)) & 1 != 0
915 // One of the main ideas of Two-Way is that we factorize the needle into
916 // two halves, (u, v), and begin trying to find v in the haystack by scanning
917 // left to right. If v matches, we try to match u by scanning right to left.
918 // How far we can jump when we encounter a mismatch is all based on the fact
919 // that (u, v) is a critical factorization for the needle.
921 fn next<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool)
923 where S: TwoWayStrategy
925 // `next()` uses `self.position` as its cursor
926 let old_pos = self.position;
927 let needle_last = needle.len() - 1;
929 // Check that we have room to search in
930 // position + needle_last can not overflow if we assume slices
931 // are bounded by isize's range.
932 let tail_byte = match haystack.get(self.position + needle_last) {
935 self.position = haystack.len();
936 return S::rejecting(old_pos, self.position);
940 if S::use_early_reject() && old_pos != self.position {
941 return S::rejecting(old_pos, self.position);
944 // Quickly skip by large portions unrelated to our substring
945 if !self.byteset_contains(tail_byte) {
946 self.position += needle.len();
953 // See if the right part of the needle matches
954 let start = if long_period { self.crit_pos }
955 else { cmp::max(self.crit_pos, self.memory) };
956 for i in start..needle.len() {
957 if needle[i] != haystack[self.position + i] {
958 self.position += i - self.crit_pos + 1;
966 // See if the left part of the needle matches
967 let start = if long_period { 0 } else { self.memory };
968 for i in (start..self.crit_pos).rev() {
969 if needle[i] != haystack[self.position + i] {
970 self.position += self.period;
972 self.memory = needle.len() - self.period;
978 // We have found a match!
979 let match_pos = self.position;
981 // Note: add self.period instead of needle.len() to have overlapping matches
982 self.position += needle.len();
984 self.memory = 0; // set to needle.len() - self.period for overlapping matches
987 return S::matching(match_pos, match_pos + needle.len());
991 // Follows the ideas in `next()`.
993 // The definitions are symmetrical, with period(x) = period(reverse(x))
994 // and local_period(u, v) = local_period(reverse(v), reverse(u)), so if (u, v)
995 // is a critical factorization, so is (reverse(v), reverse(u)).
997 // For the reverse case we have computed a critical factorization x = u' v'
998 // (field `crit_pos_back`). We need |u| < period(x) for the forward case and
999 // thus |v'| < period(x) for the reverse.
1001 // To search in reverse through the haystack, we search forward through
1002 // a reversed haystack with a reversed needle, matching first u' and then v'.
1004 fn next_back<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool)
1006 where S: TwoWayStrategy
1008 // `next_back()` uses `self.end` as its cursor -- so that `next()` and `next_back()`
1010 let old_end = self.end;
1012 // Check that we have room to search in
1013 // end - needle.len() will wrap around when there is no more room,
1014 // but due to slice length limits it can never wrap all the way back
1015 // into the length of haystack.
1016 let front_byte = match haystack.get(self.end.wrapping_sub(needle.len())) {
1020 return S::rejecting(0, old_end);
1024 if S::use_early_reject() && old_end != self.end {
1025 return S::rejecting(self.end, old_end);
1028 // Quickly skip by large portions unrelated to our substring
1029 if !self.byteset_contains(front_byte) {
1030 self.end -= needle.len();
1032 self.memory_back = needle.len();
1037 // See if the left part of the needle matches
1038 let crit = if long_period { self.crit_pos_back }
1039 else { cmp::min(self.crit_pos_back, self.memory_back) };
1040 for i in (0..crit).rev() {
1041 if needle[i] != haystack[self.end - needle.len() + i] {
1042 self.end -= self.crit_pos_back - i;
1044 self.memory_back = needle.len();
1050 // See if the right part of the needle matches
1051 let needle_end = if long_period { needle.len() }
1052 else { self.memory_back };
1053 for i in self.crit_pos_back..needle_end {
1054 if needle[i] != haystack[self.end - needle.len() + i] {
1055 self.end -= self.period;
1057 self.memory_back = self.period;
1063 // We have found a match!
1064 let match_pos = self.end - needle.len();
1065 // Note: sub self.period instead of needle.len() to have overlapping matches
1066 self.end -= needle.len();
1068 self.memory_back = needle.len();
1071 return S::matching(match_pos, match_pos + needle.len());
1075 // Compute the maximal suffix of `arr`.
1077 // The maximal suffix is a possible critical factorization (u, v) of `arr`.
1079 // Returns (`i`, `p`) where `i` is the starting index of v and `p` is the
1082 // `order_greater` determines if lexical order is `<` or `>`. Both
1083 // orders must be computed -- the ordering with the largest `i` gives
1084 // a critical factorization.
1086 // For long period cases, the resulting period is not exact (it is too short).
1088 fn maximal_suffix(arr: &[u8], order_greater: bool) -> (usize, usize) {
1089 let mut left = 0; // Corresponds to i in the paper
1090 let mut right = 1; // Corresponds to j in the paper
1091 let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1092 // to match 0-based indexing.
1093 let mut period = 1; // Corresponds to p in the paper
1095 while let Some(&a) = arr.get(right + offset) {
1096 // `left` will be inbounds when `right` is.
1097 let b = arr[left + offset];
1098 if (a < b && !order_greater) || (a > b && order_greater) {
1099 // Suffix is smaller, period is entire prefix so far.
1100 right += offset + 1;
1102 period = right - left;
1104 // Advance through repetition of the current period.
1105 if offset + 1 == period {
1106 right += offset + 1;
1112 // Suffix is larger, start over from current location.
1122 // Compute the maximal suffix of the reverse of `arr`.
1124 // The maximal suffix is a possible critical factorization (u', v') of `arr`.
1126 // Returns `i` where `i` is the starting index of v', from the back;
1127 // returns immedately when a period of `known_period` is reached.
1129 // `order_greater` determines if lexical order is `<` or `>`. Both
1130 // orders must be computed -- the ordering with the largest `i` gives
1131 // a critical factorization.
1133 // For long period cases, the resulting period is not exact (it is too short).
1134 fn reverse_maximal_suffix(arr: &[u8], known_period: usize,
1135 order_greater: bool) -> usize
1137 let mut left = 0; // Corresponds to i in the paper
1138 let mut right = 1; // Corresponds to j in the paper
1139 let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1140 // to match 0-based indexing.
1141 let mut period = 1; // Corresponds to p in the paper
1144 while right + offset < n {
1145 let a = arr[n - (1 + right + offset)];
1146 let b = arr[n - (1 + left + offset)];
1147 if (a < b && !order_greater) || (a > b && order_greater) {
1148 // Suffix is smaller, period is entire prefix so far.
1149 right += offset + 1;
1151 period = right - left;
1153 // Advance through repetition of the current period.
1154 if offset + 1 == period {
1155 right += offset + 1;
1161 // Suffix is larger, start over from current location.
1167 if period == known_period {
1171 debug_assert!(period <= known_period);
1176 // TwoWayStrategy allows the algorithm to either skip non-matches as quickly
1177 // as possible, or to work in a mode where it emits Rejects relatively quickly.
1178 trait TwoWayStrategy {
1180 fn use_early_reject() -> bool;
1181 fn rejecting(usize, usize) -> Self::Output;
1182 fn matching(usize, usize) -> Self::Output;
1185 /// Skip to match intervals as quickly as possible
1188 impl TwoWayStrategy for MatchOnly {
1189 type Output = Option<(usize, usize)>;
1192 fn use_early_reject() -> bool { false }
1194 fn rejecting(_a: usize, _b: usize) -> Self::Output { None }
1196 fn matching(a: usize, b: usize) -> Self::Output { Some((a, b)) }
1199 /// Emit Rejects regularly
1200 enum RejectAndMatch { }
1202 impl TwoWayStrategy for RejectAndMatch {
1203 type Output = SearchStep;
1206 fn use_early_reject() -> bool { true }
1208 fn rejecting(a: usize, b: usize) -> Self::Output { SearchStep::Reject(a, b) }
1210 fn matching(a: usize, b: usize) -> Self::Output { SearchStep::Match(a, b) }