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