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