]> git.lizzy.rs Git - rust.git/blob - library/core/src/str/pattern.rs
Suggest more impl Trait on `-> _`
[rust.git] / library / core / src / str / pattern.rs
1 //! The string Pattern API.
2 //!
3 //! The Pattern API provides a generic mechanism for using different pattern
4 //! types when searching through a string.
5 //!
6 //! For more details, see the traits [`Pattern`], [`Searcher`],
7 //! [`ReverseSearcher`], and [`DoubleEndedSearcher`].
8 //!
9 //! Although this API is unstable, it is exposed via stable APIs on the
10 //! [`str`] type.
11 //!
12 //! # Examples
13 //!
14 //! [`Pattern`] is [implemented][pattern-impls] in the stable API for
15 //! [`&str`][`str`], [`char`], slices of [`char`], and functions and closures
16 //! implementing `FnMut(char) -> bool`.
17 //!
18 //! ```
19 //! let s = "Can you find a needle in a haystack?";
20 //!
21 //! // &str pattern
22 //! assert_eq!(s.find("you"), Some(4));
23 //! // char pattern
24 //! assert_eq!(s.find('n'), Some(2));
25 //! // array of chars pattern
26 //! assert_eq!(s.find(&['a', 'e', 'i', 'o', 'u']), Some(1));
27 //! // slice of chars pattern
28 //! assert_eq!(s.find(&['a', 'e', 'i', 'o', 'u'][..]), Some(1));
29 //! // closure pattern
30 //! assert_eq!(s.find(|c: char| c.is_ascii_punctuation()), Some(35));
31 //! ```
32 //!
33 //! [pattern-impls]: Pattern#implementors
34
35 #![unstable(
36     feature = "pattern",
37     reason = "API not fully fleshed out and ready to be stabilized",
38     issue = "27721"
39 )]
40
41 use crate::cmp;
42 use crate::cmp::Ordering;
43 use crate::fmt;
44 use crate::slice::memchr;
45
46 // Pattern
47
48 /// A string pattern.
49 ///
50 /// A `Pattern<'a>` expresses that the implementing type
51 /// can be used as a string pattern for searching in a [`&'a str`][str].
52 ///
53 /// For example, both `'a'` and `"aa"` are patterns that
54 /// would match at index `1` in the string `"baaaab"`.
55 ///
56 /// The trait itself acts as a builder for an associated
57 /// [`Searcher`] type, which does the actual work of finding
58 /// occurrences of the pattern in a string.
59 ///
60 /// Depending on the type of the pattern, the behaviour of methods like
61 /// [`str::find`] and [`str::contains`] can change. The table below describes
62 /// some of those behaviours.
63 ///
64 /// | Pattern type             | Match condition                           |
65 /// |--------------------------|-------------------------------------------|
66 /// | `&str`                   | is substring                              |
67 /// | `char`                   | is contained in string                    |
68 /// | `&[char]`                | any char in slice is contained in string  |
69 /// | `F: FnMut(char) -> bool` | `F` returns `true` for a char in string   |
70 /// | `&&str`                  | is substring                              |
71 /// | `&String`                | is substring                              |
72 ///
73 /// # Examples
74 ///
75 /// ```
76 /// // &str
77 /// assert_eq!("abaaa".find("ba"), Some(1));
78 /// assert_eq!("abaaa".find("bac"), None);
79 ///
80 /// // char
81 /// assert_eq!("abaaa".find('a'), Some(0));
82 /// assert_eq!("abaaa".find('b'), Some(1));
83 /// assert_eq!("abaaa".find('c'), None);
84 ///
85 /// // &[char; N]
86 /// assert_eq!("ab".find(&['b', 'a']), Some(0));
87 /// assert_eq!("abaaa".find(&['a', 'z']), Some(0));
88 /// assert_eq!("abaaa".find(&['c', 'd']), None);
89 ///
90 /// // &[char]
91 /// assert_eq!("ab".find(&['b', 'a'][..]), Some(0));
92 /// assert_eq!("abaaa".find(&['a', 'z'][..]), Some(0));
93 /// assert_eq!("abaaa".find(&['c', 'd'][..]), None);
94 ///
95 /// // FnMut(char) -> bool
96 /// assert_eq!("abcdef_z".find(|ch| ch > 'd' && ch < 'y'), Some(4));
97 /// assert_eq!("abcddd_z".find(|ch| ch > 'd' && ch < 'y'), None);
98 /// ```
99 pub trait Pattern<'a>: Sized {
100     /// Associated searcher for this pattern
101     type Searcher: Searcher<'a>;
102
103     /// Constructs the associated searcher from
104     /// `self` and the `haystack` to search in.
105     fn into_searcher(self, haystack: &'a str) -> Self::Searcher;
106
107     /// Checks whether the pattern matches anywhere in the haystack
108     #[inline]
109     fn is_contained_in(self, haystack: &'a str) -> bool {
110         self.into_searcher(haystack).next_match().is_some()
111     }
112
113     /// Checks whether the pattern matches at the front of the haystack
114     #[inline]
115     fn is_prefix_of(self, haystack: &'a str) -> bool {
116         matches!(self.into_searcher(haystack).next(), SearchStep::Match(0, _))
117     }
118
119     /// Checks whether the pattern matches at the back of the haystack
120     #[inline]
121     fn is_suffix_of(self, haystack: &'a str) -> bool
122     where
123         Self::Searcher: ReverseSearcher<'a>,
124     {
125         matches!(self.into_searcher(haystack).next_back(), SearchStep::Match(_, j) if haystack.len() == j)
126     }
127
128     /// Removes the pattern from the front of haystack, if it matches.
129     #[inline]
130     fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> {
131         if let SearchStep::Match(start, len) = self.into_searcher(haystack).next() {
132             debug_assert_eq!(
133                 start, 0,
134                 "The first search step from Searcher \
135                  must include the first character"
136             );
137             // SAFETY: `Searcher` is known to return valid indices.
138             unsafe { Some(haystack.get_unchecked(len..)) }
139         } else {
140             None
141         }
142     }
143
144     /// Removes the pattern from the back of haystack, if it matches.
145     #[inline]
146     fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str>
147     where
148         Self::Searcher: ReverseSearcher<'a>,
149     {
150         if let SearchStep::Match(start, end) = self.into_searcher(haystack).next_back() {
151             debug_assert_eq!(
152                 end,
153                 haystack.len(),
154                 "The first search step from ReverseSearcher \
155                  must include the last character"
156             );
157             // SAFETY: `Searcher` is known to return valid indices.
158             unsafe { Some(haystack.get_unchecked(..start)) }
159         } else {
160             None
161         }
162     }
163 }
164
165 // Searcher
166
167 /// Result of calling [`Searcher::next()`] or [`ReverseSearcher::next_back()`].
168 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
169 pub enum SearchStep {
170     /// Expresses that a match of the pattern has been found at
171     /// `haystack[a..b]`.
172     Match(usize, usize),
173     /// Expresses that `haystack[a..b]` has been rejected as a possible match
174     /// of the pattern.
175     ///
176     /// Note that there might be more than one `Reject` between two `Match`es,
177     /// there is no requirement for them to be combined into one.
178     Reject(usize, usize),
179     /// Expresses that every byte of the haystack has been visited, ending
180     /// the iteration.
181     Done,
182 }
183
184 /// A searcher for a string pattern.
185 ///
186 /// This trait provides methods for searching for non-overlapping
187 /// matches of a pattern starting from the front (left) of a string.
188 ///
189 /// It will be implemented by associated `Searcher`
190 /// types of the [`Pattern`] trait.
191 ///
192 /// The trait is marked unsafe because the indices returned by the
193 /// [`next()`][Searcher::next] methods are required to lie on valid utf8
194 /// boundaries in the haystack. This enables consumers of this trait to
195 /// slice the haystack without additional runtime checks.
196 pub unsafe trait Searcher<'a> {
197     /// Getter for the underlying string to be searched in
198     ///
199     /// Will always return the same [`&str`][str].
200     fn haystack(&self) -> &'a str;
201
202     /// Performs the next search step starting from the front.
203     ///
204     /// - Returns [`Match(a, b)`][SearchStep::Match] if `haystack[a..b]` matches
205     ///   the pattern.
206     /// - Returns [`Reject(a, b)`][SearchStep::Reject] if `haystack[a..b]` can
207     ///   not match the pattern, even partially.
208     /// - Returns [`Done`][SearchStep::Done] if every byte of the haystack has
209     ///   been visited.
210     ///
211     /// The stream of [`Match`][SearchStep::Match] and
212     /// [`Reject`][SearchStep::Reject] values up to a [`Done`][SearchStep::Done]
213     /// will contain index ranges that are adjacent, non-overlapping,
214     /// covering the whole haystack, and laying on utf8 boundaries.
215     ///
216     /// A [`Match`][SearchStep::Match] result needs to contain the whole matched
217     /// pattern, however [`Reject`][SearchStep::Reject] results may be split up
218     /// into arbitrary many adjacent fragments. Both ranges may have zero length.
219     ///
220     /// As an example, the pattern `"aaa"` and the haystack `"cbaaaaab"`
221     /// might produce the stream
222     /// `[Reject(0, 1), Reject(1, 2), Match(2, 5), Reject(5, 8)]`
223     fn next(&mut self) -> SearchStep;
224
225     /// Finds the next [`Match`][SearchStep::Match] result. See [`next()`][Searcher::next].
226     ///
227     /// Unlike [`next()`][Searcher::next], there is no guarantee that the returned ranges
228     /// of this and [`next_reject`][Searcher::next_reject] will overlap. This will return
229     /// `(start_match, end_match)`, where start_match is the index of where
230     /// the match begins, and end_match is the index after the end of the match.
231     #[inline]
232     fn next_match(&mut self) -> Option<(usize, usize)> {
233         loop {
234             match self.next() {
235                 SearchStep::Match(a, b) => return Some((a, b)),
236                 SearchStep::Done => return None,
237                 _ => continue,
238             }
239         }
240     }
241
242     /// Finds the next [`Reject`][SearchStep::Reject] result. See [`next()`][Searcher::next]
243     /// and [`next_match()`][Searcher::next_match].
244     ///
245     /// Unlike [`next()`][Searcher::next], there is no guarantee that the returned ranges
246     /// of this and [`next_match`][Searcher::next_match] will overlap.
247     #[inline]
248     fn next_reject(&mut self) -> Option<(usize, usize)> {
249         loop {
250             match self.next() {
251                 SearchStep::Reject(a, b) => return Some((a, b)),
252                 SearchStep::Done => return None,
253                 _ => continue,
254             }
255         }
256     }
257 }
258
259 /// A reverse searcher for a string pattern.
260 ///
261 /// This trait provides methods for searching for non-overlapping
262 /// matches of a pattern starting from the back (right) of a string.
263 ///
264 /// It will be implemented by associated [`Searcher`]
265 /// types of the [`Pattern`] trait if the pattern supports searching
266 /// for it from the back.
267 ///
268 /// The index ranges returned by this trait are not required
269 /// to exactly match those of the forward search in reverse.
270 ///
271 /// For the reason why this trait is marked unsafe, see the
272 /// parent trait [`Searcher`].
273 pub unsafe trait ReverseSearcher<'a>: Searcher<'a> {
274     /// Performs the next search step starting from the back.
275     ///
276     /// - Returns [`Match(a, b)`][SearchStep::Match] if `haystack[a..b]`
277     ///   matches the pattern.
278     /// - Returns [`Reject(a, b)`][SearchStep::Reject] if `haystack[a..b]`
279     ///   can not match the pattern, even partially.
280     /// - Returns [`Done`][SearchStep::Done] if every byte of the haystack
281     ///   has been visited
282     ///
283     /// The stream of [`Match`][SearchStep::Match] and
284     /// [`Reject`][SearchStep::Reject] values up to a [`Done`][SearchStep::Done]
285     /// will contain index ranges that are adjacent, non-overlapping,
286     /// covering the whole haystack, and laying on utf8 boundaries.
287     ///
288     /// A [`Match`][SearchStep::Match] result needs to contain the whole matched
289     /// pattern, however [`Reject`][SearchStep::Reject] results may be split up
290     /// into arbitrary many adjacent fragments. Both ranges may have zero length.
291     ///
292     /// As an example, the pattern `"aaa"` and the haystack `"cbaaaaab"`
293     /// might produce the stream
294     /// `[Reject(7, 8), Match(4, 7), Reject(1, 4), Reject(0, 1)]`.
295     fn next_back(&mut self) -> SearchStep;
296
297     /// Finds the next [`Match`][SearchStep::Match] result.
298     /// See [`next_back()`][ReverseSearcher::next_back].
299     #[inline]
300     fn next_match_back(&mut self) -> Option<(usize, usize)> {
301         loop {
302             match self.next_back() {
303                 SearchStep::Match(a, b) => return Some((a, b)),
304                 SearchStep::Done => return None,
305                 _ => continue,
306             }
307         }
308     }
309
310     /// Finds the next [`Reject`][SearchStep::Reject] result.
311     /// See [`next_back()`][ReverseSearcher::next_back].
312     #[inline]
313     fn next_reject_back(&mut self) -> Option<(usize, usize)> {
314         loop {
315             match self.next_back() {
316                 SearchStep::Reject(a, b) => return Some((a, b)),
317                 SearchStep::Done => return None,
318                 _ => continue,
319             }
320         }
321     }
322 }
323
324 /// A marker trait to express that a [`ReverseSearcher`]
325 /// can be used for a [`DoubleEndedIterator`] implementation.
326 ///
327 /// For this, the impl of [`Searcher`] and [`ReverseSearcher`] need
328 /// to follow these conditions:
329 ///
330 /// - All results of `next()` need to be identical
331 ///   to the results of `next_back()` in reverse order.
332 /// - `next()` and `next_back()` need to behave as
333 ///   the two ends of a range of values, that is they
334 ///   can not "walk past each other".
335 ///
336 /// # Examples
337 ///
338 /// `char::Searcher` is a `DoubleEndedSearcher` because searching for a
339 /// [`char`] only requires looking at one at a time, which behaves the same
340 /// from both ends.
341 ///
342 /// `(&str)::Searcher` is not a `DoubleEndedSearcher` because
343 /// the pattern `"aa"` in the haystack `"aaa"` matches as either
344 /// `"[aa]a"` or `"a[aa]"`, depending from which side it is searched.
345 pub trait DoubleEndedSearcher<'a>: ReverseSearcher<'a> {}
346
347 /////////////////////////////////////////////////////////////////////////////
348 // Impl for char
349 /////////////////////////////////////////////////////////////////////////////
350
351 /// Associated type for `<char as Pattern<'a>>::Searcher`.
352 #[derive(Clone, Debug)]
353 pub struct CharSearcher<'a> {
354     haystack: &'a str,
355     // safety invariant: `finger`/`finger_back` must be a valid utf8 byte index of `haystack`
356     // This invariant can be broken *within* next_match and next_match_back, however
357     // they must exit with fingers on valid code point boundaries.
358     /// `finger` is the current byte index of the forward search.
359     /// Imagine that it exists before the byte at its index, i.e.
360     /// `haystack[finger]` is the first byte of the slice we must inspect during
361     /// forward searching
362     finger: usize,
363     /// `finger_back` is the current byte index of the reverse search.
364     /// Imagine that it exists after the byte at its index, i.e.
365     /// haystack[finger_back - 1] is the last byte of the slice we must inspect during
366     /// forward searching (and thus the first byte to be inspected when calling next_back()).
367     finger_back: usize,
368     /// The character being searched for
369     needle: char,
370
371     // safety invariant: `utf8_size` must be less than 5
372     /// The number of bytes `needle` takes up when encoded in utf8.
373     utf8_size: usize,
374     /// A utf8 encoded copy of the `needle`
375     utf8_encoded: [u8; 4],
376 }
377
378 unsafe impl<'a> Searcher<'a> for CharSearcher<'a> {
379     #[inline]
380     fn haystack(&self) -> &'a str {
381         self.haystack
382     }
383     #[inline]
384     fn next(&mut self) -> SearchStep {
385         let old_finger = self.finger;
386         // SAFETY: 1-4 guarantee safety of `get_unchecked`
387         // 1. `self.finger` and `self.finger_back` are kept on unicode boundaries
388         //    (this is invariant)
389         // 2. `self.finger >= 0` since it starts at 0 and only increases
390         // 3. `self.finger < self.finger_back` because otherwise the char `iter`
391         //    would return `SearchStep::Done`
392         // 4. `self.finger` comes before the end of the haystack because `self.finger_back`
393         //    starts at the end and only decreases
394         let slice = unsafe { self.haystack.get_unchecked(old_finger..self.finger_back) };
395         let mut iter = slice.chars();
396         let old_len = iter.iter.len();
397         if let Some(ch) = iter.next() {
398             // add byte offset of current character
399             // without re-encoding as utf-8
400             self.finger += old_len - iter.iter.len();
401             if ch == self.needle {
402                 SearchStep::Match(old_finger, self.finger)
403             } else {
404                 SearchStep::Reject(old_finger, self.finger)
405             }
406         } else {
407             SearchStep::Done
408         }
409     }
410     #[inline]
411     fn next_match(&mut self) -> Option<(usize, usize)> {
412         loop {
413             // get the haystack after the last character found
414             let bytes = self.haystack.as_bytes().get(self.finger..self.finger_back)?;
415             // the last byte of the utf8 encoded needle
416             // SAFETY: we have an invariant that `utf8_size < 5`
417             let last_byte = unsafe { *self.utf8_encoded.get_unchecked(self.utf8_size - 1) };
418             if let Some(index) = memchr::memchr(last_byte, bytes) {
419                 // The new finger is the index of the byte we found,
420                 // plus one, since we memchr'd for the last byte of the character.
421                 //
422                 // Note that this doesn't always give us a finger on a UTF8 boundary.
423                 // If we *didn't* find our character
424                 // we may have indexed to the non-last byte of a 3-byte or 4-byte character.
425                 // We can't just skip to the next valid starting byte because a character like
426                 // ꁁ (U+A041 YI SYLLABLE PA), utf-8 `EA 81 81` will have us always find
427                 // the second byte when searching for the third.
428                 //
429                 // However, this is totally okay. While we have the invariant that
430                 // self.finger is on a UTF8 boundary, this invariant is not relied upon
431                 // within this method (it is relied upon in CharSearcher::next()).
432                 //
433                 // We only exit this method when we reach the end of the string, or if we
434                 // find something. When we find something the `finger` will be set
435                 // to a UTF8 boundary.
436                 self.finger += index + 1;
437                 if self.finger >= self.utf8_size {
438                     let found_char = self.finger - self.utf8_size;
439                     if let Some(slice) = self.haystack.as_bytes().get(found_char..self.finger) {
440                         if slice == &self.utf8_encoded[0..self.utf8_size] {
441                             return Some((found_char, self.finger));
442                         }
443                     }
444                 }
445             } else {
446                 // found nothing, exit
447                 self.finger = self.finger_back;
448                 return None;
449             }
450         }
451     }
452
453     // let next_reject use the default implementation from the Searcher trait
454 }
455
456 unsafe impl<'a> ReverseSearcher<'a> for CharSearcher<'a> {
457     #[inline]
458     fn next_back(&mut self) -> SearchStep {
459         let old_finger = self.finger_back;
460         // SAFETY: see the comment for next() above
461         let slice = unsafe { self.haystack.get_unchecked(self.finger..old_finger) };
462         let mut iter = slice.chars();
463         let old_len = iter.iter.len();
464         if let Some(ch) = iter.next_back() {
465             // subtract byte offset of current character
466             // without re-encoding as utf-8
467             self.finger_back -= old_len - iter.iter.len();
468             if ch == self.needle {
469                 SearchStep::Match(self.finger_back, old_finger)
470             } else {
471                 SearchStep::Reject(self.finger_back, old_finger)
472             }
473         } else {
474             SearchStep::Done
475         }
476     }
477     #[inline]
478     fn next_match_back(&mut self) -> Option<(usize, usize)> {
479         let haystack = self.haystack.as_bytes();
480         loop {
481             // get the haystack up to but not including the last character searched
482             let bytes = haystack.get(self.finger..self.finger_back)?;
483             // the last byte of the utf8 encoded needle
484             // SAFETY: we have an invariant that `utf8_size < 5`
485             let last_byte = unsafe { *self.utf8_encoded.get_unchecked(self.utf8_size - 1) };
486             if let Some(index) = memchr::memrchr(last_byte, bytes) {
487                 // we searched a slice that was offset by self.finger,
488                 // add self.finger to recoup the original index
489                 let index = self.finger + index;
490                 // memrchr will return the index of the byte we wish to
491                 // find. In case of an ASCII character, this is indeed
492                 // were we wish our new finger to be ("after" the found
493                 // char in the paradigm of reverse iteration). For
494                 // multibyte chars we need to skip down by the number of more
495                 // bytes they have than ASCII
496                 let shift = self.utf8_size - 1;
497                 if index >= shift {
498                     let found_char = index - shift;
499                     if let Some(slice) = haystack.get(found_char..(found_char + self.utf8_size)) {
500                         if slice == &self.utf8_encoded[0..self.utf8_size] {
501                             // move finger to before the character found (i.e., at its start index)
502                             self.finger_back = found_char;
503                             return Some((self.finger_back, self.finger_back + self.utf8_size));
504                         }
505                     }
506                 }
507                 // We can't use finger_back = index - size + 1 here. If we found the last char
508                 // of a different-sized character (or the middle byte of a different character)
509                 // we need to bump the finger_back down to `index`. This similarly makes
510                 // `finger_back` have the potential to no longer be on a boundary,
511                 // but this is OK since we only exit this function on a boundary
512                 // or when the haystack has been searched completely.
513                 //
514                 // Unlike next_match this does not
515                 // have the problem of repeated bytes in utf-8 because
516                 // we're searching for the last byte, and we can only have
517                 // found the last byte when searching in reverse.
518                 self.finger_back = index;
519             } else {
520                 self.finger_back = self.finger;
521                 // found nothing, exit
522                 return None;
523             }
524         }
525     }
526
527     // let next_reject_back use the default implementation from the Searcher trait
528 }
529
530 impl<'a> DoubleEndedSearcher<'a> for CharSearcher<'a> {}
531
532 /// Searches for chars that are equal to a given [`char`].
533 ///
534 /// # Examples
535 ///
536 /// ```
537 /// assert_eq!("Hello world".find('o'), Some(4));
538 /// ```
539 impl<'a> Pattern<'a> for char {
540     type Searcher = CharSearcher<'a>;
541
542     #[inline]
543     fn into_searcher(self, haystack: &'a str) -> Self::Searcher {
544         let mut utf8_encoded = [0; 4];
545         let utf8_size = self.encode_utf8(&mut utf8_encoded).len();
546         CharSearcher {
547             haystack,
548             finger: 0,
549             finger_back: haystack.len(),
550             needle: self,
551             utf8_size,
552             utf8_encoded,
553         }
554     }
555
556     #[inline]
557     fn is_contained_in(self, haystack: &'a str) -> bool {
558         if (self as u32) < 128 {
559             haystack.as_bytes().contains(&(self as u8))
560         } else {
561             let mut buffer = [0u8; 4];
562             self.encode_utf8(&mut buffer).is_contained_in(haystack)
563         }
564     }
565
566     #[inline]
567     fn is_prefix_of(self, haystack: &'a str) -> bool {
568         self.encode_utf8(&mut [0u8; 4]).is_prefix_of(haystack)
569     }
570
571     #[inline]
572     fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> {
573         self.encode_utf8(&mut [0u8; 4]).strip_prefix_of(haystack)
574     }
575
576     #[inline]
577     fn is_suffix_of(self, haystack: &'a str) -> bool
578     where
579         Self::Searcher: ReverseSearcher<'a>,
580     {
581         self.encode_utf8(&mut [0u8; 4]).is_suffix_of(haystack)
582     }
583
584     #[inline]
585     fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str>
586     where
587         Self::Searcher: ReverseSearcher<'a>,
588     {
589         self.encode_utf8(&mut [0u8; 4]).strip_suffix_of(haystack)
590     }
591 }
592
593 /////////////////////////////////////////////////////////////////////////////
594 // Impl for a MultiCharEq wrapper
595 /////////////////////////////////////////////////////////////////////////////
596
597 #[doc(hidden)]
598 trait MultiCharEq {
599     fn matches(&mut self, c: char) -> bool;
600 }
601
602 impl<F> MultiCharEq for F
603 where
604     F: FnMut(char) -> bool,
605 {
606     #[inline]
607     fn matches(&mut self, c: char) -> bool {
608         (*self)(c)
609     }
610 }
611
612 impl<const N: usize> MultiCharEq for [char; N] {
613     #[inline]
614     fn matches(&mut self, c: char) -> bool {
615         self.iter().any(|&m| m == c)
616     }
617 }
618
619 impl<const N: usize> MultiCharEq for &[char; N] {
620     #[inline]
621     fn matches(&mut self, c: char) -> bool {
622         self.iter().any(|&m| m == c)
623     }
624 }
625
626 impl MultiCharEq for &[char] {
627     #[inline]
628     fn matches(&mut self, c: char) -> bool {
629         self.iter().any(|&m| m == c)
630     }
631 }
632
633 struct MultiCharEqPattern<C: MultiCharEq>(C);
634
635 #[derive(Clone, Debug)]
636 struct MultiCharEqSearcher<'a, C: MultiCharEq> {
637     char_eq: C,
638     haystack: &'a str,
639     char_indices: super::CharIndices<'a>,
640 }
641
642 impl<'a, C: MultiCharEq> Pattern<'a> for MultiCharEqPattern<C> {
643     type Searcher = MultiCharEqSearcher<'a, C>;
644
645     #[inline]
646     fn into_searcher(self, haystack: &'a str) -> MultiCharEqSearcher<'a, C> {
647         MultiCharEqSearcher { haystack, char_eq: self.0, char_indices: haystack.char_indices() }
648     }
649 }
650
651 unsafe impl<'a, C: MultiCharEq> Searcher<'a> for MultiCharEqSearcher<'a, C> {
652     #[inline]
653     fn haystack(&self) -> &'a str {
654         self.haystack
655     }
656
657     #[inline]
658     fn next(&mut self) -> SearchStep {
659         let s = &mut self.char_indices;
660         // Compare lengths of the internal byte slice iterator
661         // to find length of current char
662         let pre_len = s.iter.iter.len();
663         if let Some((i, c)) = s.next() {
664             let len = s.iter.iter.len();
665             let char_len = pre_len - len;
666             if self.char_eq.matches(c) {
667                 return SearchStep::Match(i, i + char_len);
668             } else {
669                 return SearchStep::Reject(i, i + char_len);
670             }
671         }
672         SearchStep::Done
673     }
674 }
675
676 unsafe impl<'a, C: MultiCharEq> ReverseSearcher<'a> for MultiCharEqSearcher<'a, C> {
677     #[inline]
678     fn next_back(&mut self) -> SearchStep {
679         let s = &mut self.char_indices;
680         // Compare lengths of the internal byte slice iterator
681         // to find length of current char
682         let pre_len = s.iter.iter.len();
683         if let Some((i, c)) = s.next_back() {
684             let len = s.iter.iter.len();
685             let char_len = pre_len - len;
686             if self.char_eq.matches(c) {
687                 return SearchStep::Match(i, i + char_len);
688             } else {
689                 return SearchStep::Reject(i, i + char_len);
690             }
691         }
692         SearchStep::Done
693     }
694 }
695
696 impl<'a, C: MultiCharEq> DoubleEndedSearcher<'a> for MultiCharEqSearcher<'a, C> {}
697
698 /////////////////////////////////////////////////////////////////////////////
699
700 macro_rules! pattern_methods {
701     ($t:ty, $pmap:expr, $smap:expr) => {
702         type Searcher = $t;
703
704         #[inline]
705         fn into_searcher(self, haystack: &'a str) -> $t {
706             ($smap)(($pmap)(self).into_searcher(haystack))
707         }
708
709         #[inline]
710         fn is_contained_in(self, haystack: &'a str) -> bool {
711             ($pmap)(self).is_contained_in(haystack)
712         }
713
714         #[inline]
715         fn is_prefix_of(self, haystack: &'a str) -> bool {
716             ($pmap)(self).is_prefix_of(haystack)
717         }
718
719         #[inline]
720         fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> {
721             ($pmap)(self).strip_prefix_of(haystack)
722         }
723
724         #[inline]
725         fn is_suffix_of(self, haystack: &'a str) -> bool
726         where
727             $t: ReverseSearcher<'a>,
728         {
729             ($pmap)(self).is_suffix_of(haystack)
730         }
731
732         #[inline]
733         fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str>
734         where
735             $t: ReverseSearcher<'a>,
736         {
737             ($pmap)(self).strip_suffix_of(haystack)
738         }
739     };
740 }
741
742 macro_rules! searcher_methods {
743     (forward) => {
744         #[inline]
745         fn haystack(&self) -> &'a str {
746             self.0.haystack()
747         }
748         #[inline]
749         fn next(&mut self) -> SearchStep {
750             self.0.next()
751         }
752         #[inline]
753         fn next_match(&mut self) -> Option<(usize, usize)> {
754             self.0.next_match()
755         }
756         #[inline]
757         fn next_reject(&mut self) -> Option<(usize, usize)> {
758             self.0.next_reject()
759         }
760     };
761     (reverse) => {
762         #[inline]
763         fn next_back(&mut self) -> SearchStep {
764             self.0.next_back()
765         }
766         #[inline]
767         fn next_match_back(&mut self) -> Option<(usize, usize)> {
768             self.0.next_match_back()
769         }
770         #[inline]
771         fn next_reject_back(&mut self) -> Option<(usize, usize)> {
772             self.0.next_reject_back()
773         }
774     };
775 }
776
777 /// Associated type for `<[char; N] as Pattern<'a>>::Searcher`.
778 #[derive(Clone, Debug)]
779 pub struct CharArraySearcher<'a, const N: usize>(
780     <MultiCharEqPattern<[char; N]> as Pattern<'a>>::Searcher,
781 );
782
783 /// Associated type for `<&[char; N] as Pattern<'a>>::Searcher`.
784 #[derive(Clone, Debug)]
785 pub struct CharArrayRefSearcher<'a, 'b, const N: usize>(
786     <MultiCharEqPattern<&'b [char; N]> as Pattern<'a>>::Searcher,
787 );
788
789 /// Searches for chars that are equal to any of the [`char`]s in the array.
790 ///
791 /// # Examples
792 ///
793 /// ```
794 /// assert_eq!("Hello world".find(['l', 'l']), Some(2));
795 /// assert_eq!("Hello world".find(['l', 'l']), Some(2));
796 /// ```
797 impl<'a, const N: usize> Pattern<'a> for [char; N] {
798     pattern_methods!(CharArraySearcher<'a, N>, MultiCharEqPattern, CharArraySearcher);
799 }
800
801 unsafe impl<'a, const N: usize> Searcher<'a> for CharArraySearcher<'a, N> {
802     searcher_methods!(forward);
803 }
804
805 unsafe impl<'a, const N: usize> ReverseSearcher<'a> for CharArraySearcher<'a, N> {
806     searcher_methods!(reverse);
807 }
808
809 /// Searches for chars that are equal to any of the [`char`]s in the array.
810 ///
811 /// # Examples
812 ///
813 /// ```
814 /// assert_eq!("Hello world".find(&['l', 'l']), Some(2));
815 /// assert_eq!("Hello world".find(&['l', 'l']), Some(2));
816 /// ```
817 impl<'a, 'b, const N: usize> Pattern<'a> for &'b [char; N] {
818     pattern_methods!(CharArrayRefSearcher<'a, 'b, N>, MultiCharEqPattern, CharArrayRefSearcher);
819 }
820
821 unsafe impl<'a, 'b, const N: usize> Searcher<'a> for CharArrayRefSearcher<'a, 'b, N> {
822     searcher_methods!(forward);
823 }
824
825 unsafe impl<'a, 'b, const N: usize> ReverseSearcher<'a> for CharArrayRefSearcher<'a, 'b, N> {
826     searcher_methods!(reverse);
827 }
828
829 /////////////////////////////////////////////////////////////////////////////
830 // Impl for &[char]
831 /////////////////////////////////////////////////////////////////////////////
832
833 // Todo: Change / Remove due to ambiguity in meaning.
834
835 /// Associated type for `<&[char] as Pattern<'a>>::Searcher`.
836 #[derive(Clone, Debug)]
837 pub struct CharSliceSearcher<'a, 'b>(<MultiCharEqPattern<&'b [char]> as Pattern<'a>>::Searcher);
838
839 unsafe impl<'a, 'b> Searcher<'a> for CharSliceSearcher<'a, 'b> {
840     searcher_methods!(forward);
841 }
842
843 unsafe impl<'a, 'b> ReverseSearcher<'a> for CharSliceSearcher<'a, 'b> {
844     searcher_methods!(reverse);
845 }
846
847 impl<'a, 'b> DoubleEndedSearcher<'a> for CharSliceSearcher<'a, 'b> {}
848
849 /// Searches for chars that are equal to any of the [`char`]s in the slice.
850 ///
851 /// # Examples
852 ///
853 /// ```
854 /// assert_eq!("Hello world".find(&['l', 'l'] as &[_]), Some(2));
855 /// assert_eq!("Hello world".find(&['l', 'l'][..]), Some(2));
856 /// ```
857 impl<'a, 'b> Pattern<'a> for &'b [char] {
858     pattern_methods!(CharSliceSearcher<'a, 'b>, MultiCharEqPattern, CharSliceSearcher);
859 }
860
861 /////////////////////////////////////////////////////////////////////////////
862 // Impl for F: FnMut(char) -> bool
863 /////////////////////////////////////////////////////////////////////////////
864
865 /// Associated type for `<F as Pattern<'a>>::Searcher`.
866 #[derive(Clone)]
867 pub struct CharPredicateSearcher<'a, F>(<MultiCharEqPattern<F> as Pattern<'a>>::Searcher)
868 where
869     F: FnMut(char) -> bool;
870
871 impl<F> fmt::Debug for CharPredicateSearcher<'_, F>
872 where
873     F: FnMut(char) -> bool,
874 {
875     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
876         f.debug_struct("CharPredicateSearcher")
877             .field("haystack", &self.0.haystack)
878             .field("char_indices", &self.0.char_indices)
879             .finish()
880     }
881 }
882 unsafe impl<'a, F> Searcher<'a> for CharPredicateSearcher<'a, F>
883 where
884     F: FnMut(char) -> bool,
885 {
886     searcher_methods!(forward);
887 }
888
889 unsafe impl<'a, F> ReverseSearcher<'a> for CharPredicateSearcher<'a, F>
890 where
891     F: FnMut(char) -> bool,
892 {
893     searcher_methods!(reverse);
894 }
895
896 impl<'a, F> DoubleEndedSearcher<'a> for CharPredicateSearcher<'a, F> where F: FnMut(char) -> bool {}
897
898 /// Searches for [`char`]s that match the given predicate.
899 ///
900 /// # Examples
901 ///
902 /// ```
903 /// assert_eq!("Hello world".find(char::is_uppercase), Some(0));
904 /// assert_eq!("Hello world".find(|c| "aeiou".contains(c)), Some(1));
905 /// ```
906 impl<'a, F> Pattern<'a> for F
907 where
908     F: FnMut(char) -> bool,
909 {
910     pattern_methods!(CharPredicateSearcher<'a, F>, MultiCharEqPattern, CharPredicateSearcher);
911 }
912
913 /////////////////////////////////////////////////////////////////////////////
914 // Impl for &&str
915 /////////////////////////////////////////////////////////////////////////////
916
917 /// Delegates to the `&str` impl.
918 impl<'a, 'b, 'c> Pattern<'a> for &'c &'b str {
919     pattern_methods!(StrSearcher<'a, 'b>, |&s| s, |s| s);
920 }
921
922 /////////////////////////////////////////////////////////////////////////////
923 // Impl for &str
924 /////////////////////////////////////////////////////////////////////////////
925
926 /// Non-allocating substring search.
927 ///
928 /// Will handle the pattern `""` as returning empty matches at each character
929 /// boundary.
930 ///
931 /// # Examples
932 ///
933 /// ```
934 /// assert_eq!("Hello world".find("world"), Some(6));
935 /// ```
936 impl<'a, 'b> Pattern<'a> for &'b str {
937     type Searcher = StrSearcher<'a, 'b>;
938
939     #[inline]
940     fn into_searcher(self, haystack: &'a str) -> StrSearcher<'a, 'b> {
941         StrSearcher::new(haystack, self)
942     }
943
944     /// Checks whether the pattern matches at the front of the haystack.
945     #[inline]
946     fn is_prefix_of(self, haystack: &'a str) -> bool {
947         haystack.as_bytes().starts_with(self.as_bytes())
948     }
949
950     /// Checks whether the pattern matches anywhere in the haystack
951     #[inline]
952     fn is_contained_in(self, haystack: &'a str) -> bool {
953         if self.len() == 0 {
954             return true;
955         }
956
957         match self.len().cmp(&haystack.len()) {
958             Ordering::Less => {
959                 if self.len() == 1 {
960                     return haystack.as_bytes().contains(&self.as_bytes()[0]);
961                 }
962
963                 #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
964                 if self.len() <= 32 {
965                     if let Some(result) = simd_contains(self, haystack) {
966                         return result;
967                     }
968                 }
969
970                 self.into_searcher(haystack).next_match().is_some()
971             }
972             _ => self == haystack,
973         }
974     }
975
976     /// Removes the pattern from the front of haystack, if it matches.
977     #[inline]
978     fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> {
979         if self.is_prefix_of(haystack) {
980             // SAFETY: prefix was just verified to exist.
981             unsafe { Some(haystack.get_unchecked(self.as_bytes().len()..)) }
982         } else {
983             None
984         }
985     }
986
987     /// Checks whether the pattern matches at the back of the haystack.
988     #[inline]
989     fn is_suffix_of(self, haystack: &'a str) -> bool {
990         haystack.as_bytes().ends_with(self.as_bytes())
991     }
992
993     /// Removes the pattern from the back of haystack, if it matches.
994     #[inline]
995     fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str> {
996         if self.is_suffix_of(haystack) {
997             let i = haystack.len() - self.as_bytes().len();
998             // SAFETY: suffix was just verified to exist.
999             unsafe { Some(haystack.get_unchecked(..i)) }
1000         } else {
1001             None
1002         }
1003     }
1004 }
1005
1006 /////////////////////////////////////////////////////////////////////////////
1007 // Two Way substring searcher
1008 /////////////////////////////////////////////////////////////////////////////
1009
1010 #[derive(Clone, Debug)]
1011 /// Associated type for `<&str as Pattern<'a>>::Searcher`.
1012 pub struct StrSearcher<'a, 'b> {
1013     haystack: &'a str,
1014     needle: &'b str,
1015
1016     searcher: StrSearcherImpl,
1017 }
1018
1019 #[derive(Clone, Debug)]
1020 enum StrSearcherImpl {
1021     Empty(EmptyNeedle),
1022     TwoWay(TwoWaySearcher),
1023 }
1024
1025 #[derive(Clone, Debug)]
1026 struct EmptyNeedle {
1027     position: usize,
1028     end: usize,
1029     is_match_fw: bool,
1030     is_match_bw: bool,
1031     // Needed in case of an empty haystack, see #85462
1032     is_finished: bool,
1033 }
1034
1035 impl<'a, 'b> StrSearcher<'a, 'b> {
1036     fn new(haystack: &'a str, needle: &'b str) -> StrSearcher<'a, 'b> {
1037         if needle.is_empty() {
1038             StrSearcher {
1039                 haystack,
1040                 needle,
1041                 searcher: StrSearcherImpl::Empty(EmptyNeedle {
1042                     position: 0,
1043                     end: haystack.len(),
1044                     is_match_fw: true,
1045                     is_match_bw: true,
1046                     is_finished: false,
1047                 }),
1048             }
1049         } else {
1050             StrSearcher {
1051                 haystack,
1052                 needle,
1053                 searcher: StrSearcherImpl::TwoWay(TwoWaySearcher::new(
1054                     needle.as_bytes(),
1055                     haystack.len(),
1056                 )),
1057             }
1058         }
1059     }
1060 }
1061
1062 unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> {
1063     #[inline]
1064     fn haystack(&self) -> &'a str {
1065         self.haystack
1066     }
1067
1068     #[inline]
1069     fn next(&mut self) -> SearchStep {
1070         match self.searcher {
1071             StrSearcherImpl::Empty(ref mut searcher) => {
1072                 if searcher.is_finished {
1073                     return SearchStep::Done;
1074                 }
1075                 // empty needle rejects every char and matches every empty string between them
1076                 let is_match = searcher.is_match_fw;
1077                 searcher.is_match_fw = !searcher.is_match_fw;
1078                 let pos = searcher.position;
1079                 match self.haystack[pos..].chars().next() {
1080                     _ if is_match => SearchStep::Match(pos, pos),
1081                     None => {
1082                         searcher.is_finished = true;
1083                         SearchStep::Done
1084                     }
1085                     Some(ch) => {
1086                         searcher.position += ch.len_utf8();
1087                         SearchStep::Reject(pos, searcher.position)
1088                     }
1089                 }
1090             }
1091             StrSearcherImpl::TwoWay(ref mut searcher) => {
1092                 // TwoWaySearcher produces valid *Match* indices that split at char boundaries
1093                 // as long as it does correct matching and that haystack and needle are
1094                 // valid UTF-8
1095                 // *Rejects* from the algorithm can fall on any indices, but we will walk them
1096                 // manually to the next character boundary, so that they are utf-8 safe.
1097                 if searcher.position == self.haystack.len() {
1098                     return SearchStep::Done;
1099                 }
1100                 let is_long = searcher.memory == usize::MAX;
1101                 match searcher.next::<RejectAndMatch>(
1102                     self.haystack.as_bytes(),
1103                     self.needle.as_bytes(),
1104                     is_long,
1105                 ) {
1106                     SearchStep::Reject(a, mut b) => {
1107                         // skip to next char boundary
1108                         while !self.haystack.is_char_boundary(b) {
1109                             b += 1;
1110                         }
1111                         searcher.position = cmp::max(b, searcher.position);
1112                         SearchStep::Reject(a, b)
1113                     }
1114                     otherwise => otherwise,
1115                 }
1116             }
1117         }
1118     }
1119
1120     #[inline]
1121     fn next_match(&mut self) -> Option<(usize, usize)> {
1122         match self.searcher {
1123             StrSearcherImpl::Empty(..) => loop {
1124                 match self.next() {
1125                     SearchStep::Match(a, b) => return Some((a, b)),
1126                     SearchStep::Done => return None,
1127                     SearchStep::Reject(..) => {}
1128                 }
1129             },
1130             StrSearcherImpl::TwoWay(ref mut searcher) => {
1131                 let is_long = searcher.memory == usize::MAX;
1132                 // write out `true` and `false` cases to encourage the compiler
1133                 // to specialize the two cases separately.
1134                 if is_long {
1135                     searcher.next::<MatchOnly>(
1136                         self.haystack.as_bytes(),
1137                         self.needle.as_bytes(),
1138                         true,
1139                     )
1140                 } else {
1141                     searcher.next::<MatchOnly>(
1142                         self.haystack.as_bytes(),
1143                         self.needle.as_bytes(),
1144                         false,
1145                     )
1146                 }
1147             }
1148         }
1149     }
1150 }
1151
1152 unsafe impl<'a, 'b> ReverseSearcher<'a> for StrSearcher<'a, 'b> {
1153     #[inline]
1154     fn next_back(&mut self) -> SearchStep {
1155         match self.searcher {
1156             StrSearcherImpl::Empty(ref mut searcher) => {
1157                 if searcher.is_finished {
1158                     return SearchStep::Done;
1159                 }
1160                 let is_match = searcher.is_match_bw;
1161                 searcher.is_match_bw = !searcher.is_match_bw;
1162                 let end = searcher.end;
1163                 match self.haystack[..end].chars().next_back() {
1164                     _ if is_match => SearchStep::Match(end, end),
1165                     None => {
1166                         searcher.is_finished = true;
1167                         SearchStep::Done
1168                     }
1169                     Some(ch) => {
1170                         searcher.end -= ch.len_utf8();
1171                         SearchStep::Reject(searcher.end, end)
1172                     }
1173                 }
1174             }
1175             StrSearcherImpl::TwoWay(ref mut searcher) => {
1176                 if searcher.end == 0 {
1177                     return SearchStep::Done;
1178                 }
1179                 let is_long = searcher.memory == usize::MAX;
1180                 match searcher.next_back::<RejectAndMatch>(
1181                     self.haystack.as_bytes(),
1182                     self.needle.as_bytes(),
1183                     is_long,
1184                 ) {
1185                     SearchStep::Reject(mut a, b) => {
1186                         // skip to next char boundary
1187                         while !self.haystack.is_char_boundary(a) {
1188                             a -= 1;
1189                         }
1190                         searcher.end = cmp::min(a, searcher.end);
1191                         SearchStep::Reject(a, b)
1192                     }
1193                     otherwise => otherwise,
1194                 }
1195             }
1196         }
1197     }
1198
1199     #[inline]
1200     fn next_match_back(&mut self) -> Option<(usize, usize)> {
1201         match self.searcher {
1202             StrSearcherImpl::Empty(..) => loop {
1203                 match self.next_back() {
1204                     SearchStep::Match(a, b) => return Some((a, b)),
1205                     SearchStep::Done => return None,
1206                     SearchStep::Reject(..) => {}
1207                 }
1208             },
1209             StrSearcherImpl::TwoWay(ref mut searcher) => {
1210                 let is_long = searcher.memory == usize::MAX;
1211                 // write out `true` and `false`, like `next_match`
1212                 if is_long {
1213                     searcher.next_back::<MatchOnly>(
1214                         self.haystack.as_bytes(),
1215                         self.needle.as_bytes(),
1216                         true,
1217                     )
1218                 } else {
1219                     searcher.next_back::<MatchOnly>(
1220                         self.haystack.as_bytes(),
1221                         self.needle.as_bytes(),
1222                         false,
1223                     )
1224                 }
1225             }
1226         }
1227     }
1228 }
1229
1230 /// The internal state of the two-way substring search algorithm.
1231 #[derive(Clone, Debug)]
1232 struct TwoWaySearcher {
1233     // constants
1234     /// critical factorization index
1235     crit_pos: usize,
1236     /// critical factorization index for reversed needle
1237     crit_pos_back: usize,
1238     period: usize,
1239     /// `byteset` is an extension (not part of the two way algorithm);
1240     /// it's a 64-bit "fingerprint" where each set bit `j` corresponds
1241     /// to a (byte & 63) == j present in the needle.
1242     byteset: u64,
1243
1244     // variables
1245     position: usize,
1246     end: usize,
1247     /// index into needle before which we have already matched
1248     memory: usize,
1249     /// index into needle after which we have already matched
1250     memory_back: usize,
1251 }
1252
1253 /*
1254     This is the Two-Way search algorithm, which was introduced in the paper:
1255     Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.
1256
1257     Here's some background information.
1258
1259     A *word* is a string of symbols. The *length* of a word should be a familiar
1260     notion, and here we denote it for any word x by |x|.
1261     (We also allow for the possibility of the *empty word*, a word of length zero).
1262
1263     If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
1264     *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
1265     For example, both 1 and 2 are periods for the string "aa". As another example,
1266     the only period of the string "abcd" is 4.
1267
1268     We denote by period(x) the *smallest* period of x (provided that x is non-empty).
1269     This is always well-defined since every non-empty word x has at least one period,
1270     |x|. We sometimes call this *the period* of x.
1271
1272     If u, v and x are words such that x = uv, where uv is the concatenation of u and
1273     v, then we say that (u, v) is a *factorization* of x.
1274
1275     Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
1276     that both of the following hold
1277
1278       - either w is a suffix of u or u is a suffix of w
1279       - either w is a prefix of v or v is a prefix of w
1280
1281     then w is said to be a *repetition* for the factorization (u, v).
1282
1283     Just to unpack this, there are four possibilities here. Let w = "abc". Then we
1284     might have:
1285
1286       - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
1287       - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
1288       - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
1289       - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")
1290
1291     Note that the word vu is a repetition for any factorization (u,v) of x = uv,
1292     so every factorization has at least one repetition.
1293
1294     If x is a string and (u, v) is a factorization for x, then a *local period* for
1295     (u, v) is an integer r such that there is some word w such that |w| = r and w is
1296     a repetition for (u, v).
1297
1298     We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
1299     call this *the local period* of (u, v). Provided that x = uv is non-empty, this
1300     is well-defined (because each non-empty word has at least one factorization, as
1301     noted above).
1302
1303     It can be proven that the following is an equivalent definition of a local period
1304     for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
1305     all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
1306     defined. (i.e., i > 0 and i + r < |x|).
1307
1308     Using the above reformulation, it is easy to prove that
1309
1310         1 <= local_period(u, v) <= period(uv)
1311
1312     A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
1313     *critical factorization*.
1314
1315     The algorithm hinges on the following theorem, which is stated without proof:
1316
1317     **Critical Factorization Theorem** Any word x has at least one critical
1318     factorization (u, v) such that |u| < period(x).
1319
1320     The purpose of maximal_suffix is to find such a critical factorization.
1321
1322     If the period is short, compute another factorization x = u' v' to use
1323     for reverse search, chosen instead so that |v'| < period(x).
1324
1325 */
1326 impl TwoWaySearcher {
1327     fn new(needle: &[u8], end: usize) -> TwoWaySearcher {
1328         let (crit_pos_false, period_false) = TwoWaySearcher::maximal_suffix(needle, false);
1329         let (crit_pos_true, period_true) = TwoWaySearcher::maximal_suffix(needle, true);
1330
1331         let (crit_pos, period) = if crit_pos_false > crit_pos_true {
1332             (crit_pos_false, period_false)
1333         } else {
1334             (crit_pos_true, period_true)
1335         };
1336
1337         // A particularly readable explanation of what's going on here can be found
1338         // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
1339         // see the code for "Algorithm CP" on p. 323.
1340         //
1341         // What's going on is we have some critical factorization (u, v) of the
1342         // needle, and we want to determine whether u is a suffix of
1343         // &v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
1344         // "Algorithm CP2", which is optimized for when the period of the needle
1345         // is large.
1346         if needle[..crit_pos] == needle[period..period + crit_pos] {
1347             // short period case -- the period is exact
1348             // compute a separate critical factorization for the reversed needle
1349             // x = u' v' where |v'| < period(x).
1350             //
1351             // This is sped up by the period being known already.
1352             // Note that a case like x = "acba" may be factored exactly forwards
1353             // (crit_pos = 1, period = 3) while being factored with approximate
1354             // period in reverse (crit_pos = 2, period = 2). We use the given
1355             // reverse factorization but keep the exact period.
1356             let crit_pos_back = needle.len()
1357                 - cmp::max(
1358                     TwoWaySearcher::reverse_maximal_suffix(needle, period, false),
1359                     TwoWaySearcher::reverse_maximal_suffix(needle, period, true),
1360                 );
1361
1362             TwoWaySearcher {
1363                 crit_pos,
1364                 crit_pos_back,
1365                 period,
1366                 byteset: Self::byteset_create(&needle[..period]),
1367
1368                 position: 0,
1369                 end,
1370                 memory: 0,
1371                 memory_back: needle.len(),
1372             }
1373         } else {
1374             // long period case -- we have an approximation to the actual period,
1375             // and don't use memorization.
1376             //
1377             // Approximate the period by lower bound max(|u|, |v|) + 1.
1378             // The critical factorization is efficient to use for both forward and
1379             // reverse search.
1380
1381             TwoWaySearcher {
1382                 crit_pos,
1383                 crit_pos_back: crit_pos,
1384                 period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
1385                 byteset: Self::byteset_create(needle),
1386
1387                 position: 0,
1388                 end,
1389                 memory: usize::MAX, // Dummy value to signify that the period is long
1390                 memory_back: usize::MAX,
1391             }
1392         }
1393     }
1394
1395     #[inline]
1396     fn byteset_create(bytes: &[u8]) -> u64 {
1397         bytes.iter().fold(0, |a, &b| (1 << (b & 0x3f)) | a)
1398     }
1399
1400     #[inline]
1401     fn byteset_contains(&self, byte: u8) -> bool {
1402         (self.byteset >> ((byte & 0x3f) as usize)) & 1 != 0
1403     }
1404
1405     // One of the main ideas of Two-Way is that we factorize the needle into
1406     // two halves, (u, v), and begin trying to find v in the haystack by scanning
1407     // left to right. If v matches, we try to match u by scanning right to left.
1408     // How far we can jump when we encounter a mismatch is all based on the fact
1409     // that (u, v) is a critical factorization for the needle.
1410     #[inline]
1411     fn next<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> S::Output
1412     where
1413         S: TwoWayStrategy,
1414     {
1415         // `next()` uses `self.position` as its cursor
1416         let old_pos = self.position;
1417         let needle_last = needle.len() - 1;
1418         'search: loop {
1419             // Check that we have room to search in
1420             // position + needle_last can not overflow if we assume slices
1421             // are bounded by isize's range.
1422             let tail_byte = match haystack.get(self.position + needle_last) {
1423                 Some(&b) => b,
1424                 None => {
1425                     self.position = haystack.len();
1426                     return S::rejecting(old_pos, self.position);
1427                 }
1428             };
1429
1430             if S::use_early_reject() && old_pos != self.position {
1431                 return S::rejecting(old_pos, self.position);
1432             }
1433
1434             // Quickly skip by large portions unrelated to our substring
1435             if !self.byteset_contains(tail_byte) {
1436                 self.position += needle.len();
1437                 if !long_period {
1438                     self.memory = 0;
1439                 }
1440                 continue 'search;
1441             }
1442
1443             // See if the right part of the needle matches
1444             let start =
1445                 if long_period { self.crit_pos } else { cmp::max(self.crit_pos, self.memory) };
1446             for i in start..needle.len() {
1447                 if needle[i] != haystack[self.position + i] {
1448                     self.position += i - self.crit_pos + 1;
1449                     if !long_period {
1450                         self.memory = 0;
1451                     }
1452                     continue 'search;
1453                 }
1454             }
1455
1456             // See if the left part of the needle matches
1457             let start = if long_period { 0 } else { self.memory };
1458             for i in (start..self.crit_pos).rev() {
1459                 if needle[i] != haystack[self.position + i] {
1460                     self.position += self.period;
1461                     if !long_period {
1462                         self.memory = needle.len() - self.period;
1463                     }
1464                     continue 'search;
1465                 }
1466             }
1467
1468             // We have found a match!
1469             let match_pos = self.position;
1470
1471             // Note: add self.period instead of needle.len() to have overlapping matches
1472             self.position += needle.len();
1473             if !long_period {
1474                 self.memory = 0; // set to needle.len() - self.period for overlapping matches
1475             }
1476
1477             return S::matching(match_pos, match_pos + needle.len());
1478         }
1479     }
1480
1481     // Follows the ideas in `next()`.
1482     //
1483     // The definitions are symmetrical, with period(x) = period(reverse(x))
1484     // and local_period(u, v) = local_period(reverse(v), reverse(u)), so if (u, v)
1485     // is a critical factorization, so is (reverse(v), reverse(u)).
1486     //
1487     // For the reverse case we have computed a critical factorization x = u' v'
1488     // (field `crit_pos_back`). We need |u| < period(x) for the forward case and
1489     // thus |v'| < period(x) for the reverse.
1490     //
1491     // To search in reverse through the haystack, we search forward through
1492     // a reversed haystack with a reversed needle, matching first u' and then v'.
1493     #[inline]
1494     fn next_back<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> S::Output
1495     where
1496         S: TwoWayStrategy,
1497     {
1498         // `next_back()` uses `self.end` as its cursor -- so that `next()` and `next_back()`
1499         // are independent.
1500         let old_end = self.end;
1501         'search: loop {
1502             // Check that we have room to search in
1503             // end - needle.len() will wrap around when there is no more room,
1504             // but due to slice length limits it can never wrap all the way back
1505             // into the length of haystack.
1506             let front_byte = match haystack.get(self.end.wrapping_sub(needle.len())) {
1507                 Some(&b) => b,
1508                 None => {
1509                     self.end = 0;
1510                     return S::rejecting(0, old_end);
1511                 }
1512             };
1513
1514             if S::use_early_reject() && old_end != self.end {
1515                 return S::rejecting(self.end, old_end);
1516             }
1517
1518             // Quickly skip by large portions unrelated to our substring
1519             if !self.byteset_contains(front_byte) {
1520                 self.end -= needle.len();
1521                 if !long_period {
1522                     self.memory_back = needle.len();
1523                 }
1524                 continue 'search;
1525             }
1526
1527             // See if the left part of the needle matches
1528             let crit = if long_period {
1529                 self.crit_pos_back
1530             } else {
1531                 cmp::min(self.crit_pos_back, self.memory_back)
1532             };
1533             for i in (0..crit).rev() {
1534                 if needle[i] != haystack[self.end - needle.len() + i] {
1535                     self.end -= self.crit_pos_back - i;
1536                     if !long_period {
1537                         self.memory_back = needle.len();
1538                     }
1539                     continue 'search;
1540                 }
1541             }
1542
1543             // See if the right part of the needle matches
1544             let needle_end = if long_period { needle.len() } else { self.memory_back };
1545             for i in self.crit_pos_back..needle_end {
1546                 if needle[i] != haystack[self.end - needle.len() + i] {
1547                     self.end -= self.period;
1548                     if !long_period {
1549                         self.memory_back = self.period;
1550                     }
1551                     continue 'search;
1552                 }
1553             }
1554
1555             // We have found a match!
1556             let match_pos = self.end - needle.len();
1557             // Note: sub self.period instead of needle.len() to have overlapping matches
1558             self.end -= needle.len();
1559             if !long_period {
1560                 self.memory_back = needle.len();
1561             }
1562
1563             return S::matching(match_pos, match_pos + needle.len());
1564         }
1565     }
1566
1567     // Compute the maximal suffix of `arr`.
1568     //
1569     // The maximal suffix is a possible critical factorization (u, v) of `arr`.
1570     //
1571     // Returns (`i`, `p`) where `i` is the starting index of v and `p` is the
1572     // period of v.
1573     //
1574     // `order_greater` determines if lexical order is `<` or `>`. Both
1575     // orders must be computed -- the ordering with the largest `i` gives
1576     // a critical factorization.
1577     //
1578     // For long period cases, the resulting period is not exact (it is too short).
1579     #[inline]
1580     fn maximal_suffix(arr: &[u8], order_greater: bool) -> (usize, usize) {
1581         let mut left = 0; // Corresponds to i in the paper
1582         let mut right = 1; // Corresponds to j in the paper
1583         let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1584         // to match 0-based indexing.
1585         let mut period = 1; // Corresponds to p in the paper
1586
1587         while let Some(&a) = arr.get(right + offset) {
1588             // `left` will be inbounds when `right` is.
1589             let b = arr[left + offset];
1590             if (a < b && !order_greater) || (a > b && order_greater) {
1591                 // Suffix is smaller, period is entire prefix so far.
1592                 right += offset + 1;
1593                 offset = 0;
1594                 period = right - left;
1595             } else if a == b {
1596                 // Advance through repetition of the current period.
1597                 if offset + 1 == period {
1598                     right += offset + 1;
1599                     offset = 0;
1600                 } else {
1601                     offset += 1;
1602                 }
1603             } else {
1604                 // Suffix is larger, start over from current location.
1605                 left = right;
1606                 right += 1;
1607                 offset = 0;
1608                 period = 1;
1609             }
1610         }
1611         (left, period)
1612     }
1613
1614     // Compute the maximal suffix of the reverse of `arr`.
1615     //
1616     // The maximal suffix is a possible critical factorization (u', v') of `arr`.
1617     //
1618     // Returns `i` where `i` is the starting index of v', from the back;
1619     // returns immediately when a period of `known_period` is reached.
1620     //
1621     // `order_greater` determines if lexical order is `<` or `>`. Both
1622     // orders must be computed -- the ordering with the largest `i` gives
1623     // a critical factorization.
1624     //
1625     // For long period cases, the resulting period is not exact (it is too short).
1626     fn reverse_maximal_suffix(arr: &[u8], known_period: usize, order_greater: bool) -> usize {
1627         let mut left = 0; // Corresponds to i in the paper
1628         let mut right = 1; // Corresponds to j in the paper
1629         let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1630         // to match 0-based indexing.
1631         let mut period = 1; // Corresponds to p in the paper
1632         let n = arr.len();
1633
1634         while right + offset < n {
1635             let a = arr[n - (1 + right + offset)];
1636             let b = arr[n - (1 + left + offset)];
1637             if (a < b && !order_greater) || (a > b && order_greater) {
1638                 // Suffix is smaller, period is entire prefix so far.
1639                 right += offset + 1;
1640                 offset = 0;
1641                 period = right - left;
1642             } else if a == b {
1643                 // Advance through repetition of the current period.
1644                 if offset + 1 == period {
1645                     right += offset + 1;
1646                     offset = 0;
1647                 } else {
1648                     offset += 1;
1649                 }
1650             } else {
1651                 // Suffix is larger, start over from current location.
1652                 left = right;
1653                 right += 1;
1654                 offset = 0;
1655                 period = 1;
1656             }
1657             if period == known_period {
1658                 break;
1659             }
1660         }
1661         debug_assert!(period <= known_period);
1662         left
1663     }
1664 }
1665
1666 // TwoWayStrategy allows the algorithm to either skip non-matches as quickly
1667 // as possible, or to work in a mode where it emits Rejects relatively quickly.
1668 trait TwoWayStrategy {
1669     type Output;
1670     fn use_early_reject() -> bool;
1671     fn rejecting(a: usize, b: usize) -> Self::Output;
1672     fn matching(a: usize, b: usize) -> Self::Output;
1673 }
1674
1675 /// Skip to match intervals as quickly as possible
1676 enum MatchOnly {}
1677
1678 impl TwoWayStrategy for MatchOnly {
1679     type Output = Option<(usize, usize)>;
1680
1681     #[inline]
1682     fn use_early_reject() -> bool {
1683         false
1684     }
1685     #[inline]
1686     fn rejecting(_a: usize, _b: usize) -> Self::Output {
1687         None
1688     }
1689     #[inline]
1690     fn matching(a: usize, b: usize) -> Self::Output {
1691         Some((a, b))
1692     }
1693 }
1694
1695 /// Emit Rejects regularly
1696 enum RejectAndMatch {}
1697
1698 impl TwoWayStrategy for RejectAndMatch {
1699     type Output = SearchStep;
1700
1701     #[inline]
1702     fn use_early_reject() -> bool {
1703         true
1704     }
1705     #[inline]
1706     fn rejecting(a: usize, b: usize) -> Self::Output {
1707         SearchStep::Reject(a, b)
1708     }
1709     #[inline]
1710     fn matching(a: usize, b: usize) -> Self::Output {
1711         SearchStep::Match(a, b)
1712     }
1713 }
1714
1715 /// SIMD search for short needles based on
1716 /// Wojciech Muła's "SIMD-friendly algorithms for substring searching"[0]
1717 ///
1718 /// It skips ahead by the vector width on each iteration (rather than the needle length as two-way
1719 /// does) by probing the first and last byte of the needle for the whole vector width
1720 /// and only doing full needle comparisons when the vectorized probe indicated potential matches.
1721 ///
1722 /// Since the x86_64 baseline only offers SSE2 we only use u8x16 here.
1723 /// If we ever ship std with for x86-64-v3 or adapt this for other platforms then wider vectors
1724 /// should be evaluated.
1725 ///
1726 /// For haystacks smaller than vector-size + needle length it falls back to
1727 /// a naive O(n*m) search so this implementation should not be called on larger needles.
1728 ///
1729 /// [0]: http://0x80.pl/articles/simd-strfind.html#sse-avx2
1730 #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
1731 #[inline]
1732 fn simd_contains(needle: &str, haystack: &str) -> Option<bool> {
1733     let needle = needle.as_bytes();
1734     let haystack = haystack.as_bytes();
1735
1736     debug_assert!(needle.len() > 1);
1737
1738     use crate::ops::BitAnd;
1739     use crate::simd::mask8x16 as Mask;
1740     use crate::simd::u8x16 as Block;
1741     use crate::simd::{SimdPartialEq, ToBitMask};
1742
1743     let first_probe = needle[0];
1744     let last_byte_offset = needle.len() - 1;
1745
1746     // the offset used for the 2nd vector
1747     let second_probe_offset = if needle.len() == 2 {
1748         // never bail out on len=2 needles because the probes will fully cover them and have
1749         // no degenerate cases.
1750         1
1751     } else {
1752         // try a few bytes in case first and last byte of the needle are the same
1753         let Some(second_probe_offset) = (needle.len().saturating_sub(4)..needle.len()).rfind(|&idx| needle[idx] != first_probe) else {
1754             // fall back to other search methods if we can't find any different bytes
1755             // since we could otherwise hit some degenerate cases
1756             return None;
1757         };
1758         second_probe_offset
1759     };
1760
1761     // do a naive search if the haystack is too small to fit
1762     if haystack.len() < Block::LANES + last_byte_offset {
1763         return Some(haystack.windows(needle.len()).any(|c| c == needle));
1764     }
1765
1766     let first_probe: Block = Block::splat(first_probe);
1767     let second_probe: Block = Block::splat(needle[second_probe_offset]);
1768     // first byte are already checked by the outer loop. to verify a match only the
1769     // remainder has to be compared.
1770     let trimmed_needle = &needle[1..];
1771
1772     // this #[cold] is load-bearing, benchmark before removing it...
1773     let check_mask = #[cold]
1774     |idx, mask: u16, skip: bool| -> bool {
1775         if skip {
1776             return false;
1777         }
1778
1779         // and so is this. optimizations are weird.
1780         let mut mask = mask;
1781
1782         while mask != 0 {
1783             let trailing = mask.trailing_zeros();
1784             let offset = idx + trailing as usize + 1;
1785             // SAFETY: mask is between 0 and 15 trailing zeroes, we skip one additional byte that was already compared
1786             // and then take trimmed_needle.len() bytes. This is within the bounds defined by the outer loop
1787             unsafe {
1788                 let sub = haystack.get_unchecked(offset..).get_unchecked(..trimmed_needle.len());
1789                 if small_slice_eq(sub, trimmed_needle) {
1790                     return true;
1791                 }
1792             }
1793             mask &= !(1 << trailing);
1794         }
1795         return false;
1796     };
1797
1798     let test_chunk = |idx| -> u16 {
1799         // SAFETY: this requires at least LANES bytes being readable at idx
1800         // that is ensured by the loop ranges (see comments below)
1801         let a: Block = unsafe { haystack.as_ptr().add(idx).cast::<Block>().read_unaligned() };
1802         // SAFETY: this requires LANES + block_offset bytes being readable at idx
1803         let b: Block = unsafe {
1804             haystack.as_ptr().add(idx).add(second_probe_offset).cast::<Block>().read_unaligned()
1805         };
1806         let eq_first: Mask = a.simd_eq(first_probe);
1807         let eq_last: Mask = b.simd_eq(second_probe);
1808         let both = eq_first.bitand(eq_last);
1809         let mask = both.to_bitmask();
1810
1811         return mask;
1812     };
1813
1814     let mut i = 0;
1815     let mut result = false;
1816     // The loop condition must ensure that there's enough headroom to read LANE bytes,
1817     // and not only at the current index but also at the index shifted by block_offset
1818     const UNROLL: usize = 4;
1819     while i + last_byte_offset + UNROLL * Block::LANES < haystack.len() && !result {
1820         let mut masks = [0u16; UNROLL];
1821         for j in 0..UNROLL {
1822             masks[j] = test_chunk(i + j * Block::LANES);
1823         }
1824         for j in 0..UNROLL {
1825             let mask = masks[j];
1826             if mask != 0 {
1827                 result |= check_mask(i + j * Block::LANES, mask, result);
1828             }
1829         }
1830         i += UNROLL * Block::LANES;
1831     }
1832     while i + last_byte_offset + Block::LANES < haystack.len() && !result {
1833         let mask = test_chunk(i);
1834         if mask != 0 {
1835             result |= check_mask(i, mask, result);
1836         }
1837         i += Block::LANES;
1838     }
1839
1840     // Process the tail that didn't fit into LANES-sized steps.
1841     // This simply repeats the same procedure but as right-aligned chunk instead
1842     // of a left-aligned one. The last byte must be exactly flush with the string end so
1843     // we don't miss a single byte or read out of bounds.
1844     let i = haystack.len() - last_byte_offset - Block::LANES;
1845     let mask = test_chunk(i);
1846     if mask != 0 {
1847         result |= check_mask(i, mask, result);
1848     }
1849
1850     Some(result)
1851 }
1852
1853 /// Compares short slices for equality.
1854 ///
1855 /// It avoids a call to libc's memcmp which is faster on long slices
1856 /// due to SIMD optimizations but it incurs a function call overhead.
1857 ///
1858 /// # Safety
1859 ///
1860 /// Both slices must have the same length.
1861 #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] // only called on x86
1862 #[inline]
1863 unsafe fn small_slice_eq(x: &[u8], y: &[u8]) -> bool {
1864     debug_assert_eq!(x.len(), y.len());
1865     // This function is adapted from
1866     // https://github.com/BurntSushi/memchr/blob/8037d11b4357b0f07be2bb66dc2659d9cf28ad32/src/memmem/util.rs#L32
1867
1868     // If we don't have enough bytes to do 4-byte at a time loads, then
1869     // fall back to the naive slow version.
1870     //
1871     // Potential alternative: We could do a copy_nonoverlapping combined with a mask instead
1872     // of a loop. Benchmark it.
1873     if x.len() < 4 {
1874         for (&b1, &b2) in x.iter().zip(y) {
1875             if b1 != b2 {
1876                 return false;
1877             }
1878         }
1879         return true;
1880     }
1881     // When we have 4 or more bytes to compare, then proceed in chunks of 4 at
1882     // a time using unaligned loads.
1883     //
1884     // Also, why do 4 byte loads instead of, say, 8 byte loads? The reason is
1885     // that this particular version of memcmp is likely to be called with tiny
1886     // needles. That means that if we do 8 byte loads, then a higher proportion
1887     // of memcmp calls will use the slower variant above. With that said, this
1888     // is a hypothesis and is only loosely supported by benchmarks. There's
1889     // likely some improvement that could be made here. The main thing here
1890     // though is to optimize for latency, not throughput.
1891
1892     // SAFETY: Via the conditional above, we know that both `px` and `py`
1893     // have the same length, so `px < pxend` implies that `py < pyend`.
1894     // Thus, derefencing both `px` and `py` in the loop below is safe.
1895     //
1896     // Moreover, we set `pxend` and `pyend` to be 4 bytes before the actual
1897     // end of `px` and `py`. Thus, the final dereference outside of the
1898     // loop is guaranteed to be valid. (The final comparison will overlap with
1899     // the last comparison done in the loop for lengths that aren't multiples
1900     // of four.)
1901     //
1902     // Finally, we needn't worry about alignment here, since we do unaligned
1903     // loads.
1904     unsafe {
1905         let (mut px, mut py) = (x.as_ptr(), y.as_ptr());
1906         let (pxend, pyend) = (px.add(x.len() - 4), py.add(y.len() - 4));
1907         while px < pxend {
1908             let vx = (px as *const u32).read_unaligned();
1909             let vy = (py as *const u32).read_unaligned();
1910             if vx != vy {
1911                 return false;
1912             }
1913             px = px.add(4);
1914             py = py.add(4);
1915         }
1916         let vx = (pxend as *const u32).read_unaligned();
1917         let vy = (pyend as *const u32).read_unaligned();
1918         vx == vy
1919     }
1920 }