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