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