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