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#[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#[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 all(target_arch = "aarch64", target_feature = "neon")
1061 ))]
1062 if self.len() <= 32 {
1063 if let Some(result) = simd_contains(self, haystack) {
1064 return result;
1065 }
1066 }
1067
1068 self.into_searcher(haystack).next_match().is_some()
1069 }
1070 _ => self == haystack,
1071 }
1072 }
1073
1074 /// Removes the pattern from the front of haystack, if it matches.
1075 #[inline]
1076 #[cfg(not(feature = "ferrocene_subset"))]
1077 fn strip_prefix_of(self, haystack: &str) -> Option<&str> {
1078 if self.is_prefix_of(haystack) {
1079 // SAFETY: prefix was just verified to exist.
1080 unsafe { Some(haystack.get_unchecked(self.as_bytes().len()..)) }
1081 } else {
1082 None
1083 }
1084 }
1085
1086 /// Checks whether the pattern matches at the back of the haystack.
1087 #[inline]
1088 fn is_suffix_of<'a>(self, haystack: &'a str) -> bool
1089 where
1090 Self::Searcher<'a>: ReverseSearcher<'a>,
1091 {
1092 haystack.as_bytes().ends_with(self.as_bytes())
1093 }
1094
1095 /// Removes the pattern from the back of haystack, if it matches.
1096 #[inline]
1097 #[cfg(not(feature = "ferrocene_subset"))]
1098 fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str>
1099 where
1100 Self::Searcher<'a>: ReverseSearcher<'a>,
1101 {
1102 if self.is_suffix_of(haystack) {
1103 let i = haystack.len() - self.as_bytes().len();
1104 // SAFETY: suffix was just verified to exist.
1105 unsafe { Some(haystack.get_unchecked(..i)) }
1106 } else {
1107 None
1108 }
1109 }
1110
1111 #[inline]
1112 #[cfg(not(feature = "ferrocene_subset"))]
1113 fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>> {
1114 Some(Utf8Pattern::StringPattern(self.as_bytes()))
1115 }
1116}
1117
1118/////////////////////////////////////////////////////////////////////////////
1119// Two Way substring searcher
1120/////////////////////////////////////////////////////////////////////////////
1121
1122#[derive(Clone, Debug)]
1123/// Associated type for `<&str as Pattern>::Searcher<'a>`.
1124pub struct StrSearcher<'a, 'b> {
1125 haystack: &'a str,
1126 needle: &'b str,
1127
1128 searcher: StrSearcherImpl,
1129}
1130
1131#[derive(Clone, Debug)]
1132enum StrSearcherImpl {
1133 Empty(EmptyNeedle),
1134 TwoWay(TwoWaySearcher),
1135}
1136#[derive(Clone, Debug)]
1137struct EmptyNeedle {
1138 position: usize,
1139 end: usize,
1140 is_match_fw: bool,
1141 is_match_bw: bool,
1142 // Needed in case of an empty haystack, see #85462
1143 is_finished: bool,
1144}
1145
1146impl<'a, 'b> StrSearcher<'a, 'b> {
1147 fn new(haystack: &'a str, needle: &'b str) -> StrSearcher<'a, 'b> {
1148 if needle.is_empty() {
1149 StrSearcher {
1150 haystack,
1151 needle,
1152 searcher: StrSearcherImpl::Empty(EmptyNeedle {
1153 position: 0,
1154 end: haystack.len(),
1155 is_match_fw: true,
1156 is_match_bw: true,
1157 is_finished: false,
1158 }),
1159 }
1160 } else {
1161 StrSearcher {
1162 haystack,
1163 needle,
1164 searcher: StrSearcherImpl::TwoWay(TwoWaySearcher::new(
1165 needle.as_bytes(),
1166 haystack.len(),
1167 )),
1168 }
1169 }
1170 }
1171}
1172
1173unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> {
1174 #[inline]
1175 fn haystack(&self) -> &'a str {
1176 self.haystack
1177 }
1178
1179 #[inline]
1180 fn next(&mut self) -> SearchStep {
1181 match self.searcher {
1182 StrSearcherImpl::Empty(ref mut searcher) => {
1183 if searcher.is_finished {
1184 return SearchStep::Done;
1185 }
1186 // empty needle rejects every char and matches every empty string between them
1187 let is_match = searcher.is_match_fw;
1188 searcher.is_match_fw = !searcher.is_match_fw;
1189 let pos = searcher.position;
1190 match self.haystack[pos..].chars().next() {
1191 _ if is_match => SearchStep::Match(pos, pos),
1192 None => {
1193 searcher.is_finished = true;
1194 SearchStep::Done
1195 }
1196 Some(ch) => {
1197 searcher.position += ch.len_utf8();
1198 SearchStep::Reject(pos, searcher.position)
1199 }
1200 }
1201 }
1202 StrSearcherImpl::TwoWay(ref mut searcher) => {
1203 // TwoWaySearcher produces valid *Match* indices that split at char boundaries
1204 // as long as it does correct matching and that haystack and needle are
1205 // valid UTF-8
1206 // *Rejects* from the algorithm can fall on any indices, but we will walk them
1207 // manually to the next character boundary, so that they are utf-8 safe.
1208 if searcher.position == self.haystack.len() {
1209 return SearchStep::Done;
1210 }
1211 let is_long = searcher.memory == usize::MAX;
1212 match searcher.next::<RejectAndMatch>(
1213 self.haystack.as_bytes(),
1214 self.needle.as_bytes(),
1215 is_long,
1216 ) {
1217 SearchStep::Reject(a, mut b) => {
1218 // skip to next char boundary
1219 while !self.haystack.is_char_boundary(b) {
1220 b += 1;
1221 }
1222 searcher.position = cmp::max(b, searcher.position);
1223 SearchStep::Reject(a, b)
1224 }
1225 otherwise => otherwise,
1226 }
1227 }
1228 }
1229 }
1230
1231 #[inline]
1232 fn next_match(&mut self) -> Option<(usize, usize)> {
1233 match self.searcher {
1234 StrSearcherImpl::Empty(..) => loop {
1235 match self.next() {
1236 SearchStep::Match(a, b) => return Some((a, b)),
1237 SearchStep::Done => return None,
1238 SearchStep::Reject(..) => {}
1239 }
1240 },
1241 StrSearcherImpl::TwoWay(ref mut searcher) => {
1242 let is_long = searcher.memory == usize::MAX;
1243 // write out `true` and `false` cases to encourage the compiler
1244 // to specialize the two cases separately.
1245 if is_long {
1246 searcher.next::<MatchOnly>(
1247 self.haystack.as_bytes(),
1248 self.needle.as_bytes(),
1249 true,
1250 )
1251 } else {
1252 searcher.next::<MatchOnly>(
1253 self.haystack.as_bytes(),
1254 self.needle.as_bytes(),
1255 false,
1256 )
1257 }
1258 }
1259 }
1260 }
1261}
1262
1263unsafe impl<'a, 'b> ReverseSearcher<'a> for StrSearcher<'a, 'b> {
1264 #[inline]
1265 fn next_back(&mut self) -> SearchStep {
1266 match self.searcher {
1267 StrSearcherImpl::Empty(ref mut searcher) => {
1268 if searcher.is_finished {
1269 return SearchStep::Done;
1270 }
1271 let is_match = searcher.is_match_bw;
1272 searcher.is_match_bw = !searcher.is_match_bw;
1273 let end = searcher.end;
1274 match self.haystack[..end].chars().next_back() {
1275 _ if is_match => SearchStep::Match(end, end),
1276 None => {
1277 searcher.is_finished = true;
1278 SearchStep::Done
1279 }
1280 Some(ch) => {
1281 searcher.end -= ch.len_utf8();
1282 SearchStep::Reject(searcher.end, end)
1283 }
1284 }
1285 }
1286 StrSearcherImpl::TwoWay(ref mut searcher) => {
1287 if searcher.end == 0 {
1288 return SearchStep::Done;
1289 }
1290 let is_long = searcher.memory == usize::MAX;
1291 match searcher.next_back::<RejectAndMatch>(
1292 self.haystack.as_bytes(),
1293 self.needle.as_bytes(),
1294 is_long,
1295 ) {
1296 SearchStep::Reject(mut a, b) => {
1297 // skip to next char boundary
1298 while !self.haystack.is_char_boundary(a) {
1299 a -= 1;
1300 }
1301 searcher.end = cmp::min(a, searcher.end);
1302 SearchStep::Reject(a, b)
1303 }
1304 otherwise => otherwise,
1305 }
1306 }
1307 }
1308 }
1309
1310 #[inline]
1311 #[cfg(not(feature = "ferrocene_subset"))]
1312 fn next_match_back(&mut self) -> Option<(usize, usize)> {
1313 match self.searcher {
1314 StrSearcherImpl::Empty(..) => loop {
1315 match self.next_back() {
1316 SearchStep::Match(a, b) => return Some((a, b)),
1317 SearchStep::Done => return None,
1318 SearchStep::Reject(..) => {}
1319 }
1320 },
1321 StrSearcherImpl::TwoWay(ref mut searcher) => {
1322 let is_long = searcher.memory == usize::MAX;
1323 // write out `true` and `false`, like `next_match`
1324 if is_long {
1325 searcher.next_back::<MatchOnly>(
1326 self.haystack.as_bytes(),
1327 self.needle.as_bytes(),
1328 true,
1329 )
1330 } else {
1331 searcher.next_back::<MatchOnly>(
1332 self.haystack.as_bytes(),
1333 self.needle.as_bytes(),
1334 false,
1335 )
1336 }
1337 }
1338 }
1339 }
1340}
1341
1342/// The internal state of the two-way substring search algorithm.
1343#[derive(Clone, Debug)]
1344struct TwoWaySearcher {
1345 // constants
1346 /// critical factorization index
1347 crit_pos: usize,
1348 /// critical factorization index for reversed needle
1349 crit_pos_back: usize,
1350 period: usize,
1351 /// `byteset` is an extension (not part of the two way algorithm);
1352 /// it's a 64-bit "fingerprint" where each set bit `j` corresponds
1353 /// to a (byte & 63) == j present in the needle.
1354 byteset: u64,
1355
1356 // variables
1357 position: usize,
1358 end: usize,
1359 /// index into needle before which we have already matched
1360 memory: usize,
1361 /// index into needle after which we have already matched
1362 memory_back: usize,
1363}
1364
1365/*
1366 This is the Two-Way search algorithm, which was introduced in the paper:
1367 Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.
1368
1369 Here's some background information.
1370
1371 A *word* is a string of symbols. The *length* of a word should be a familiar
1372 notion, and here we denote it for any word x by |x|.
1373 (We also allow for the possibility of the *empty word*, a word of length zero).
1374
1375 If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
1376 *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
1377 For example, both 1 and 2 are periods for the string "aa". As another example,
1378 the only period of the string "abcd" is 4.
1379
1380 We denote by period(x) the *smallest* period of x (provided that x is non-empty).
1381 This is always well-defined since every non-empty word x has at least one period,
1382 |x|. We sometimes call this *the period* of x.
1383
1384 If u, v and x are words such that x = uv, where uv is the concatenation of u and
1385 v, then we say that (u, v) is a *factorization* of x.
1386
1387 Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
1388 that both of the following hold
1389
1390 - either w is a suffix of u or u is a suffix of w
1391 - either w is a prefix of v or v is a prefix of w
1392
1393 then w is said to be a *repetition* for the factorization (u, v).
1394
1395 Just to unpack this, there are four possibilities here. Let w = "abc". Then we
1396 might have:
1397
1398 - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
1399 - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
1400 - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
1401 - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")
1402
1403 Note that the word vu is a repetition for any factorization (u,v) of x = uv,
1404 so every factorization has at least one repetition.
1405
1406 If x is a string and (u, v) is a factorization for x, then a *local period* for
1407 (u, v) is an integer r such that there is some word w such that |w| = r and w is
1408 a repetition for (u, v).
1409
1410 We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
1411 call this *the local period* of (u, v). Provided that x = uv is non-empty, this
1412 is well-defined (because each non-empty word has at least one factorization, as
1413 noted above).
1414
1415 It can be proven that the following is an equivalent definition of a local period
1416 for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
1417 all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
1418 defined. (i.e., i > 0 and i + r < |x|).
1419
1420 Using the above reformulation, it is easy to prove that
1421
1422 1 <= local_period(u, v) <= period(uv)
1423
1424 A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
1425 *critical factorization*.
1426
1427 The algorithm hinges on the following theorem, which is stated without proof:
1428
1429 **Critical Factorization Theorem** Any word x has at least one critical
1430 factorization (u, v) such that |u| < period(x).
1431
1432 The purpose of maximal_suffix is to find such a critical factorization.
1433
1434 If the period is short, compute another factorization x = u' v' to use
1435 for reverse search, chosen instead so that |v'| < period(x).
1436
1437*/
1438impl TwoWaySearcher {
1439 fn new(needle: &[u8], end: usize) -> TwoWaySearcher {
1440 let (crit_pos_false, period_false) = TwoWaySearcher::maximal_suffix(needle, false);
1441 let (crit_pos_true, period_true) = TwoWaySearcher::maximal_suffix(needle, true);
1442
1443 let (crit_pos, period) = if crit_pos_false > crit_pos_true {
1444 (crit_pos_false, period_false)
1445 } else {
1446 (crit_pos_true, period_true)
1447 };
1448
1449 // A particularly readable explanation of what's going on here can be found
1450 // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
1451 // see the code for "Algorithm CP" on p. 323.
1452 //
1453 // What's going on is we have some critical factorization (u, v) of the
1454 // needle, and we want to determine whether u is a suffix of
1455 // &v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
1456 // "Algorithm CP2", which is optimized for when the period of the needle
1457 // is large.
1458 if needle[..crit_pos] == needle[period..period + crit_pos] {
1459 // short period case -- the period is exact
1460 // compute a separate critical factorization for the reversed needle
1461 // x = u' v' where |v'| < period(x).
1462 //
1463 // This is sped up by the period being known already.
1464 // Note that a case like x = "acba" may be factored exactly forwards
1465 // (crit_pos = 1, period = 3) while being factored with approximate
1466 // period in reverse (crit_pos = 2, period = 2). We use the given
1467 // reverse factorization but keep the exact period.
1468 let crit_pos_back = needle.len()
1469 - cmp::max(
1470 TwoWaySearcher::reverse_maximal_suffix(needle, period, false),
1471 TwoWaySearcher::reverse_maximal_suffix(needle, period, true),
1472 );
1473
1474 TwoWaySearcher {
1475 crit_pos,
1476 crit_pos_back,
1477 period,
1478 byteset: Self::byteset_create(&needle[..period]),
1479
1480 position: 0,
1481 end,
1482 memory: 0,
1483 memory_back: needle.len(),
1484 }
1485 } else {
1486 // long period case -- we have an approximation to the actual period,
1487 // and don't use memorization.
1488 //
1489 // Approximate the period by lower bound max(|u|, |v|) + 1.
1490 // The critical factorization is efficient to use for both forward and
1491 // reverse search.
1492
1493 TwoWaySearcher {
1494 crit_pos,
1495 crit_pos_back: crit_pos,
1496 period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
1497 byteset: Self::byteset_create(needle),
1498
1499 position: 0,
1500 end,
1501 memory: usize::MAX, // Dummy value to signify that the period is long
1502 memory_back: usize::MAX,
1503 }
1504 }
1505 }
1506
1507 #[inline]
1508 fn byteset_create(bytes: &[u8]) -> u64 {
1509 bytes.iter().fold(0, |a, &b| (1 << (b & 0x3f)) | a)
1510 }
1511
1512 #[inline]
1513 fn byteset_contains(&self, byte: u8) -> bool {
1514 (self.byteset >> ((byte & 0x3f) as usize)) & 1 != 0
1515 }
1516
1517 // One of the main ideas of Two-Way is that we factorize the needle into
1518 // two halves, (u, v), and begin trying to find v in the haystack by scanning
1519 // left to right. If v matches, we try to match u by scanning right to left.
1520 // How far we can jump when we encounter a mismatch is all based on the fact
1521 // that (u, v) is a critical factorization for the needle.
1522 #[inline]
1523 fn next<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> S::Output
1524 where
1525 S: TwoWayStrategy,
1526 {
1527 // `next()` uses `self.position` as its cursor
1528 let old_pos = self.position;
1529 let needle_last = needle.len() - 1;
1530 'search: loop {
1531 // Check that we have room to search in
1532 // position + needle_last can not overflow if we assume slices
1533 // are bounded by isize's range.
1534 let tail_byte = match haystack.get(self.position + needle_last) {
1535 Some(&b) => b,
1536 None => {
1537 self.position = haystack.len();
1538 return S::rejecting(old_pos, self.position);
1539 }
1540 };
1541
1542 if S::use_early_reject() && old_pos != self.position {
1543 return S::rejecting(old_pos, self.position);
1544 }
1545
1546 // Quickly skip by large portions unrelated to our substring
1547 if !self.byteset_contains(tail_byte) {
1548 self.position += needle.len();
1549 if !long_period {
1550 self.memory = 0;
1551 }
1552 continue 'search;
1553 }
1554
1555 // See if the right part of the needle matches
1556 let start =
1557 if long_period { self.crit_pos } else { cmp::max(self.crit_pos, self.memory) };
1558 for i in start..needle.len() {
1559 if needle[i] != haystack[self.position + i] {
1560 self.position += i - self.crit_pos + 1;
1561 if !long_period {
1562 self.memory = 0;
1563 }
1564 continue 'search;
1565 }
1566 }
1567
1568 // See if the left part of the needle matches
1569 let start = if long_period { 0 } else { self.memory };
1570 for i in (start..self.crit_pos).rev() {
1571 if needle[i] != haystack[self.position + i] {
1572 self.position += self.period;
1573 if !long_period {
1574 self.memory = needle.len() - self.period;
1575 }
1576 continue 'search;
1577 }
1578 }
1579
1580 // We have found a match!
1581 let match_pos = self.position;
1582
1583 // Note: add self.period instead of needle.len() to have overlapping matches
1584 self.position += needle.len();
1585 if !long_period {
1586 self.memory = 0; // set to needle.len() - self.period for overlapping matches
1587 }
1588
1589 return S::matching(match_pos, match_pos + needle.len());
1590 }
1591 }
1592
1593 // Follows the ideas in `next()`.
1594 //
1595 // The definitions are symmetrical, with period(x) = period(reverse(x))
1596 // and local_period(u, v) = local_period(reverse(v), reverse(u)), so if (u, v)
1597 // is a critical factorization, so is (reverse(v), reverse(u)).
1598 //
1599 // For the reverse case we have computed a critical factorization x = u' v'
1600 // (field `crit_pos_back`). We need |u| < period(x) for the forward case and
1601 // thus |v'| < period(x) for the reverse.
1602 //
1603 // To search in reverse through the haystack, we search forward through
1604 // a reversed haystack with a reversed needle, matching first u' and then v'.
1605 #[inline]
1606 fn next_back<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> S::Output
1607 where
1608 S: TwoWayStrategy,
1609 {
1610 // `next_back()` uses `self.end` as its cursor -- so that `next()` and `next_back()`
1611 // are independent.
1612 let old_end = self.end;
1613 'search: loop {
1614 // Check that we have room to search in
1615 // end - needle.len() will wrap around when there is no more room,
1616 // but due to slice length limits it can never wrap all the way back
1617 // into the length of haystack.
1618 let front_byte = match haystack.get(self.end.wrapping_sub(needle.len())) {
1619 Some(&b) => b,
1620 None => {
1621 self.end = 0;
1622 return S::rejecting(0, old_end);
1623 }
1624 };
1625
1626 if S::use_early_reject() && old_end != self.end {
1627 return S::rejecting(self.end, old_end);
1628 }
1629
1630 // Quickly skip by large portions unrelated to our substring
1631 if !self.byteset_contains(front_byte) {
1632 self.end -= needle.len();
1633 if !long_period {
1634 self.memory_back = needle.len();
1635 }
1636 continue 'search;
1637 }
1638
1639 // See if the left part of the needle matches
1640 let crit = if long_period {
1641 self.crit_pos_back
1642 } else {
1643 cmp::min(self.crit_pos_back, self.memory_back)
1644 };
1645 for i in (0..crit).rev() {
1646 if needle[i] != haystack[self.end - needle.len() + i] {
1647 self.end -= self.crit_pos_back - i;
1648 if !long_period {
1649 self.memory_back = needle.len();
1650 }
1651 continue 'search;
1652 }
1653 }
1654
1655 // See if the right part of the needle matches
1656 let needle_end = if long_period { needle.len() } else { self.memory_back };
1657 for i in self.crit_pos_back..needle_end {
1658 if needle[i] != haystack[self.end - needle.len() + i] {
1659 self.end -= self.period;
1660 if !long_period {
1661 self.memory_back = self.period;
1662 }
1663 continue 'search;
1664 }
1665 }
1666
1667 // We have found a match!
1668 let match_pos = self.end - needle.len();
1669 // Note: sub self.period instead of needle.len() to have overlapping matches
1670 self.end -= needle.len();
1671 if !long_period {
1672 self.memory_back = needle.len();
1673 }
1674
1675 return S::matching(match_pos, match_pos + needle.len());
1676 }
1677 }
1678
1679 // Compute the maximal suffix of `arr`.
1680 //
1681 // The maximal suffix is a possible critical factorization (u, v) of `arr`.
1682 //
1683 // Returns (`i`, `p`) where `i` is the starting index of v and `p` is the
1684 // period of v.
1685 //
1686 // `order_greater` determines if lexical order is `<` or `>`. Both
1687 // orders must be computed -- the ordering with the largest `i` gives
1688 // a critical factorization.
1689 //
1690 // For long period cases, the resulting period is not exact (it is too short).
1691 #[inline]
1692 fn maximal_suffix(arr: &[u8], order_greater: bool) -> (usize, usize) {
1693 let mut left = 0; // Corresponds to i in the paper
1694 let mut right = 1; // Corresponds to j in the paper
1695 let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1696 // to match 0-based indexing.
1697 let mut period = 1; // Corresponds to p in the paper
1698
1699 while let Some(&a) = arr.get(right + offset) {
1700 // `left` will be inbounds when `right` is.
1701 let b = arr[left + offset];
1702 if (a < b && !order_greater) || (a > b && order_greater) {
1703 // Suffix is smaller, period is entire prefix so far.
1704 right += offset + 1;
1705 offset = 0;
1706 period = right - left;
1707 } else if a == b {
1708 // Advance through repetition of the current period.
1709 if offset + 1 == period {
1710 right += offset + 1;
1711 offset = 0;
1712 } else {
1713 offset += 1;
1714 }
1715 } else {
1716 // Suffix is larger, start over from current location.
1717 left = right;
1718 right += 1;
1719 offset = 0;
1720 period = 1;
1721 }
1722 }
1723 (left, period)
1724 }
1725
1726 // Compute the maximal suffix of the reverse of `arr`.
1727 //
1728 // The maximal suffix is a possible critical factorization (u', v') of `arr`.
1729 //
1730 // Returns `i` where `i` is the starting index of v', from the back;
1731 // returns immediately when a period of `known_period` is reached.
1732 //
1733 // `order_greater` determines if lexical order is `<` or `>`. Both
1734 // orders must be computed -- the ordering with the largest `i` gives
1735 // a critical factorization.
1736 //
1737 // For long period cases, the resulting period is not exact (it is too short).
1738 fn reverse_maximal_suffix(arr: &[u8], known_period: usize, order_greater: bool) -> usize {
1739 let mut left = 0; // Corresponds to i in the paper
1740 let mut right = 1; // Corresponds to j in the paper
1741 let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1742 // to match 0-based indexing.
1743 let mut period = 1; // Corresponds to p in the paper
1744 let n = arr.len();
1745
1746 while right + offset < n {
1747 let a = arr[n - (1 + right + offset)];
1748 let b = arr[n - (1 + left + offset)];
1749 if (a < b && !order_greater) || (a > b && order_greater) {
1750 // Suffix is smaller, period is entire prefix so far.
1751 right += offset + 1;
1752 offset = 0;
1753 period = right - left;
1754 } else if a == b {
1755 // Advance through repetition of the current period.
1756 if offset + 1 == period {
1757 right += offset + 1;
1758 offset = 0;
1759 } else {
1760 offset += 1;
1761 }
1762 } else {
1763 // Suffix is larger, start over from current location.
1764 left = right;
1765 right += 1;
1766 offset = 0;
1767 period = 1;
1768 }
1769 if period == known_period {
1770 break;
1771 }
1772 }
1773 debug_assert!(period <= known_period);
1774 left
1775 }
1776}
1777
1778// TwoWayStrategy allows the algorithm to either skip non-matches as quickly
1779// as possible, or to work in a mode where it emits Rejects relatively quickly.
1780trait TwoWayStrategy {
1781 type Output;
1782 fn use_early_reject() -> bool;
1783 fn rejecting(a: usize, b: usize) -> Self::Output;
1784 fn matching(a: usize, b: usize) -> Self::Output;
1785}
1786
1787/// Skip to match intervals as quickly as possible
1788enum MatchOnly {}
1789
1790impl TwoWayStrategy for MatchOnly {
1791 type Output = Option<(usize, usize)>;
1792
1793 #[inline]
1794 fn use_early_reject() -> bool {
1795 false
1796 }
1797 #[inline]
1798 fn rejecting(_a: usize, _b: usize) -> Self::Output {
1799 None
1800 }
1801 #[inline]
1802 fn matching(a: usize, b: usize) -> Self::Output {
1803 Some((a, b))
1804 }
1805}
1806
1807/// Emit Rejects regularly
1808enum RejectAndMatch {}
1809
1810impl TwoWayStrategy for RejectAndMatch {
1811 type Output = SearchStep;
1812
1813 #[inline]
1814 fn use_early_reject() -> bool {
1815 true
1816 }
1817 #[inline]
1818 fn rejecting(a: usize, b: usize) -> Self::Output {
1819 SearchStep::Reject(a, b)
1820 }
1821 #[inline]
1822 fn matching(a: usize, b: usize) -> Self::Output {
1823 SearchStep::Match(a, b)
1824 }
1825}
1826
1827/// SIMD search for short needles based on
1828/// Wojciech Muła's "SIMD-friendly algorithms for substring searching"[0]
1829///
1830/// It skips ahead by the vector width on each iteration (rather than the needle length as two-way
1831/// does) by probing the first and last byte of the needle for the whole vector width
1832/// and only doing full needle comparisons when the vectorized probe indicated potential matches.
1833///
1834/// Since the x86_64 baseline only offers SSE2 we only use u8x16 here.
1835/// If we ever ship std with for x86-64-v3 or adapt this for other platforms then wider vectors
1836/// should be evaluated.
1837///
1838/// Similarly, on LoongArch the 128-bit LSX vector extension is the baseline,
1839/// so we also use `u8x16` there. Wider vector widths may be considered
1840/// for future LoongArch extensions (e.g., LASX).
1841///
1842/// For haystacks smaller than vector-size + needle length it falls back to
1843/// a naive O(n*m) search so this implementation should not be called on larger needles.
1844///
1845/// [0]: http://0x80.pl/articles/simd-strfind.html#sse-avx2
1846#[cfg(any(
1847 all(target_arch = "x86_64", target_feature = "sse2"),
1848 all(target_arch = "loongarch64", target_feature = "lsx"),
1849 all(target_arch = "aarch64", target_feature = "neon")
1850))]
1851#[inline]
1852#[cfg(not(feature = "ferrocene_subset"))]
1853fn simd_contains(needle: &str, haystack: &str) -> Option<bool> {
1854 let needle = needle.as_bytes();
1855 let haystack = haystack.as_bytes();
1856
1857 debug_assert!(needle.len() > 1);
1858
1859 use crate::ops::BitAnd;
1860 use crate::simd::cmp::SimdPartialEq;
1861 use crate::simd::{mask8x16 as Mask, u8x16 as Block};
1862
1863 let first_probe = needle[0];
1864 let last_byte_offset = needle.len() - 1;
1865
1866 // the offset used for the 2nd vector
1867 let second_probe_offset = if needle.len() == 2 {
1868 // never bail out on len=2 needles because the probes will fully cover them and have
1869 // no degenerate cases.
1870 1
1871 } else {
1872 // try a few bytes in case first and last byte of the needle are the same
1873 let Some(second_probe_offset) =
1874 (needle.len().saturating_sub(4)..needle.len()).rfind(|&idx| needle[idx] != first_probe)
1875 else {
1876 // fall back to other search methods if we can't find any different bytes
1877 // since we could otherwise hit some degenerate cases
1878 return None;
1879 };
1880 second_probe_offset
1881 };
1882
1883 // do a naive search if the haystack is too small to fit
1884 if haystack.len() < Block::LEN + last_byte_offset {
1885 return Some(haystack.windows(needle.len()).any(|c| c == needle));
1886 }
1887
1888 let first_probe: Block = Block::splat(first_probe);
1889 let second_probe: Block = Block::splat(needle[second_probe_offset]);
1890 // first byte are already checked by the outer loop. to verify a match only the
1891 // remainder has to be compared.
1892 let trimmed_needle = &needle[1..];
1893
1894 // this #[cold] is load-bearing, benchmark before removing it...
1895 let check_mask = #[cold]
1896 |idx, mask: u16, skip: bool| -> bool {
1897 if skip {
1898 return false;
1899 }
1900
1901 // and so is this. optimizations are weird.
1902 let mut mask = mask;
1903
1904 while mask != 0 {
1905 let trailing = mask.trailing_zeros();
1906 let offset = idx + trailing as usize + 1;
1907 // SAFETY: mask is between 0 and 15 trailing zeroes, we skip one additional byte that was already compared
1908 // and then take trimmed_needle.len() bytes. This is within the bounds defined by the outer loop
1909 unsafe {
1910 let sub = haystack.get_unchecked(offset..).get_unchecked(..trimmed_needle.len());
1911 if small_slice_eq(sub, trimmed_needle) {
1912 return true;
1913 }
1914 }
1915 mask &= !(1 << trailing);
1916 }
1917 false
1918 };
1919
1920 let test_chunk = |idx| -> u16 {
1921 // SAFETY: this requires at least LANES bytes being readable at idx
1922 // that is ensured by the loop ranges (see comments below)
1923 let a: Block = unsafe { haystack.as_ptr().add(idx).cast::<Block>().read_unaligned() };
1924 // SAFETY: this requires LANES + block_offset bytes being readable at idx
1925 let b: Block = unsafe {
1926 haystack.as_ptr().add(idx).add(second_probe_offset).cast::<Block>().read_unaligned()
1927 };
1928 let eq_first: Mask = a.simd_eq(first_probe);
1929 let eq_last: Mask = b.simd_eq(second_probe);
1930 let both = eq_first.bitand(eq_last);
1931 let mask = both.to_bitmask() as u16;
1932
1933 mask
1934 };
1935
1936 let mut i = 0;
1937 let mut result = false;
1938 // The loop condition must ensure that there's enough headroom to read LANE bytes,
1939 // and not only at the current index but also at the index shifted by block_offset
1940 const UNROLL: usize = 4;
1941 while i + last_byte_offset + UNROLL * Block::LEN < haystack.len() && !result {
1942 let mut masks = [0u16; UNROLL];
1943 for j in 0..UNROLL {
1944 masks[j] = test_chunk(i + j * Block::LEN);
1945 }
1946 for j in 0..UNROLL {
1947 let mask = masks[j];
1948 if mask != 0 {
1949 result |= check_mask(i + j * Block::LEN, mask, result);
1950 }
1951 }
1952 i += UNROLL * Block::LEN;
1953 }
1954 while i + last_byte_offset + Block::LEN < haystack.len() && !result {
1955 let mask = test_chunk(i);
1956 if mask != 0 {
1957 result |= check_mask(i, mask, result);
1958 }
1959 i += Block::LEN;
1960 }
1961
1962 // Process the tail that didn't fit into LANES-sized steps.
1963 // This simply repeats the same procedure but as right-aligned chunk instead
1964 // of a left-aligned one. The last byte must be exactly flush with the string end so
1965 // we don't miss a single byte or read out of bounds.
1966 let i = haystack.len() - last_byte_offset - Block::LEN;
1967 let mask = test_chunk(i);
1968 if mask != 0 {
1969 result |= check_mask(i, mask, result);
1970 }
1971
1972 Some(result)
1973}
1974
1975/// Compares short slices for equality.
1976///
1977/// It avoids a call to libc's memcmp which is faster on long slices
1978/// due to SIMD optimizations but it incurs a function call overhead.
1979///
1980/// # Safety
1981///
1982/// Both slices must have the same length.
1983#[cfg(any(
1984 all(target_arch = "x86_64", target_feature = "sse2"),
1985 all(target_arch = "loongarch64", target_feature = "lsx"),
1986 all(target_arch = "aarch64", target_feature = "neon")
1987))]
1988#[inline]
1989#[cfg(not(feature = "ferrocene_subset"))]
1990unsafe fn small_slice_eq(x: &[u8], y: &[u8]) -> bool {
1991 debug_assert_eq!(x.len(), y.len());
1992 // This function is adapted from
1993 // https://github.com/BurntSushi/memchr/blob/8037d11b4357b0f07be2bb66dc2659d9cf28ad32/src/memmem/util.rs#L32
1994
1995 // If we don't have enough bytes to do 4-byte at a time loads, then
1996 // fall back to the naive slow version.
1997 //
1998 // Potential alternative: We could do a copy_nonoverlapping combined with a mask instead
1999 // of a loop. Benchmark it.
2000 if x.len() < 4 {
2001 for (&b1, &b2) in x.iter().zip(y) {
2002 if b1 != b2 {
2003 return false;
2004 }
2005 }
2006 return true;
2007 }
2008 // When we have 4 or more bytes to compare, then proceed in chunks of 4 at
2009 // a time using unaligned loads.
2010 //
2011 // Also, why do 4 byte loads instead of, say, 8 byte loads? The reason is
2012 // that this particular version of memcmp is likely to be called with tiny
2013 // needles. That means that if we do 8 byte loads, then a higher proportion
2014 // of memcmp calls will use the slower variant above. With that said, this
2015 // is a hypothesis and is only loosely supported by benchmarks. There's
2016 // likely some improvement that could be made here. The main thing here
2017 // though is to optimize for latency, not throughput.
2018
2019 // SAFETY: Via the conditional above, we know that both `px` and `py`
2020 // have the same length, so `px < pxend` implies that `py < pyend`.
2021 // Thus, dereferencing both `px` and `py` in the loop below is safe.
2022 //
2023 // Moreover, we set `pxend` and `pyend` to be 4 bytes before the actual
2024 // end of `px` and `py`. Thus, the final dereference outside of the
2025 // loop is guaranteed to be valid. (The final comparison will overlap with
2026 // the last comparison done in the loop for lengths that aren't multiples
2027 // of four.)
2028 //
2029 // Finally, we needn't worry about alignment here, since we do unaligned
2030 // loads.
2031 unsafe {
2032 let (mut px, mut py) = (x.as_ptr(), y.as_ptr());
2033 let (pxend, pyend) = (px.add(x.len() - 4), py.add(y.len() - 4));
2034 while px < pxend {
2035 let vx = (px as *const u32).read_unaligned();
2036 let vy = (py as *const u32).read_unaligned();
2037 if vx != vy {
2038 return false;
2039 }
2040 px = px.add(4);
2041 py = py.add(4);
2042 }
2043 let vx = (pxend as *const u32).read_unaligned();
2044 let vy = (pyend as *const u32).read_unaligned();
2045 vx == vy
2046 }
2047}
2048
2049/// Ferrocene addition: Hidden module to test crate-internal functionality
2050#[doc(hidden)]
2051#[unstable(feature = "ferrocene_test", issue = "none")]
2052#[cfg(not(feature = "ferrocene_subset"))]
2053pub mod ferrocene_test;