Skip to main content

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