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.is_empty() {
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.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.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    Byte(ByteNeedle),
1107    TwoWay(TwoWaySearcher),
1108}
1109#[derive(Clone, Debug)]
1110#[ferrocene::prevalidated]
1111struct EmptyNeedle {
1112    position: usize,
1113    end: usize,
1114    is_match_fw: bool,
1115    is_match_bw: bool,
1116    // Needed in case of an empty haystack, see #85462
1117    is_finished: bool,
1118}
1119
1120/// Fast searcher for a single-byte needle using `memchr`/`memrchr`.
1121#[ferrocene::prevalidated]
1122#[derive(Clone, Debug)]
1123struct ByteNeedle {
1124    b: u8,
1125    /// Forward cursor: `haystack[..position]` has already been reported.
1126    position: usize,
1127    /// Backward cursor: `haystack[end..]` has already been reported.
1128    end: usize,
1129}
1130
1131impl<'a, 'b> StrSearcher<'a, 'b> {
1132    #[ferrocene::prevalidated]
1133    fn new(haystack: &'a str, needle: &'b str) -> StrSearcher<'a, 'b> {
1134        if needle.is_empty() {
1135            StrSearcher {
1136                haystack,
1137                needle,
1138                searcher: StrSearcherImpl::Empty(EmptyNeedle {
1139                    position: 0,
1140                    end: haystack.len(),
1141                    is_match_fw: true,
1142                    is_match_bw: true,
1143                    is_finished: false,
1144                }),
1145            }
1146        } else if let &[b] = needle.as_bytes() {
1147            StrSearcher {
1148                haystack,
1149                needle,
1150                searcher: StrSearcherImpl::Byte(ByteNeedle { b, position: 0, end: haystack.len() }),
1151            }
1152        } else {
1153            StrSearcher {
1154                haystack,
1155                needle,
1156                searcher: StrSearcherImpl::TwoWay(TwoWaySearcher::new(
1157                    needle.as_bytes(),
1158                    haystack.len(),
1159                )),
1160            }
1161        }
1162    }
1163}
1164
1165unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> {
1166    #[inline]
1167    #[ferrocene::prevalidated]
1168    fn haystack(&self) -> &'a str {
1169        self.haystack
1170    }
1171
1172    #[inline]
1173    #[ferrocene::prevalidated]
1174    fn next(&mut self) -> SearchStep {
1175        match self.searcher {
1176            StrSearcherImpl::Empty(ref mut searcher) => {
1177                if searcher.is_finished {
1178                    return SearchStep::Done;
1179                }
1180                // empty needle rejects every char and matches every empty string between them
1181                let is_match = searcher.is_match_fw;
1182                searcher.is_match_fw = !searcher.is_match_fw;
1183                let pos = searcher.position;
1184                match self.haystack[pos..].chars().next() {
1185                    _ if is_match => SearchStep::Match(pos, pos),
1186                    None => {
1187                        searcher.is_finished = true;
1188                        SearchStep::Done
1189                    }
1190                    Some(ch) => {
1191                        searcher.position += ch.len_utf8();
1192                        SearchStep::Reject(pos, searcher.position)
1193                    }
1194                }
1195            }
1196            StrSearcherImpl::Byte(ref mut searcher) => {
1197                let bytes = self.haystack.as_bytes();
1198                let pos = searcher.position;
1199                if pos >= bytes.len() {
1200                    return SearchStep::Done;
1201                }
1202                if bytes[pos] == searcher.b {
1203                    searcher.position = pos + 1;
1204                    SearchStep::Match(pos, pos + 1)
1205                } else {
1206                    // `pos` is always on a char boundary, so this rejects
1207                    // exactly the char starting at `pos`.
1208                    let end = self.haystack.ceil_char_boundary(pos + 1);
1209                    searcher.position = end;
1210                    SearchStep::Reject(pos, end)
1211                }
1212            }
1213            StrSearcherImpl::TwoWay(ref mut searcher) => {
1214                // TwoWaySearcher produces valid *Match* indices that split at char boundaries
1215                // as long as it does correct matching and that haystack and needle are
1216                // valid UTF-8
1217                // *Rejects* from the algorithm can fall on any indices, but we will walk them
1218                // manually to the next character boundary, so that they are utf-8 safe.
1219                if searcher.position == self.haystack.len() {
1220                    return SearchStep::Done;
1221                }
1222                let is_long = searcher.memory == usize::MAX;
1223                match searcher.next::<RejectAndMatch>(
1224                    self.haystack.as_bytes(),
1225                    self.needle.as_bytes(),
1226                    is_long,
1227                ) {
1228                    SearchStep::Reject(a, b) => {
1229                        // skip to next char boundary
1230                        let b = self.haystack.ceil_char_boundary(b);
1231                        searcher.position = cmp::max(b, searcher.position);
1232                        SearchStep::Reject(a, b)
1233                    }
1234                    otherwise => otherwise,
1235                }
1236            }
1237        }
1238    }
1239
1240    #[inline]
1241    #[ferrocene::prevalidated]
1242    fn next_match(&mut self) -> Option<(usize, usize)> {
1243        match self.searcher {
1244            StrSearcherImpl::Empty(..) => loop {
1245                match self.next() {
1246                    SearchStep::Match(a, b) => return Some((a, b)),
1247                    SearchStep::Done => return None,
1248                    SearchStep::Reject(..) => {}
1249                }
1250            },
1251            StrSearcherImpl::Byte(ref mut searcher) => {
1252                let bytes = self.haystack.as_bytes();
1253                if searcher.position >= bytes.len() {
1254                    return None;
1255                }
1256                match memchr::memchr(searcher.b, &bytes[searcher.position..]) {
1257                    Some(i) => {
1258                        let pos = searcher.position + i;
1259                        searcher.position = pos + 1;
1260                        Some((pos, pos + 1))
1261                    }
1262                    None => {
1263                        searcher.position = bytes.len();
1264                        None
1265                    }
1266                }
1267            }
1268            StrSearcherImpl::TwoWay(ref mut searcher) => {
1269                let is_long = searcher.memory == usize::MAX;
1270                // write out `true` and `false` cases to encourage the compiler
1271                // to specialize the two cases separately.
1272                if is_long {
1273                    searcher.next::<MatchOnly>(
1274                        self.haystack.as_bytes(),
1275                        self.needle.as_bytes(),
1276                        true,
1277                    )
1278                } else {
1279                    searcher.next::<MatchOnly>(
1280                        self.haystack.as_bytes(),
1281                        self.needle.as_bytes(),
1282                        false,
1283                    )
1284                }
1285            }
1286        }
1287    }
1288}
1289
1290unsafe impl<'a, 'b> ReverseSearcher<'a> for StrSearcher<'a, 'b> {
1291    #[inline]
1292    #[ferrocene::prevalidated]
1293    fn next_back(&mut self) -> SearchStep {
1294        match self.searcher {
1295            StrSearcherImpl::Empty(ref mut searcher) => {
1296                if searcher.is_finished {
1297                    return SearchStep::Done;
1298                }
1299                let is_match = searcher.is_match_bw;
1300                searcher.is_match_bw = !searcher.is_match_bw;
1301                let end = searcher.end;
1302                match self.haystack[..end].chars().next_back() {
1303                    _ if is_match => SearchStep::Match(end, end),
1304                    None => {
1305                        searcher.is_finished = true;
1306                        SearchStep::Done
1307                    }
1308                    Some(ch) => {
1309                        searcher.end -= ch.len_utf8();
1310                        SearchStep::Reject(searcher.end, end)
1311                    }
1312                }
1313            }
1314            StrSearcherImpl::Byte(ref mut searcher) => {
1315                let end = searcher.end;
1316                if end == 0 {
1317                    return SearchStep::Done;
1318                }
1319                let bytes = self.haystack.as_bytes();
1320                if bytes[end - 1] == searcher.b {
1321                    searcher.end = end - 1;
1322                    SearchStep::Match(end - 1, end)
1323                } else {
1324                    let start = self.haystack.floor_char_boundary(end - 1);
1325                    searcher.end = start;
1326                    SearchStep::Reject(start, end)
1327                }
1328            }
1329            StrSearcherImpl::TwoWay(ref mut searcher) => {
1330                if searcher.end == 0 {
1331                    return SearchStep::Done;
1332                }
1333                let is_long = searcher.memory == usize::MAX;
1334                match searcher.next_back::<RejectAndMatch>(
1335                    self.haystack.as_bytes(),
1336                    self.needle.as_bytes(),
1337                    is_long,
1338                ) {
1339                    SearchStep::Reject(a, b) => {
1340                        // skip to previous char boundary
1341                        let a = self.haystack.floor_char_boundary(a);
1342                        searcher.end = cmp::min(a, searcher.end);
1343                        SearchStep::Reject(a, b)
1344                    }
1345                    otherwise => otherwise,
1346                }
1347            }
1348        }
1349    }
1350
1351    #[inline]
1352    fn next_match_back(&mut self) -> Option<(usize, usize)> {
1353        match self.searcher {
1354            StrSearcherImpl::Empty(..) => loop {
1355                match self.next_back() {
1356                    SearchStep::Match(a, b) => return Some((a, b)),
1357                    SearchStep::Done => return None,
1358                    SearchStep::Reject(..) => {}
1359                }
1360            },
1361            StrSearcherImpl::Byte(ref mut searcher) => {
1362                if searcher.end == 0 {
1363                    return None;
1364                }
1365                let bytes = self.haystack.as_bytes();
1366                match memchr::memrchr(searcher.b, &bytes[..searcher.end]) {
1367                    Some(i) => {
1368                        searcher.end = i;
1369                        Some((i, i + 1))
1370                    }
1371                    None => {
1372                        searcher.end = 0;
1373                        None
1374                    }
1375                }
1376            }
1377            StrSearcherImpl::TwoWay(ref mut searcher) => {
1378                let is_long = searcher.memory == usize::MAX;
1379                // write out `true` and `false`, like `next_match`
1380                if is_long {
1381                    searcher.next_back::<MatchOnly>(
1382                        self.haystack.as_bytes(),
1383                        self.needle.as_bytes(),
1384                        true,
1385                    )
1386                } else {
1387                    searcher.next_back::<MatchOnly>(
1388                        self.haystack.as_bytes(),
1389                        self.needle.as_bytes(),
1390                        false,
1391                    )
1392                }
1393            }
1394        }
1395    }
1396}
1397
1398/// The internal state of the two-way substring search algorithm.
1399#[derive(Clone, Debug)]
1400#[ferrocene::prevalidated]
1401struct TwoWaySearcher {
1402    // constants
1403    /// critical factorization index
1404    crit_pos: usize,
1405    /// critical factorization index for reversed needle
1406    crit_pos_back: usize,
1407    period: usize,
1408    /// `byteset` is an extension (not part of the two way algorithm);
1409    /// it's a 64-bit "fingerprint" where each set bit `j` corresponds
1410    /// to a (byte & 63) == j present in the needle.
1411    byteset: u64,
1412
1413    // variables
1414    position: usize,
1415    end: usize,
1416    /// index into needle before which we have already matched
1417    memory: usize,
1418    /// index into needle after which we have already matched
1419    memory_back: usize,
1420}
1421
1422/*
1423    This is the Two-Way search algorithm, which was introduced in the paper:
1424    Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.
1425
1426    Here's some background information.
1427
1428    A *word* is a string of symbols. The *length* of a word should be a familiar
1429    notion, and here we denote it for any word x by |x|.
1430    (We also allow for the possibility of the *empty word*, a word of length zero).
1431
1432    If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
1433    *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
1434    For example, both 1 and 2 are periods for the string "aa". As another example,
1435    the only period of the string "abcd" is 4.
1436
1437    We denote by period(x) the *smallest* period of x (provided that x is non-empty).
1438    This is always well-defined since every non-empty word x has at least one period,
1439    |x|. We sometimes call this *the period* of x.
1440
1441    If u, v and x are words such that x = uv, where uv is the concatenation of u and
1442    v, then we say that (u, v) is a *factorization* of x.
1443
1444    Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
1445    that both of the following hold
1446
1447      - either w is a suffix of u or u is a suffix of w
1448      - either w is a prefix of v or v is a prefix of w
1449
1450    then w is said to be a *repetition* for the factorization (u, v).
1451
1452    Just to unpack this, there are four possibilities here. Let w = "abc". Then we
1453    might have:
1454
1455      - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
1456      - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
1457      - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
1458      - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")
1459
1460    Note that the word vu is a repetition for any factorization (u,v) of x = uv,
1461    so every factorization has at least one repetition.
1462
1463    If x is a string and (u, v) is a factorization for x, then a *local period* for
1464    (u, v) is an integer r such that there is some word w such that |w| = r and w is
1465    a repetition for (u, v).
1466
1467    We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
1468    call this *the local period* of (u, v). Provided that x = uv is non-empty, this
1469    is well-defined (because each non-empty word has at least one factorization, as
1470    noted above).
1471
1472    It can be proven that the following is an equivalent definition of a local period
1473    for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
1474    all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
1475    defined. (i.e., i > 0 and i + r < |x|).
1476
1477    Using the above reformulation, it is easy to prove that
1478
1479        1 <= local_period(u, v) <= period(uv)
1480
1481    A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
1482    *critical factorization*.
1483
1484    The algorithm hinges on the following theorem, which is stated without proof:
1485
1486    **Critical Factorization Theorem** Any word x has at least one critical
1487    factorization (u, v) such that |u| < period(x).
1488
1489    The purpose of maximal_suffix is to find such a critical factorization.
1490
1491    If the period is short, compute another factorization x = u' v' to use
1492    for reverse search, chosen instead so that |v'| < period(x).
1493
1494*/
1495impl TwoWaySearcher {
1496    #[ferrocene::prevalidated]
1497    fn new(needle: &[u8], end: usize) -> TwoWaySearcher {
1498        let (crit_pos_false, period_false) = TwoWaySearcher::maximal_suffix(needle, false);
1499        let (crit_pos_true, period_true) = TwoWaySearcher::maximal_suffix(needle, true);
1500
1501        let (crit_pos, period) = if crit_pos_false > crit_pos_true {
1502            (crit_pos_false, period_false)
1503        } else {
1504            (crit_pos_true, period_true)
1505        };
1506
1507        // A particularly readable explanation of what's going on here can be found
1508        // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
1509        // see the code for "Algorithm CP" on p. 323.
1510        //
1511        // What's going on is we have some critical factorization (u, v) of the
1512        // needle, and we want to determine whether u is a suffix of
1513        // &v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
1514        // "Algorithm CP2", which is optimized for when the period of the needle
1515        // is large.
1516        if needle[..crit_pos] == needle[period..period + crit_pos] {
1517            // short period case -- the period is exact
1518            // compute a separate critical factorization for the reversed needle
1519            // x = u' v' where |v'| < period(x).
1520            //
1521            // This is sped up by the period being known already.
1522            // Note that a case like x = "acba" may be factored exactly forwards
1523            // (crit_pos = 1, period = 3) while being factored with approximate
1524            // period in reverse (crit_pos = 2, period = 2). We use the given
1525            // reverse factorization but keep the exact period.
1526            let crit_pos_back = needle.len()
1527                - cmp::max(
1528                    TwoWaySearcher::reverse_maximal_suffix(needle, period, false),
1529                    TwoWaySearcher::reverse_maximal_suffix(needle, period, true),
1530                );
1531
1532            TwoWaySearcher {
1533                crit_pos,
1534                crit_pos_back,
1535                period,
1536                byteset: Self::byteset_create(&needle[..period]),
1537
1538                position: 0,
1539                end,
1540                memory: 0,
1541                memory_back: needle.len(),
1542            }
1543        } else {
1544            // long period case -- we have an approximation to the actual period,
1545            // and don't use memorization.
1546            //
1547            // Approximate the period by lower bound max(|u|, |v|) + 1.
1548            // The critical factorization is efficient to use for both forward and
1549            // reverse search.
1550
1551            TwoWaySearcher {
1552                crit_pos,
1553                crit_pos_back: crit_pos,
1554                period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
1555                byteset: Self::byteset_create(needle),
1556
1557                position: 0,
1558                end,
1559                memory: usize::MAX, // Dummy value to signify that the period is long
1560                memory_back: usize::MAX,
1561            }
1562        }
1563    }
1564
1565    #[inline]
1566    #[ferrocene::prevalidated]
1567    fn byteset_create(bytes: &[u8]) -> u64 {
1568        bytes.iter().fold(0, |a, &b| (1 << (b & 0x3f)) | a)
1569    }
1570
1571    #[inline]
1572    #[ferrocene::prevalidated]
1573    fn byteset_contains(&self, byte: u8) -> bool {
1574        (self.byteset >> ((byte & 0x3f) as usize)) & 1 != 0
1575    }
1576
1577    // One of the main ideas of Two-Way is that we factorize the needle into
1578    // two halves, (u, v), and begin trying to find v in the haystack by scanning
1579    // left to right. If v matches, we try to match u by scanning right to left.
1580    // How far we can jump when we encounter a mismatch is all based on the fact
1581    // that (u, v) is a critical factorization for the needle.
1582    #[inline]
1583    #[ferrocene::prevalidated]
1584    fn next<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> S::Output
1585    where
1586        S: TwoWayStrategy,
1587    {
1588        // `next()` uses `self.position` as its cursor
1589        let old_pos = self.position;
1590        let needle_last = needle.len() - 1;
1591        'search: loop {
1592            // Check that we have room to search in
1593            // position + needle_last can not overflow if we assume slices
1594            // are bounded by isize's range.
1595            let tail_byte = match haystack.get(self.position + needle_last) {
1596                Some(&b) => b,
1597                None => {
1598                    self.position = haystack.len();
1599                    return S::rejecting(old_pos, self.position);
1600                }
1601            };
1602
1603            if S::use_early_reject() && old_pos != self.position {
1604                return S::rejecting(old_pos, self.position);
1605            }
1606
1607            // Quickly skip by large portions unrelated to our substring
1608            if !self.byteset_contains(tail_byte) {
1609                self.position += needle.len();
1610                if !long_period {
1611                    self.memory = 0;
1612                }
1613                continue 'search;
1614            }
1615
1616            // See if the right part of the needle matches
1617            let start =
1618                if long_period { self.crit_pos } else { cmp::max(self.crit_pos, self.memory) };
1619            for i in start..needle.len() {
1620                // SAFETY: on every iteration of `'search`, the `haystack.get(self.position + needle_last)`
1621                // check returned `Some`, so `self.position + needle_last < haystack.len()`.
1622                // Since `i < needle.len()` implies `i <= needle_last`, we have
1623                // `self.position + i < haystack.len()`.
1624                // Every path that mutates `self.position` below either returns or re-enters `'search`,
1625                // which re-runs the check before reaching the loop again.
1626                if needle[i] != unsafe { *haystack.get_unchecked(self.position + i) } {
1627                    self.position += i - self.crit_pos + 1;
1628                    if !long_period {
1629                        self.memory = 0;
1630                    }
1631                    continue 'search;
1632                }
1633            }
1634
1635            // See if the left part of the needle matches
1636            let start = if long_period { 0 } else { self.memory };
1637            for i in (start..self.crit_pos).rev() {
1638                // SAFETY: on every iteration of `'search`, the `haystack.get(self.position + needle_last)`
1639                // check returned `Some`, so `self.position + needle_last < haystack.len()`.
1640                // Since `i < self.crit_pos <= needle.len()`, we have `i <= needle_last`, and thus
1641                // `self.position + i <= self.position + needle_last < haystack.len()`.
1642                // Every path that mutates `self.position` below either returns or re-enters `'search`,
1643                // which re-runs the check before reaching the loop again.
1644                if needle[i] != unsafe { *haystack.get_unchecked(self.position + i) } {
1645                    self.position += self.period;
1646                    if !long_period {
1647                        self.memory = needle.len() - self.period;
1648                    }
1649                    continue 'search;
1650                }
1651            }
1652
1653            // We have found a match!
1654            let match_pos = self.position;
1655
1656            // Note: add self.period instead of needle.len() to have overlapping matches
1657            self.position += needle.len();
1658            if !long_period {
1659                self.memory = 0; // set to needle.len() - self.period for overlapping matches
1660            }
1661
1662            return S::matching(match_pos, match_pos + needle.len());
1663        }
1664    }
1665
1666    // Follows the ideas in `next()`.
1667    //
1668    // The definitions are symmetrical, with period(x) = period(reverse(x))
1669    // and local_period(u, v) = local_period(reverse(v), reverse(u)), so if (u, v)
1670    // is a critical factorization, so is (reverse(v), reverse(u)).
1671    //
1672    // For the reverse case we have computed a critical factorization x = u' v'
1673    // (field `crit_pos_back`). We need |u| < period(x) for the forward case and
1674    // thus |v'| < period(x) for the reverse.
1675    //
1676    // To search in reverse through the haystack, we search forward through
1677    // a reversed haystack with a reversed needle, matching first u' and then v'.
1678    #[inline]
1679    #[ferrocene::prevalidated]
1680    fn next_back<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> S::Output
1681    where
1682        S: TwoWayStrategy,
1683    {
1684        // `next_back()` uses `self.end` as its cursor -- so that `next()` and `next_back()`
1685        // are independent.
1686        let old_end = self.end;
1687        'search: loop {
1688            // Check that we have room to search in
1689            // end - needle.len() will wrap around when there is no more room,
1690            // but due to slice length limits it can never wrap all the way back
1691            // into the length of haystack.
1692            let front_byte = match haystack.get(self.end.wrapping_sub(needle.len())) {
1693                Some(&b) => b,
1694                None => {
1695                    self.end = 0;
1696                    return S::rejecting(0, old_end);
1697                }
1698            };
1699
1700            if S::use_early_reject() && old_end != self.end {
1701                return S::rejecting(self.end, old_end);
1702            }
1703
1704            // Quickly skip by large portions unrelated to our substring
1705            if !self.byteset_contains(front_byte) {
1706                self.end -= needle.len();
1707                if !long_period {
1708                    self.memory_back = needle.len();
1709                }
1710                continue 'search;
1711            }
1712
1713            // See if the left part of the needle matches
1714            let crit = if long_period {
1715                self.crit_pos_back
1716            } else {
1717                cmp::min(self.crit_pos_back, self.memory_back)
1718            };
1719            for i in (0..crit).rev() {
1720                // SAFETY: On every iteration of `'search`, `haystack.get(self.end.wrapping_sub(needle.len()))`
1721                //   returned `Some`, so `self.end >= needle.len()` and `self.end - needle.len() < haystack.len()`.
1722                //   Since `self.end <= haystack.len()` and `i < needle.len()`, we have
1723                //   `self.end - needle.len() + i < self.end <= haystack.len()`, so
1724                //   `haystack.get_unchecked(self.end - needle.len() + i)` is safe.
1725                // - The path that mutates `self.end` either re-enters `'search`, which re-runs the checks
1726                //   before reaching this loop again, or returns on match, so the invariant holds.
1727                if needle[i] != unsafe { *haystack.get_unchecked(self.end - needle.len() + i) } {
1728                    self.end -= self.crit_pos_back - i;
1729                    if !long_period {
1730                        self.memory_back = needle.len();
1731                    }
1732                    continue 'search;
1733                }
1734            }
1735
1736            // See if the right part of the needle matches
1737            let needle_end = if long_period { needle.len() } else { self.memory_back };
1738            for i in self.crit_pos_back..needle_end {
1739                // SAFETY: The same `self.end - needle.len() + i < haystack.len()` argument as the
1740                // left-part loop applies: the `haystack.get(self.end.wrapping_sub(needle.len()))`
1741                // check at the top of `'search` established the bound for this iteration, and
1742                // every mutation of `self.end` is followed by `continue 'search` (which re-runs
1743                // the check) or a `return` (which exits before any further unsafe access).
1744                if needle[i] != unsafe { *haystack.get_unchecked(self.end - needle.len() + i) } {
1745                    self.end -= self.period;
1746                    if !long_period {
1747                        self.memory_back = self.period;
1748                    }
1749                    continue 'search;
1750                }
1751            }
1752
1753            // We have found a match!
1754            let match_pos = self.end - needle.len();
1755            // Note: sub self.period instead of needle.len() to have overlapping matches
1756            self.end -= needle.len();
1757            if !long_period {
1758                self.memory_back = needle.len();
1759            }
1760
1761            return S::matching(match_pos, match_pos + needle.len());
1762        }
1763    }
1764
1765    // Compute the maximal suffix of `arr`.
1766    //
1767    // The maximal suffix is a possible critical factorization (u, v) of `arr`.
1768    //
1769    // Returns (`i`, `p`) where `i` is the starting index of v and `p` is the
1770    // period of v.
1771    //
1772    // `order_greater` determines if lexical order is `<` or `>`. Both
1773    // orders must be computed -- the ordering with the largest `i` gives
1774    // a critical factorization.
1775    //
1776    // For long period cases, the resulting period is not exact (it is too short).
1777    #[inline]
1778    #[ferrocene::prevalidated]
1779    fn maximal_suffix(arr: &[u8], order_greater: bool) -> (usize, usize) {
1780        let mut left = 0; // Corresponds to i in the paper
1781        let mut right = 1; // Corresponds to j in the paper
1782        let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1783        // to match 0-based indexing.
1784        let mut period = 1; // Corresponds to p in the paper
1785
1786        while let Some(&a) = arr.get(right + offset) {
1787            // `left` will be inbounds when `right` is.
1788            let b = arr[left + offset];
1789            if (a < b && !order_greater) || (a > b && order_greater) {
1790                // Suffix is smaller, period is entire prefix so far.
1791                right += offset + 1;
1792                offset = 0;
1793                period = right - left;
1794            } else if a == b {
1795                // Advance through repetition of the current period.
1796                if offset + 1 == period {
1797                    right += offset + 1;
1798                    offset = 0;
1799                } else {
1800                    offset += 1;
1801                }
1802            } else {
1803                // Suffix is larger, start over from current location.
1804                left = right;
1805                right += 1;
1806                offset = 0;
1807                period = 1;
1808            }
1809        }
1810        (left, period)
1811    }
1812
1813    // Compute the maximal suffix of the reverse of `arr`.
1814    //
1815    // The maximal suffix is a possible critical factorization (u', v') of `arr`.
1816    //
1817    // Returns `i` where `i` is the starting index of v', from the back;
1818    // returns immediately when a period of `known_period` is reached.
1819    //
1820    // `order_greater` determines if lexical order is `<` or `>`. Both
1821    // orders must be computed -- the ordering with the largest `i` gives
1822    // a critical factorization.
1823    //
1824    // For long period cases, the resulting period is not exact (it is too short).
1825    #[ferrocene::prevalidated]
1826    fn reverse_maximal_suffix(arr: &[u8], known_period: usize, order_greater: bool) -> usize {
1827        let mut left = 0; // Corresponds to i in the paper
1828        let mut right = 1; // Corresponds to j in the paper
1829        let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1830        // to match 0-based indexing.
1831        let mut period = 1; // Corresponds to p in the paper
1832        let n = arr.len();
1833
1834        while right + offset < n {
1835            let a = arr[n - (1 + right + offset)];
1836            let b = arr[n - (1 + left + offset)];
1837            if (a < b && !order_greater) || (a > b && order_greater) {
1838                // Suffix is smaller, period is entire prefix so far.
1839                right += offset + 1;
1840                offset = 0;
1841                period = right - left;
1842            } else if a == b {
1843                // Advance through repetition of the current period.
1844                if offset + 1 == period {
1845                    right += offset + 1;
1846                    offset = 0;
1847                } else {
1848                    offset += 1;
1849                }
1850            } else {
1851                // Suffix is larger, start over from current location.
1852                left = right;
1853                right += 1;
1854                offset = 0;
1855                period = 1;
1856            }
1857            if period == known_period {
1858                break;
1859            }
1860        }
1861        debug_assert!(period <= known_period);
1862        left
1863    }
1864}
1865
1866// TwoWayStrategy allows the algorithm to either skip non-matches as quickly
1867// as possible, or to work in a mode where it emits Rejects relatively quickly.
1868trait TwoWayStrategy {
1869    type Output;
1870    fn use_early_reject() -> bool;
1871    fn rejecting(a: usize, b: usize) -> Self::Output;
1872    fn matching(a: usize, b: usize) -> Self::Output;
1873}
1874
1875/// Skip to match intervals as quickly as possible
1876#[ferrocene::prevalidated]
1877enum MatchOnly {}
1878
1879impl TwoWayStrategy for MatchOnly {
1880    type Output = Option<(usize, usize)>;
1881
1882    #[inline]
1883    #[ferrocene::prevalidated]
1884    fn use_early_reject() -> bool {
1885        false
1886    }
1887    #[inline]
1888    #[ferrocene::prevalidated]
1889    fn rejecting(_a: usize, _b: usize) -> Self::Output {
1890        None
1891    }
1892    #[inline]
1893    #[ferrocene::prevalidated]
1894    fn matching(a: usize, b: usize) -> Self::Output {
1895        Some((a, b))
1896    }
1897}
1898
1899/// Emit Rejects regularly
1900#[ferrocene::prevalidated]
1901enum RejectAndMatch {}
1902
1903impl TwoWayStrategy for RejectAndMatch {
1904    type Output = SearchStep;
1905
1906    #[inline]
1907    #[ferrocene::prevalidated]
1908    fn use_early_reject() -> bool {
1909        true
1910    }
1911    #[inline]
1912    #[ferrocene::prevalidated]
1913    fn rejecting(a: usize, b: usize) -> Self::Output {
1914        SearchStep::Reject(a, b)
1915    }
1916    #[inline]
1917    #[ferrocene::prevalidated]
1918    fn matching(a: usize, b: usize) -> Self::Output {
1919        SearchStep::Match(a, b)
1920    }
1921}
1922
1923/// SIMD search for short needles based on
1924/// Wojciech Muła's "SIMD-friendly algorithms for substring searching"[0]
1925///
1926/// It skips ahead by the vector width on each iteration (rather than the needle length as two-way
1927/// does) by probing the first and last byte of the needle for the whole vector width
1928/// and only doing full needle comparisons when the vectorized probe indicated potential matches.
1929///
1930/// Since the x86_64 baseline only offers SSE2 we only use u8x16 here.
1931/// If we ever ship std with for x86-64-v3 or adapt this for other platforms then wider vectors
1932/// should be evaluated.
1933///
1934/// Similarly, on LoongArch the 128-bit LSX vector extension is the baseline,
1935/// so we also use `u8x16` there. Wider vector widths may be considered
1936/// for future LoongArch extensions (e.g., LASX).
1937///
1938/// For haystacks smaller than vector-size + needle length it falls back to
1939/// a naive O(n*m) search so this implementation should not be called on larger needles.
1940///
1941/// [0]: http://0x80.pl/articles/simd-strfind.html#sse-avx2
1942#[cfg(any(
1943    all(target_arch = "x86_64", target_feature = "sse2"),
1944    all(target_arch = "loongarch64", target_feature = "lsx"),
1945    all(target_arch = "aarch64", target_feature = "neon")
1946))]
1947#[inline]
1948fn simd_contains(needle: &str, haystack: &str) -> Option<bool> {
1949    let needle = needle.as_bytes();
1950    let haystack = haystack.as_bytes();
1951
1952    debug_assert!(needle.len() > 1);
1953
1954    use crate::ops::BitAnd;
1955    use crate::simd::cmp::SimdPartialEq;
1956    use crate::simd::{mask8x16 as Mask, u8x16 as Block};
1957
1958    let first_probe = needle[0];
1959    let last_byte_offset = needle.len() - 1;
1960
1961    // the offset used for the 2nd vector
1962    let second_probe_offset = if needle.len() == 2 {
1963        // never bail out on len=2 needles because the probes will fully cover them and have
1964        // no degenerate cases.
1965        1
1966    } else {
1967        // try a few bytes in case first and last byte of the needle are the same
1968        let Some(second_probe_offset) =
1969            (needle.len().saturating_sub(4)..needle.len()).rfind(|&idx| needle[idx] != first_probe)
1970        else {
1971            // fall back to other search methods if we can't find any different bytes
1972            // since we could otherwise hit some degenerate cases
1973            return None;
1974        };
1975        second_probe_offset
1976    };
1977
1978    // do a naive search if the haystack is too small to fit
1979    if haystack.len() < Block::LEN + last_byte_offset {
1980        return Some(haystack.windows(needle.len()).any(|c| c == needle));
1981    }
1982
1983    let first_probe: Block = Block::splat(first_probe);
1984    let second_probe: Block = Block::splat(needle[second_probe_offset]);
1985    // first byte are already checked by the outer loop. to verify a match only the
1986    // remainder has to be compared.
1987    let trimmed_needle = &needle[1..];
1988
1989    // this #[cold] is load-bearing, benchmark before removing it...
1990    let check_mask = #[cold]
1991    |idx, mask: u16, skip: bool| -> bool {
1992        if skip {
1993            return false;
1994        }
1995
1996        // and so is this. optimizations are weird.
1997        let mut mask = mask;
1998
1999        while mask != 0 {
2000            let trailing = mask.trailing_zeros();
2001            let offset = idx + trailing as usize + 1;
2002            // SAFETY: mask is between 0 and 15 trailing zeroes, we skip one additional byte that was already compared
2003            // and then take trimmed_needle.len() bytes. This is within the bounds defined by the outer loop
2004            unsafe {
2005                let sub = haystack.get_unchecked(offset..).get_unchecked(..trimmed_needle.len());
2006                if small_slice_eq(sub, trimmed_needle) {
2007                    return true;
2008                }
2009            }
2010            mask &= !(1 << trailing);
2011        }
2012        false
2013    };
2014
2015    let test_chunk = |idx| -> u16 {
2016        // SAFETY: this requires at least LANES bytes being readable at idx
2017        // that is ensured by the loop ranges (see comments below)
2018        let a: Block = unsafe { haystack.as_ptr().add(idx).cast::<Block>().read_unaligned() };
2019        // SAFETY: this requires LANES + block_offset bytes being readable at idx
2020        let b: Block = unsafe {
2021            haystack.as_ptr().add(idx).add(second_probe_offset).cast::<Block>().read_unaligned()
2022        };
2023        let eq_first: Mask = a.simd_eq(first_probe);
2024        let eq_last: Mask = b.simd_eq(second_probe);
2025        let both = eq_first.bitand(eq_last);
2026        both.to_bitmask() as u16
2027    };
2028
2029    let mut i = 0;
2030    let mut result = false;
2031    // The loop condition must ensure that there's enough headroom to read LANE bytes,
2032    // and not only at the current index but also at the index shifted by block_offset
2033    const UNROLL: usize = 4;
2034    while i + last_byte_offset + UNROLL * Block::LEN < haystack.len() && !result {
2035        let mut masks = [0u16; UNROLL];
2036        for j in 0..UNROLL {
2037            masks[j] = test_chunk(i + j * Block::LEN);
2038        }
2039        for j in 0..UNROLL {
2040            let mask = masks[j];
2041            if mask != 0 {
2042                result |= check_mask(i + j * Block::LEN, mask, result);
2043            }
2044        }
2045        i += UNROLL * Block::LEN;
2046    }
2047    while i + last_byte_offset + Block::LEN < haystack.len() && !result {
2048        let mask = test_chunk(i);
2049        if mask != 0 {
2050            result |= check_mask(i, mask, result);
2051        }
2052        i += Block::LEN;
2053    }
2054
2055    // Process the tail that didn't fit into LANES-sized steps.
2056    // This simply repeats the same procedure but as right-aligned chunk instead
2057    // of a left-aligned one. The last byte must be exactly flush with the string end so
2058    // we don't miss a single byte or read out of bounds.
2059    let i = haystack.len() - last_byte_offset - Block::LEN;
2060    let mask = test_chunk(i);
2061    if mask != 0 {
2062        result |= check_mask(i, mask, result);
2063    }
2064
2065    Some(result)
2066}
2067
2068/// Compares short slices for equality.
2069///
2070/// It avoids a call to libc's memcmp which is faster on long slices
2071/// due to SIMD optimizations but it incurs a function call overhead.
2072///
2073/// # Safety
2074///
2075/// Both slices must have the same length.
2076#[cfg(any(
2077    all(target_arch = "x86_64", target_feature = "sse2"),
2078    all(target_arch = "loongarch64", target_feature = "lsx"),
2079    all(target_arch = "aarch64", target_feature = "neon")
2080))]
2081#[inline]
2082unsafe fn small_slice_eq(x: &[u8], y: &[u8]) -> bool {
2083    debug_assert_eq!(x.len(), y.len());
2084    // This function is adapted from
2085    // https://github.com/BurntSushi/memchr/blob/8037d11b4357b0f07be2bb66dc2659d9cf28ad32/src/memmem/util.rs#L32
2086
2087    // If we don't have enough bytes to do 4-byte at a time loads, then
2088    // fall back to the naive slow version.
2089    //
2090    // Potential alternative: We could do a copy_nonoverlapping combined with a mask instead
2091    // of a loop. Benchmark it.
2092    if x.len() < 4 {
2093        for (&b1, &b2) in x.iter().zip(y) {
2094            if b1 != b2 {
2095                return false;
2096            }
2097        }
2098        return true;
2099    }
2100    // When we have 4 or more bytes to compare, then proceed in chunks of 4 at
2101    // a time using unaligned loads.
2102    //
2103    // Also, why do 4 byte loads instead of, say, 8 byte loads? The reason is
2104    // that this particular version of memcmp is likely to be called with tiny
2105    // needles. That means that if we do 8 byte loads, then a higher proportion
2106    // of memcmp calls will use the slower variant above. With that said, this
2107    // is a hypothesis and is only loosely supported by benchmarks. There's
2108    // likely some improvement that could be made here. The main thing here
2109    // though is to optimize for latency, not throughput.
2110
2111    // SAFETY: Via the conditional above, we know that both `px` and `py`
2112    // have the same length, so `px < pxend` implies that `py < pyend`.
2113    // Thus, dereferencing both `px` and `py` in the loop below is safe.
2114    //
2115    // Moreover, we set `pxend` and `pyend` to be 4 bytes before the actual
2116    // end of `px` and `py`. Thus, the final dereference outside of the
2117    // loop is guaranteed to be valid. (The final comparison will overlap with
2118    // the last comparison done in the loop for lengths that aren't multiples
2119    // of four.)
2120    //
2121    // Finally, we needn't worry about alignment here, since we do unaligned
2122    // loads.
2123    unsafe {
2124        let (mut px, mut py) = (x.as_ptr(), y.as_ptr());
2125        let (pxend, pyend) = (px.add(x.len() - 4), py.add(y.len() - 4));
2126        while px < pxend {
2127            let vx = (px as *const u32).read_unaligned();
2128            let vy = (py as *const u32).read_unaligned();
2129            if vx != vy {
2130                return false;
2131            }
2132            px = px.add(4);
2133            py = py.add(4);
2134        }
2135        let vx = (pxend as *const u32).read_unaligned();
2136        let vy = (pyend as *const u32).read_unaligned();
2137        vx == vy
2138    }
2139}
2140
2141/// Ferrocene addition: Hidden module to test crate-internal functionality
2142#[doc(hidden)]
2143#[unstable(feature = "ferrocene_test", issue = "none")]
2144pub mod ferrocene_test;