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