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