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