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