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
3435#![unstable(
36 feature = "pattern",
37 reason = "API not fully fleshed out and ready to be stabilized",
38 issue = "27721"
39)]
4041use crate::cmp::Ordering;
42use crate::convert::TryIntoas _;
43use crate::slice::memchr;
44use crate::{cmp, fmt};
4546// Pattern
4748/// 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
101type Searcher<'a>: Searcher<'a>;
102103/// Constructs the associated searcher from
104 /// `self` and the `haystack` to search in.
105fn into_searcher(self, haystack: &str) -> Self::Searcher<'_>;
106107/// Checks whether the pattern matches anywhere in the haystack
108#[inline]
109fn is_contained_in(self, haystack: &str) -> bool {
110self.into_searcher(haystack).next_match().is_some()
111 }
112113/// Checks whether the pattern matches at the front of the haystack
114#[inline]
115fn is_prefix_of(self, haystack: &str) -> bool {
116#[allow(non_exhaustive_omitted_patterns)] match self.into_searcher(haystack).next()
{
SearchStep::Match(0, _) => true,
_ => false,
}matches!(self.into_searcher(haystack).next(), SearchStep::Match(0, _))117 }
118119/// Checks whether the pattern matches at the back of the haystack
120#[inline]
121fn is_suffix_of<'a>(self, haystack: &'a str) -> bool122where
123Self::Searcher<'a>: ReverseSearcher<'a>,
124 {
125#[allow(non_exhaustive_omitted_patterns)] match self.into_searcher(haystack).next_back()
{
SearchStep::Match(_, j) if haystack.len() == j => true,
_ => false,
}matches!(self.into_searcher(haystack).next_back(), SearchStep::Match(_, j) if haystack.len() == j)126 }
127128/// Removes the pattern from the front of haystack, if it matches.
129#[inline]
130fn strip_prefix_of(self, haystack: &str) -> Option<&str> {
131if let SearchStep::Match(start, len) = self.into_searcher(haystack).next() {
132if true {
{
match (&start, &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = crate::panicking::AssertKind::Eq;
crate::panicking::assert_failed(kind, &*left_val,
&*right_val,
crate::option::Option::Some(format_args!("The first search step from Searcher must include the first character")));
}
}
}
};
};debug_assert_eq!(
133 start, 0,
134"The first search step from Searcher \
135 must include the first character"
136);
137// SAFETY: `Searcher` is known to return valid indices.
138unsafe { Some(haystack.get_unchecked(len..)) }
139 } else {
140None141 }
142 }
143144/// Removes the pattern from the back of haystack, if it matches.
145#[inline]
146fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str>
147where
148Self::Searcher<'a>: ReverseSearcher<'a>,
149 {
150if let SearchStep::Match(start, end) = self.into_searcher(haystack).next_back() {
151if true {
{
match (&end, &haystack.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = crate::panicking::AssertKind::Eq;
crate::panicking::assert_failed(kind, &*left_val,
&*right_val,
crate::option::Option::Some(format_args!("The first search step from ReverseSearcher must include the last character")));
}
}
}
};
};debug_assert_eq!(
152 end,
153 haystack.len(),
154"The first search step from ReverseSearcher \
155 must include the last character"
156);
157// SAFETY: `Searcher` is known to return valid indices.
158unsafe { Some(haystack.get_unchecked(..start)) }
159 } else {
160None161 }
162 }
163164/// Returns the pattern as UTF-8 if possible.
165fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>> {
166None167 }
168}
169/// Result of calling [`Pattern::as_utf8_pattern()`].
170/// Can be used for inspecting the contents of a [`Pattern`] in cases
171/// where the underlying representation can be represented as UTF-8.
172#[derive(#[automatically_derived]
impl<'a> crate::marker::Copy for Utf8Pattern<'a> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'a> crate::clone::TrivialClone for Utf8Pattern<'a> { }
#[automatically_derived]
impl<'a> crate::clone::Clone for Utf8Pattern<'a> {
#[inline]
fn clone(&self) -> Utf8Pattern<'a> {
let _: crate::clone::AssertParamIsClone<&'a str>;
let _: crate::clone::AssertParamIsClone<char>;
*self
}
}Clone, #[automatically_derived]
impl<'a> crate::cmp::Eq for Utf8Pattern<'a> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: crate::cmp::AssertParamIsEq<&'a str>;
let _: crate::cmp::AssertParamIsEq<char>;
}
}Eq, #[automatically_derived]
impl<'a> crate::marker::StructuralPartialEq for Utf8Pattern<'a> { }
#[automatically_derived]
impl<'a> crate::cmp::PartialEq for Utf8Pattern<'a> {
#[inline]
fn eq(&self, other: &Utf8Pattern<'a>) -> bool {
let __self_discr = crate::intrinsics::discriminant_value(self);
let __arg1_discr = crate::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(Utf8Pattern::StringPattern(__self_0),
Utf8Pattern::StringPattern(__arg1_0)) =>
__self_0 == __arg1_0,
(Utf8Pattern::CharPattern(__self_0),
Utf8Pattern::CharPattern(__arg1_0)) => __self_0 == __arg1_0,
_ => unsafe { crate::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl<'a> crate::fmt::Debug for Utf8Pattern<'a> {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
match self {
Utf8Pattern::StringPattern(__self_0) =>
crate::fmt::Formatter::debug_tuple_field1_finish(f,
"StringPattern", &__self_0),
Utf8Pattern::CharPattern(__self_0) =>
crate::fmt::Formatter::debug_tuple_field1_finish(f,
"CharPattern", &__self_0),
}
}
}Debug)]
173pub enum Utf8Pattern<'a> {
174/// Type returned by String and str types.
175 /// This stores `str` rather than bytes so callers cannot describe
176 /// non-UTF-8 string patterns through this API.
177StringPattern(&'a str),
178/// Type returned by char types.
179CharPattern(char),
180}
181182// Searcher
183184/// Result of calling [`Searcher::next()`] or [`ReverseSearcher::next_back()`].
185#[derive(#[automatically_derived]
impl crate::marker::Copy for SearchStep { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl crate::clone::TrivialClone for SearchStep { }
#[automatically_derived]
impl crate::clone::Clone for SearchStep {
#[inline]
fn clone(&self) -> SearchStep {
let _: crate::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]
impl crate::cmp::Eq for SearchStep {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: crate::cmp::AssertParamIsEq<usize>;
}
}Eq, #[automatically_derived]
impl crate::marker::StructuralPartialEq for SearchStep { }
#[automatically_derived]
impl crate::cmp::PartialEq for SearchStep {
#[inline]
fn eq(&self, other: &SearchStep) -> bool {
let __self_discr = crate::intrinsics::discriminant_value(self);
let __arg1_discr = crate::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(SearchStep::Match(__self_0, __self_1),
SearchStep::Match(__arg1_0, __arg1_1)) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
(SearchStep::Reject(__self_0, __self_1),
SearchStep::Reject(__arg1_0, __arg1_1)) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl crate::fmt::Debug for SearchStep {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
match self {
SearchStep::Match(__self_0, __self_1) =>
crate::fmt::Formatter::debug_tuple_field2_finish(f, "Match",
__self_0, &__self_1),
SearchStep::Reject(__self_0, __self_1) =>
crate::fmt::Formatter::debug_tuple_field2_finish(f, "Reject",
__self_0, &__self_1),
SearchStep::Done => crate::fmt::Formatter::write_str(f, "Done"),
}
}
}Debug)]
186pub enum SearchStep {
187/// Expresses that a match of the pattern has been found at
188 /// `haystack[a..b]`.
189Match(usize, usize),
190/// Expresses that `haystack[a..b]` has been rejected as a possible match
191 /// of the pattern.
192 ///
193 /// Note that there might be more than one `Reject` between two `Match`es,
194 /// there is no requirement for them to be combined into one.
195Reject(usize, usize),
196/// Expresses that every byte of the haystack has been visited, ending
197 /// the iteration.
198Done,
199}
200201/// A searcher for a string pattern.
202///
203/// This trait provides methods for searching for non-overlapping
204/// matches of a pattern starting from the front (left) of a string.
205///
206/// It will be implemented by associated `Searcher`
207/// types of the [`Pattern`] trait.
208///
209/// The trait is marked unsafe because the indices returned by the
210/// [`next()`][Searcher::next] methods are required to lie on valid utf8
211/// boundaries in the haystack. This enables consumers of this trait to
212/// slice the haystack without additional runtime checks.
213pub unsafe trait Searcher<'a> {
214/// Getter for the underlying string to be searched in
215 ///
216 /// Will always return the same [`&str`][str].
217fn haystack(&self) -> &'a str;
218219/// Performs the next search step starting from the front.
220 ///
221 /// - Returns [`Match(a, b)`][SearchStep::Match] if `haystack[a..b]` matches
222 /// the pattern.
223 /// - Returns [`Reject(a, b)`][SearchStep::Reject] if `haystack[a..b]` can
224 /// not match the pattern, even partially.
225 /// - Returns [`Done`][SearchStep::Done] if every byte of the haystack has
226 /// been visited.
227 ///
228 /// The stream of [`Match`][SearchStep::Match] and
229 /// [`Reject`][SearchStep::Reject] values up to a [`Done`][SearchStep::Done]
230 /// will contain index ranges that are adjacent, non-overlapping,
231 /// covering the whole haystack, and laying on utf8 boundaries.
232 ///
233 /// A [`Match`][SearchStep::Match] result needs to contain the whole matched
234 /// pattern, however [`Reject`][SearchStep::Reject] results may be split up
235 /// into arbitrary many adjacent fragments. Both ranges may have zero length.
236 ///
237 /// As an example, the pattern `"aaa"` and the haystack `"cbaaaaab"`
238 /// might produce the stream
239 /// `[Reject(0, 1), Reject(1, 2), Match(2, 5), Reject(5, 8)]`
240fn next(&mut self) -> SearchStep;
241242/// Finds the next [`Match`][SearchStep::Match] result. See [`next()`][Searcher::next].
243 ///
244 /// Unlike [`next()`][Searcher::next], there is no guarantee that the returned ranges
245 /// of this and [`next_reject`][Searcher::next_reject] will overlap. This will return
246 /// `(start_match, end_match)`, where start_match is the index of where
247 /// the match begins, and end_match is the index after the end of the match.
248#[inline]
249fn next_match(&mut self) -> Option<(usize, usize)> {
250loop {
251match self.next() {
252 SearchStep::Match(a, b) => return Some((a, b)),
253 SearchStep::Done => return None,
254_ => continue,
255 }
256 }
257 }
258259/// Finds the next [`Reject`][SearchStep::Reject] result. See [`next()`][Searcher::next]
260 /// and [`next_match()`][Searcher::next_match].
261 ///
262 /// Unlike [`next()`][Searcher::next], there is no guarantee that the returned ranges
263 /// of this and [`next_match`][Searcher::next_match] will overlap.
264#[inline]
265fn next_reject(&mut self) -> Option<(usize, usize)> {
266loop {
267match self.next() {
268 SearchStep::Reject(a, b) => return Some((a, b)),
269 SearchStep::Done => return None,
270_ => continue,
271 }
272 }
273 }
274}
275276/// A reverse searcher for a string pattern.
277///
278/// This trait provides methods for searching for non-overlapping
279/// matches of a pattern starting from the back (right) of a string.
280///
281/// It will be implemented by associated [`Searcher`]
282/// types of the [`Pattern`] trait if the pattern supports searching
283/// for it from the back.
284///
285/// The index ranges returned by this trait are not required
286/// to exactly match those of the forward search in reverse.
287///
288/// For the reason why this trait is marked unsafe, see the
289/// parent trait [`Searcher`].
290pub unsafe trait ReverseSearcher<'a>: Searcher<'a> {
291/// Performs the next search step starting from the back.
292 ///
293 /// - Returns [`Match(a, b)`][SearchStep::Match] if `haystack[a..b]`
294 /// matches the pattern.
295 /// - Returns [`Reject(a, b)`][SearchStep::Reject] if `haystack[a..b]`
296 /// can not match the pattern, even partially.
297 /// - Returns [`Done`][SearchStep::Done] if every byte of the haystack
298 /// has been visited
299 ///
300 /// The stream of [`Match`][SearchStep::Match] and
301 /// [`Reject`][SearchStep::Reject] values up to a [`Done`][SearchStep::Done]
302 /// will contain index ranges that are adjacent, non-overlapping,
303 /// covering the whole haystack, and laying on utf8 boundaries.
304 ///
305 /// A [`Match`][SearchStep::Match] result needs to contain the whole matched
306 /// pattern, however [`Reject`][SearchStep::Reject] results may be split up
307 /// into arbitrary many adjacent fragments. Both ranges may have zero length.
308 ///
309 /// As an example, the pattern `"aaa"` and the haystack `"cbaaaaab"`
310 /// might produce the stream
311 /// `[Reject(7, 8), Match(4, 7), Reject(1, 4), Reject(0, 1)]`.
312fn next_back(&mut self) -> SearchStep;
313314/// Finds the next [`Match`][SearchStep::Match] result.
315 /// See [`next_back()`][ReverseSearcher::next_back].
316#[inline]
317fn next_match_back(&mut self) -> Option<(usize, usize)> {
318loop {
319match self.next_back() {
320 SearchStep::Match(a, b) => return Some((a, b)),
321 SearchStep::Done => return None,
322_ => continue,
323 }
324 }
325 }
326327/// Finds the next [`Reject`][SearchStep::Reject] result.
328 /// See [`next_back()`][ReverseSearcher::next_back].
329#[inline]
330fn next_reject_back(&mut self) -> Option<(usize, usize)> {
331loop {
332match self.next_back() {
333 SearchStep::Reject(a, b) => return Some((a, b)),
334 SearchStep::Done => return None,
335_ => continue,
336 }
337 }
338 }
339}
340341/// A marker trait to express that a [`ReverseSearcher`]
342/// can be used for a [`DoubleEndedIterator`] implementation.
343///
344/// For this, the impl of [`Searcher`] and [`ReverseSearcher`] need
345/// to follow these conditions:
346///
347/// - All results of `next()` need to be identical
348/// to the results of `next_back()` in reverse order.
349/// - `next()` and `next_back()` need to behave as
350/// the two ends of a range of values, that is they
351/// can not "walk past each other".
352///
353/// # Examples
354///
355/// `char::Searcher` is a `DoubleEndedSearcher` because searching for a
356/// [`char`] only requires looking at one at a time, which behaves the same
357/// from both ends.
358///
359/// `(&str)::Searcher` is not a `DoubleEndedSearcher` because
360/// the pattern `"aa"` in the haystack `"aaa"` matches as either
361/// `"[aa]a"` or `"a[aa]"`, depending on which side it is searched.
362pub trait DoubleEndedSearcher<'a>: ReverseSearcher<'a> {}
363364/////////////////////////////////////////////////////////////////////////////
365// Impl for char
366/////////////////////////////////////////////////////////////////////////////
367368/// Associated type for `<char as Pattern>::Searcher<'a>`.
369#[derive(#[automatically_derived]
impl<'a> crate::clone::Clone for CharSearcher<'a> {
#[inline]
fn clone(&self) -> CharSearcher<'a> {
CharSearcher {
haystack: crate::clone::Clone::clone(&self.haystack),
finger: crate::clone::Clone::clone(&self.finger),
finger_back: crate::clone::Clone::clone(&self.finger_back),
needle: crate::clone::Clone::clone(&self.needle),
utf8_size: crate::clone::Clone::clone(&self.utf8_size),
utf8_encoded: crate::clone::Clone::clone(&self.utf8_encoded),
}
}
}Clone, #[automatically_derived]
impl<'a> crate::fmt::Debug for CharSearcher<'a> {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
let names: &'static _ =
&["haystack", "finger", "finger_back", "needle", "utf8_size",
"utf8_encoded"];
let values: &[&dyn crate::fmt::Debug] =
&[&self.haystack, &self.finger, &self.finger_back, &self.needle,
&self.utf8_size, &&self.utf8_encoded];
crate::fmt::Formatter::debug_struct_fields_finish(f, "CharSearcher",
names, values)
}
}Debug)]
370pub struct CharSearcher<'a> {
371 haystack: &'a str,
372// safety invariant: `finger`/`finger_back` must be a valid utf8 byte index of `haystack`
373 // This invariant can be broken *within* next_match and next_match_back, however
374 // they must exit with fingers on valid code point boundaries.
375/// `finger` is the current byte index of the forward search.
376 /// Imagine that it exists before the byte at its index, i.e.
377 /// `haystack[finger]` is the first byte of the slice we must inspect during
378 /// forward searching
379finger: usize,
380/// `finger_back` is the current byte index of the reverse search.
381 /// Imagine that it exists after the byte at its index, i.e.
382 /// haystack[finger_back - 1] is the last byte of the slice we must inspect during
383 /// forward searching (and thus the first byte to be inspected when calling next_back()).
384finger_back: usize,
385/// The character being searched for
386needle: char,
387388// safety invariant: `utf8_size` must be less than 5
389/// The number of bytes `needle` takes up when encoded in utf8.
390utf8_size: u8,
391/// A utf8 encoded copy of the `needle`
392utf8_encoded: [u8; 4],
393}
394395impl CharSearcher<'_> {
396fn utf8_size(&self) -> usize {
397self.utf8_size.into()
398 }
399}
400401unsafe impl<'a> Searcher<'a> for CharSearcher<'a> {
402#[inline]
403fn haystack(&self) -> &'a str {
404self.haystack
405 }
406#[inline]
407fn next(&mut self) -> SearchStep {
408let old_finger = self.finger;
409// SAFETY: 1-4 guarantee safety of `get_unchecked`
410 // 1. `self.finger` and `self.finger_back` are kept on unicode boundaries
411 // (this is invariant)
412 // 2. `self.finger >= 0` since it starts at 0 and only increases
413 // 3. `self.finger < self.finger_back` because otherwise the char `iter`
414 // would return `SearchStep::Done`
415 // 4. `self.finger` comes before the end of the haystack because `self.finger_back`
416 // starts at the end and only decreases
417let slice = unsafe { self.haystack.get_unchecked(old_finger..self.finger_back) };
418let mut iter = slice.chars();
419let old_len = iter.iter.len();
420if let Some(ch) = iter.next() {
421// add byte offset of current character
422 // without re-encoding as utf-8
423self.finger += old_len - iter.iter.len();
424if ch == self.needle {
425 SearchStep::Match(old_finger, self.finger)
426 } else {
427 SearchStep::Reject(old_finger, self.finger)
428 }
429 } else {
430 SearchStep::Done431 }
432 }
433#[inline]
434fn next_match(&mut self) -> Option<(usize, usize)> {
435loop {
436// get the haystack after the last character found
437let bytes = self.haystack.as_bytes().get(self.finger..self.finger_back)?;
438// the last byte of the utf8 encoded needle
439 // SAFETY: we have an invariant that `utf8_size < 5`
440let last_byte = unsafe { *self.utf8_encoded.get_unchecked(self.utf8_size() - 1) };
441if let Some(index) = memchr::memchr(last_byte, bytes) {
442// The new finger is the index of the byte we found,
443 // plus one, since we memchr'd for the last byte of the character.
444 //
445 // Note that this doesn't always give us a finger on a UTF8 boundary.
446 // If we *didn't* find our character
447 // we may have indexed to the non-last byte of a 3-byte or 4-byte character.
448 // We can't just skip to the next valid starting byte because a character like
449 // ꁁ (U+A041 YI SYLLABLE PA), utf-8 `EA 81 81` will have us always find
450 // the second byte when searching for the third.
451 //
452 // However, this is totally okay. While we have the invariant that
453 // self.finger is on a UTF8 boundary, this invariant is not relied upon
454 // within this method (it is relied upon in CharSearcher::next()).
455 //
456 // We only exit this method when we reach the end of the string, or if we
457 // find something. When we find something the `finger` will be set
458 // to a UTF8 boundary.
459self.finger += index + 1;
460if self.finger >= self.utf8_size() {
461let found_char = self.finger - self.utf8_size();
462if let Some(slice) = self.haystack.as_bytes().get(found_char..self.finger) {
463if slice == &self.utf8_encoded[0..self.utf8_size()] {
464return Some((found_char, self.finger));
465 }
466 }
467 }
468 } else {
469// found nothing, exit
470self.finger = self.finger_back;
471return None;
472 }
473 }
474 }
475476// let next_reject use the default implementation from the Searcher trait
477}
478479unsafe impl<'a> ReverseSearcher<'a> for CharSearcher<'a> {
480#[inline]
481fn next_back(&mut self) -> SearchStep {
482let old_finger = self.finger_back;
483// SAFETY: see the comment for next() above
484let slice = unsafe { self.haystack.get_unchecked(self.finger..old_finger) };
485let mut iter = slice.chars();
486let old_len = iter.iter.len();
487if let Some(ch) = iter.next_back() {
488// subtract byte offset of current character
489 // without re-encoding as utf-8
490self.finger_back -= old_len - iter.iter.len();
491if ch == self.needle {
492 SearchStep::Match(self.finger_back, old_finger)
493 } else {
494 SearchStep::Reject(self.finger_back, old_finger)
495 }
496 } else {
497 SearchStep::Done498 }
499 }
500#[inline]
501fn next_match_back(&mut self) -> Option<(usize, usize)> {
502let haystack = self.haystack.as_bytes();
503loop {
504// get the haystack up to but not including the last character searched
505let bytes = haystack.get(self.finger..self.finger_back)?;
506// the last byte of the utf8 encoded needle
507 // SAFETY: we have an invariant that `utf8_size < 5`
508let last_byte = unsafe { *self.utf8_encoded.get_unchecked(self.utf8_size() - 1) };
509if let Some(index) = memchr::memrchr(last_byte, bytes) {
510// we searched a slice that was offset by self.finger,
511 // add self.finger to recoup the original index
512let index = self.finger + index;
513// memrchr will return the index of the byte we wish to
514 // find. In case of an ASCII character, this is indeed
515 // were we wish our new finger to be ("after" the found
516 // char in the paradigm of reverse iteration). For
517 // multibyte chars we need to skip down by the number of more
518 // bytes they have than ASCII
519let shift = self.utf8_size() - 1;
520if index >= shift {
521let found_char = index - shift;
522if let Some(slice) = haystack.get(found_char..(found_char + self.utf8_size())) {
523if slice == &self.utf8_encoded[0..self.utf8_size()] {
524// move finger to before the character found (i.e., at its start index)
525self.finger_back = found_char;
526return Some((self.finger_back, self.finger_back + self.utf8_size()));
527 }
528 }
529 }
530// We can't use finger_back = index - size + 1 here. If we found the last char
531 // of a different-sized character (or the middle byte of a different character)
532 // we need to bump the finger_back down to `index`. This similarly makes
533 // `finger_back` have the potential to no longer be on a boundary,
534 // but this is OK since we only exit this function on a boundary
535 // or when the haystack has been searched completely.
536 //
537 // Unlike next_match this does not
538 // have the problem of repeated bytes in utf-8 because
539 // we're searching for the last byte, and we can only have
540 // found the last byte when searching in reverse.
541self.finger_back = index;
542 } else {
543self.finger_back = self.finger;
544// found nothing, exit
545return None;
546 }
547 }
548 }
549550// let next_reject_back use the default implementation from the Searcher trait
551}
552553impl<'a> DoubleEndedSearcher<'a> for CharSearcher<'a> {}
554555/// Searches for chars that are equal to a given [`char`].
556///
557/// # Examples
558///
559/// ```
560/// assert_eq!("Hello world".find('o'), Some(4));
561/// ```
562impl Patternfor char {
563type Searcher<'a> = CharSearcher<'a>;
564565#[inline]
566fn into_searcher<'a>(self, haystack: &'a str) -> Self::Searcher<'a> {
567let mut utf8_encoded = [0; char::MAX_LEN_UTF8];
568let utf8_size = self569 .encode_utf8(&mut utf8_encoded)
570 .len()
571 .try_into()
572 .expect("char len should be less than 255");
573574CharSearcher {
575haystack,
576 finger: 0,
577 finger_back: haystack.len(),
578 needle: self,
579utf8_size,
580utf8_encoded,
581 }
582 }
583584#[inline]
585fn is_contained_in(self, haystack: &str) -> bool {
586if (selfas u32) < 128 {
587haystack.as_bytes().contains(&(selfas u8))
588 } else {
589let mut buffer = [0u8; 4];
590self.encode_utf8(&mut buffer).is_contained_in(haystack)
591 }
592 }
593594#[inline]
595fn is_prefix_of(self, haystack: &str) -> bool {
596self.encode_utf8(&mut [0u8; 4]).is_prefix_of(haystack)
597 }
598599#[inline]
600fn strip_prefix_of(self, haystack: &str) -> Option<&str> {
601self.encode_utf8(&mut [0u8; 4]).strip_prefix_of(haystack)
602 }
603604#[inline]
605fn is_suffix_of<'a>(self, haystack: &'a str) -> bool606where
607Self::Searcher<'a>: ReverseSearcher<'a>,
608 {
609self.encode_utf8(&mut [0u8; 4]).is_suffix_of(haystack)
610 }
611612#[inline]
613fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str>
614where
615Self::Searcher<'a>: ReverseSearcher<'a>,
616 {
617self.encode_utf8(&mut [0u8; 4]).strip_suffix_of(haystack)
618 }
619620#[inline]
621fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>> {
622Some(Utf8Pattern::CharPattern(*self))
623 }
624}
625626/////////////////////////////////////////////////////////////////////////////
627// Impl for a MultiCharEq wrapper
628/////////////////////////////////////////////////////////////////////////////
629630#[doc(hidden)]
631trait MultiCharEq {
632fn matches(&mut self, c: char) -> bool;
633}
634635impl<F> MultiCharEqfor F
636where
637F: FnMut(char) -> bool,
638{
639#[inline]
640fn matches(&mut self, c: char) -> bool {
641 (*self)(c)
642 }
643}
644645impl<const N: usize> MultiCharEqfor [char; N] {
646#[inline]
647fn matches(&mut self, c: char) -> bool {
648self.contains(&c)
649 }
650}
651652impl<const N: usize> MultiCharEqfor &[char; N] {
653#[inline]
654fn matches(&mut self, c: char) -> bool {
655self.contains(&c)
656 }
657}
658659impl MultiCharEqfor &[char] {
660#[inline]
661fn matches(&mut self, c: char) -> bool {
662self.contains(&c)
663 }
664}
665666struct MultiCharEqPattern<C: MultiCharEq>(C);
667668#[derive(#[automatically_derived]
impl<'a, C: crate::clone::Clone + MultiCharEq> crate::clone::Clone for
MultiCharEqSearcher<'a, C> {
#[inline]
fn clone(&self) -> MultiCharEqSearcher<'a, C> {
MultiCharEqSearcher {
char_eq: crate::clone::Clone::clone(&self.char_eq),
haystack: crate::clone::Clone::clone(&self.haystack),
char_indices: crate::clone::Clone::clone(&self.char_indices),
}
}
}Clone, #[automatically_derived]
impl<'a, C: crate::fmt::Debug + MultiCharEq> crate::fmt::Debug for
MultiCharEqSearcher<'a, C> {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_struct_field3_finish(f,
"MultiCharEqSearcher", "char_eq", &self.char_eq, "haystack",
&self.haystack, "char_indices", &&self.char_indices)
}
}Debug)]
669struct MultiCharEqSearcher<'a, C: MultiCharEq> {
670 char_eq: C,
671 haystack: &'a str,
672 char_indices: super::CharIndices<'a>,
673}
674675impl<C: MultiCharEq> Patternfor MultiCharEqPattern<C> {
676type Searcher<'a> = MultiCharEqSearcher<'a, C>;
677678#[inline]
679fn into_searcher(self, haystack: &str) -> MultiCharEqSearcher<'_, C> {
680MultiCharEqSearcher { haystack, char_eq: self.0, char_indices: haystack.char_indices() }
681 }
682}
683684unsafe impl<'a, C: MultiCharEq> Searcher<'a> for MultiCharEqSearcher<'a, C> {
685#[inline]
686fn haystack(&self) -> &'a str {
687self.haystack
688 }
689690#[inline]
691fn next(&mut self) -> SearchStep {
692let s = &mut self.char_indices;
693// Compare lengths of the internal byte slice iterator
694 // to find length of current char
695let pre_len = s.iter.iter.len();
696if let Some((i, c)) = s.next() {
697let len = s.iter.iter.len();
698let char_len = pre_len - len;
699if self.char_eq.matches(c) {
700return SearchStep::Match(i, i + char_len);
701 } else {
702return SearchStep::Reject(i, i + char_len);
703 }
704 }
705 SearchStep::Done706 }
707}
708709unsafe impl<'a, C: MultiCharEq> ReverseSearcher<'a> for MultiCharEqSearcher<'a, C> {
710#[inline]
711fn next_back(&mut self) -> SearchStep {
712let s = &mut self.char_indices;
713// Compare lengths of the internal byte slice iterator
714 // to find length of current char
715let pre_len = s.iter.iter.len();
716if let Some((i, c)) = s.next_back() {
717let len = s.iter.iter.len();
718let char_len = pre_len - len;
719if self.char_eq.matches(c) {
720return SearchStep::Match(i, i + char_len);
721 } else {
722return SearchStep::Reject(i, i + char_len);
723 }
724 }
725 SearchStep::Done726 }
727}
728729impl<'a, C: MultiCharEq> DoubleEndedSearcher<'a> for MultiCharEqSearcher<'a, C> {}
730731/////////////////////////////////////////////////////////////////////////////
732733macro_rules!pattern_methods {
734 ($a:lifetime, $t:ty, $pmap:expr, $smap:expr) => {
735type Searcher<$a> = $t;
736737#[inline]
738fn into_searcher<$a>(self, haystack: &$a str) -> $t {
739 ($smap)(($pmap)(self).into_searcher(haystack))
740 }
741742#[inline]
743fn is_contained_in<$a>(self, haystack: &$a str) -> bool {
744 ($pmap)(self).is_contained_in(haystack)
745 }
746747#[inline]
748fn is_prefix_of<$a>(self, haystack: &$a str) -> bool {
749 ($pmap)(self).is_prefix_of(haystack)
750 }
751752#[inline]
753fn strip_prefix_of<$a>(self, haystack: &$a str) -> Option<&$a str> {
754 ($pmap)(self).strip_prefix_of(haystack)
755 }
756757#[inline]
758fn is_suffix_of<$a>(self, haystack: &$a str) -> bool759where
760$t: ReverseSearcher<$a>,
761 {
762 ($pmap)(self).is_suffix_of(haystack)
763 }
764765#[inline]
766fn strip_suffix_of<$a>(self, haystack: &$a str) -> Option<&$a str>
767where
768$t: ReverseSearcher<$a>,
769 {
770 ($pmap)(self).strip_suffix_of(haystack)
771 }
772 };
773}
774775macro_rules!searcher_methods {
776 (forward) => {
777#[inline]
778fn haystack(&self) -> &'a str {
779self.0.haystack()
780 }
781#[inline]
782fn next(&mut self) -> SearchStep {
783self.0.next()
784 }
785#[inline]
786fn next_match(&mut self) -> Option<(usize, usize)> {
787self.0.next_match()
788 }
789#[inline]
790fn next_reject(&mut self) -> Option<(usize, usize)> {
791self.0.next_reject()
792 }
793 };
794 (reverse) => {
795#[inline]
796fn next_back(&mut self) -> SearchStep {
797self.0.next_back()
798 }
799#[inline]
800fn next_match_back(&mut self) -> Option<(usize, usize)> {
801self.0.next_match_back()
802 }
803#[inline]
804fn next_reject_back(&mut self) -> Option<(usize, usize)> {
805self.0.next_reject_back()
806 }
807 };
808}
809810/// Associated type for `<[char; N] as Pattern>::Searcher<'a>`.
811#[derive(#[automatically_derived]
impl<'a, const N : usize> crate::clone::Clone for CharArraySearcher<'a, N> {
#[inline]
fn clone(&self) -> CharArraySearcher<'a, N> {
CharArraySearcher(crate::clone::Clone::clone(&self.0))
}
}Clone, #[automatically_derived]
impl<'a, const N : usize> crate::fmt::Debug for CharArraySearcher<'a, N> {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_tuple_field1_finish(f,
"CharArraySearcher", &&self.0)
}
}Debug)]
812pub struct CharArraySearcher<'a, const N: usize>(
813 <MultiCharEqPattern<[char; N]> as Pattern>::Searcher<'a>,
814);
815816/// Associated type for `<&[char; N] as Pattern>::Searcher<'a>`.
817#[derive(#[automatically_derived]
impl<'a, 'b, const N : usize> crate::clone::Clone for
CharArrayRefSearcher<'a, 'b, N> {
#[inline]
fn clone(&self) -> CharArrayRefSearcher<'a, 'b, N> {
CharArrayRefSearcher(crate::clone::Clone::clone(&self.0))
}
}Clone, #[automatically_derived]
impl<'a, 'b, const N : usize> crate::fmt::Debug for
CharArrayRefSearcher<'a, 'b, N> {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_tuple_field1_finish(f,
"CharArrayRefSearcher", &&self.0)
}
}Debug)]
818pub struct CharArrayRefSearcher<'a, 'b, const N: usize>(
819 <MultiCharEqPattern<&'b [char; N]> as Pattern>::Searcher<'a>,
820);
821822/// Searches for chars that are equal to any of the [`char`]s in the array.
823///
824/// # Examples
825///
826/// ```
827/// assert_eq!("Hello world".find(['o', 'l']), Some(2));
828/// assert_eq!("Hello world".find(['h', 'w']), Some(6));
829/// ```
830impl<const N: usize> Patternfor [char; N] {
831type Searcher<'a> = CharArraySearcher<'a, N>;
#[inline]
fn into_searcher<'a>(self, haystack: &'a str) -> CharArraySearcher<'a, N> {
(CharArraySearcher)((MultiCharEqPattern)(self).into_searcher(haystack))
}
#[inline]
fn is_contained_in<'a>(self, haystack: &'a str) -> bool {
(MultiCharEqPattern)(self).is_contained_in(haystack)
}
#[inline]
fn is_prefix_of<'a>(self, haystack: &'a str) -> bool {
(MultiCharEqPattern)(self).is_prefix_of(haystack)
}
#[inline]
fn strip_prefix_of<'a>(self, haystack: &'a str) -> Option<&'a str> {
(MultiCharEqPattern)(self).strip_prefix_of(haystack)
}
#[inline]
fn is_suffix_of<'a>(self, haystack: &'a str) -> bool where
CharArraySearcher<'a, N>: ReverseSearcher<'a> {
(MultiCharEqPattern)(self).is_suffix_of(haystack)
}
#[inline]
fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str> where
CharArraySearcher<'a, N>: ReverseSearcher<'a> {
(MultiCharEqPattern)(self).strip_suffix_of(haystack)
}pattern_methods!('a, CharArraySearcher<'a, N>, MultiCharEqPattern, CharArraySearcher);
832}
833834unsafe impl<'a, const N: usize> Searcher<'a> for CharArraySearcher<'a, N> {
835#[inline]
fn haystack(&self) -> &'a str { self.0.haystack() }
#[inline]
fn next(&mut self) -> SearchStep { self.0.next() }
#[inline]
fn next_match(&mut self) -> Option<(usize, usize)> { self.0.next_match() }
#[inline]
fn next_reject(&mut self) -> Option<(usize, usize)> { self.0.next_reject() }searcher_methods!(forward);
836}
837838unsafe impl<'a, const N: usize> ReverseSearcher<'a> for CharArraySearcher<'a, N> {
839#[inline]
fn next_back(&mut self) -> SearchStep { self.0.next_back() }
#[inline]
fn next_match_back(&mut self) -> Option<(usize, usize)> {
self.0.next_match_back()
}
#[inline]
fn next_reject_back(&mut self) -> Option<(usize, usize)> {
self.0.next_reject_back()
}searcher_methods!(reverse);
840}
841842impl<'a, const N: usize> DoubleEndedSearcher<'a> for CharArraySearcher<'a, N> {}
843844/// Searches for chars that are equal to any of the [`char`]s in the array.
845///
846/// # Examples
847///
848/// ```
849/// assert_eq!("Hello world".find(&['o', 'l']), Some(2));
850/// assert_eq!("Hello world".find(&['h', 'w']), Some(6));
851/// ```
852impl<'b, const N: usize> Patternfor &'b [char; N] {
853type Searcher<'a> = CharArrayRefSearcher<'a, 'b, N>;
#[inline]
fn into_searcher<'a>(self, haystack: &'a str)
-> CharArrayRefSearcher<'a, 'b, N> {
(CharArrayRefSearcher)((MultiCharEqPattern)(self).into_searcher(haystack))
}
#[inline]
fn is_contained_in<'a>(self, haystack: &'a str) -> bool {
(MultiCharEqPattern)(self).is_contained_in(haystack)
}
#[inline]
fn is_prefix_of<'a>(self, haystack: &'a str) -> bool {
(MultiCharEqPattern)(self).is_prefix_of(haystack)
}
#[inline]
fn strip_prefix_of<'a>(self, haystack: &'a str) -> Option<&'a str> {
(MultiCharEqPattern)(self).strip_prefix_of(haystack)
}
#[inline]
fn is_suffix_of<'a>(self, haystack: &'a str) -> bool where
CharArrayRefSearcher<'a, 'b, N>: ReverseSearcher<'a> {
(MultiCharEqPattern)(self).is_suffix_of(haystack)
}
#[inline]
fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str> where
CharArrayRefSearcher<'a, 'b, N>: ReverseSearcher<'a> {
(MultiCharEqPattern)(self).strip_suffix_of(haystack)
}pattern_methods!('a, CharArrayRefSearcher<'a, 'b, N>, MultiCharEqPattern, CharArrayRefSearcher);
854}
855856unsafe impl<'a, 'b, const N: usize> Searcher<'a> for CharArrayRefSearcher<'a, 'b, N> {
857#[inline]
fn haystack(&self) -> &'a str { self.0.haystack() }
#[inline]
fn next(&mut self) -> SearchStep { self.0.next() }
#[inline]
fn next_match(&mut self) -> Option<(usize, usize)> { self.0.next_match() }
#[inline]
fn next_reject(&mut self) -> Option<(usize, usize)> { self.0.next_reject() }searcher_methods!(forward);
858}
859860unsafe impl<'a, 'b, const N: usize> ReverseSearcher<'a> for CharArrayRefSearcher<'a, 'b, N> {
861#[inline]
fn next_back(&mut self) -> SearchStep { self.0.next_back() }
#[inline]
fn next_match_back(&mut self) -> Option<(usize, usize)> {
self.0.next_match_back()
}
#[inline]
fn next_reject_back(&mut self) -> Option<(usize, usize)> {
self.0.next_reject_back()
}searcher_methods!(reverse);
862}
863864impl<'a, 'b, const N: usize> DoubleEndedSearcher<'a> for CharArrayRefSearcher<'a, 'b, N> {}
865866/////////////////////////////////////////////////////////////////////////////
867// Impl for &[char]
868/////////////////////////////////////////////////////////////////////////////
869870// Todo: Change / Remove due to ambiguity in meaning.
871872/// Associated type for `<&[char] as Pattern>::Searcher<'a>`.
873#[derive(#[automatically_derived]
impl<'a, 'b> crate::clone::Clone for CharSliceSearcher<'a, 'b> {
#[inline]
fn clone(&self) -> CharSliceSearcher<'a, 'b> {
CharSliceSearcher(crate::clone::Clone::clone(&self.0))
}
}Clone, #[automatically_derived]
impl<'a, 'b> crate::fmt::Debug for CharSliceSearcher<'a, 'b> {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_tuple_field1_finish(f,
"CharSliceSearcher", &&self.0)
}
}Debug)]
874pub struct CharSliceSearcher<'a, 'b>(<MultiCharEqPattern<&'b [char]> as Pattern>::Searcher<'a>);
875876unsafe impl<'a, 'b> Searcher<'a> for CharSliceSearcher<'a, 'b> {
877#[inline]
fn haystack(&self) -> &'a str { self.0.haystack() }
#[inline]
fn next(&mut self) -> SearchStep { self.0.next() }
#[inline]
fn next_match(&mut self) -> Option<(usize, usize)> { self.0.next_match() }
#[inline]
fn next_reject(&mut self) -> Option<(usize, usize)> { self.0.next_reject() }searcher_methods!(forward);
878}
879880unsafe impl<'a, 'b> ReverseSearcher<'a> for CharSliceSearcher<'a, 'b> {
881#[inline]
fn next_back(&mut self) -> SearchStep { self.0.next_back() }
#[inline]
fn next_match_back(&mut self) -> Option<(usize, usize)> {
self.0.next_match_back()
}
#[inline]
fn next_reject_back(&mut self) -> Option<(usize, usize)> {
self.0.next_reject_back()
}searcher_methods!(reverse);
882}
883884impl<'a, 'b> DoubleEndedSearcher<'a> for CharSliceSearcher<'a, 'b> {}
885886/// Searches for chars that are equal to any of the [`char`]s in the slice.
887///
888/// # Examples
889///
890/// ```
891/// assert_eq!("Hello world".find(&['o', 'l'][..]), Some(2));
892/// assert_eq!("Hello world".find(&['h', 'w'][..]), Some(6));
893/// ```
894impl<'b> Patternfor &'b [char] {
895type Searcher<'a> = CharSliceSearcher<'a, 'b>;
#[inline]
fn into_searcher<'a>(self, haystack: &'a str) -> CharSliceSearcher<'a, 'b> {
(CharSliceSearcher)((MultiCharEqPattern)(self).into_searcher(haystack))
}
#[inline]
fn is_contained_in<'a>(self, haystack: &'a str) -> bool {
(MultiCharEqPattern)(self).is_contained_in(haystack)
}
#[inline]
fn is_prefix_of<'a>(self, haystack: &'a str) -> bool {
(MultiCharEqPattern)(self).is_prefix_of(haystack)
}
#[inline]
fn strip_prefix_of<'a>(self, haystack: &'a str) -> Option<&'a str> {
(MultiCharEqPattern)(self).strip_prefix_of(haystack)
}
#[inline]
fn is_suffix_of<'a>(self, haystack: &'a str) -> bool where
CharSliceSearcher<'a, 'b>: ReverseSearcher<'a> {
(MultiCharEqPattern)(self).is_suffix_of(haystack)
}
#[inline]
fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str> where
CharSliceSearcher<'a, 'b>: ReverseSearcher<'a> {
(MultiCharEqPattern)(self).strip_suffix_of(haystack)
}pattern_methods!('a, CharSliceSearcher<'a, 'b>, MultiCharEqPattern, CharSliceSearcher);
896}
897898/////////////////////////////////////////////////////////////////////////////
899// Impl for F: FnMut(char) -> bool
900/////////////////////////////////////////////////////////////////////////////
901902/// Associated type for `<F as Pattern>::Searcher<'a>`.
903#[derive(#[automatically_derived]
impl<'a, F: crate::clone::Clone> crate::clone::Clone for
CharPredicateSearcher<'a, F> where F: FnMut(char) -> bool {
#[inline]
fn clone(&self) -> CharPredicateSearcher<'a, F> {
CharPredicateSearcher(crate::clone::Clone::clone(&self.0))
}
}Clone)]
904pub struct CharPredicateSearcher<'a, F>(<MultiCharEqPattern<F> as Pattern>::Searcher<'a>)
905where
906F: FnMut(char) -> bool;
907908impl<F> fmt::Debugfor CharPredicateSearcher<'_, F>
909where
910F: FnMut(char) -> bool,
911{
912fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
913f.debug_struct("CharPredicateSearcher")
914 .field("haystack", &self.0.haystack)
915 .field("char_indices", &self.0.char_indices)
916 .finish()
917 }
918}
919unsafe impl<'a, F> Searcher<'a> for CharPredicateSearcher<'a, F>
920where
921F: FnMut(char) -> bool,
922{
923#[inline]
fn haystack(&self) -> &'a str { self.0.haystack() }
#[inline]
fn next(&mut self) -> SearchStep { self.0.next() }
#[inline]
fn next_match(&mut self) -> Option<(usize, usize)> { self.0.next_match() }
#[inline]
fn next_reject(&mut self) -> Option<(usize, usize)> { self.0.next_reject() }searcher_methods!(forward);
924}
925926unsafe impl<'a, F> ReverseSearcher<'a> for CharPredicateSearcher<'a, F>
927where
928F: FnMut(char) -> bool,
929{
930#[inline]
fn next_back(&mut self) -> SearchStep { self.0.next_back() }
#[inline]
fn next_match_back(&mut self) -> Option<(usize, usize)> {
self.0.next_match_back()
}
#[inline]
fn next_reject_back(&mut self) -> Option<(usize, usize)> {
self.0.next_reject_back()
}searcher_methods!(reverse);
931}
932933impl<'a, F> DoubleEndedSearcher<'a> for CharPredicateSearcher<'a, F> where F: FnMut(char) -> bool {}
934935/// Searches for [`char`]s that match the given predicate.
936///
937/// # Examples
938///
939/// ```
940/// assert_eq!("Hello world".find(char::is_uppercase), Some(0));
941/// assert_eq!("Hello world".find(|c| "aeiou".contains(c)), Some(1));
942/// ```
943impl<F> Patternfor F
944where
945F: FnMut(char) -> bool,
946{
947type Searcher<'a> = CharPredicateSearcher<'a, F>;
#[inline]
fn into_searcher<'a>(self, haystack: &'a str)
-> CharPredicateSearcher<'a, F> {
(CharPredicateSearcher)((MultiCharEqPattern)(self).into_searcher(haystack))
}
#[inline]
fn is_contained_in<'a>(self, haystack: &'a str) -> bool {
(MultiCharEqPattern)(self).is_contained_in(haystack)
}
#[inline]
fn is_prefix_of<'a>(self, haystack: &'a str) -> bool {
(MultiCharEqPattern)(self).is_prefix_of(haystack)
}
#[inline]
fn strip_prefix_of<'a>(self, haystack: &'a str) -> Option<&'a str> {
(MultiCharEqPattern)(self).strip_prefix_of(haystack)
}
#[inline]
fn is_suffix_of<'a>(self, haystack: &'a str) -> bool where
CharPredicateSearcher<'a, F>: ReverseSearcher<'a> {
(MultiCharEqPattern)(self).is_suffix_of(haystack)
}
#[inline]
fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str> where
CharPredicateSearcher<'a, F>: ReverseSearcher<'a> {
(MultiCharEqPattern)(self).strip_suffix_of(haystack)
}pattern_methods!('a, CharPredicateSearcher<'a, F>, MultiCharEqPattern, CharPredicateSearcher);
948}
949950/////////////////////////////////////////////////////////////////////////////
951// Impl for &&str
952/////////////////////////////////////////////////////////////////////////////
953954/// Delegates to the `&str` impl.
955impl<'b, 'c> Patternfor &'c &'b str {
956type Searcher<'a> = StrSearcher<'a, 'b>;
#[inline]
fn into_searcher<'a>(self, haystack: &'a str) -> StrSearcher<'a, 'b> {
(|s| s)((|&s| s)(self).into_searcher(haystack))
}
#[inline]
fn is_contained_in<'a>(self, haystack: &'a str) -> bool {
(|&s| s)(self).is_contained_in(haystack)
}
#[inline]
fn is_prefix_of<'a>(self, haystack: &'a str) -> bool {
(|&s| s)(self).is_prefix_of(haystack)
}
#[inline]
fn strip_prefix_of<'a>(self, haystack: &'a str) -> Option<&'a str> {
(|&s| s)(self).strip_prefix_of(haystack)
}
#[inline]
fn is_suffix_of<'a>(self, haystack: &'a str) -> bool where
StrSearcher<'a, 'b>: ReverseSearcher<'a> {
(|&s| s)(self).is_suffix_of(haystack)
}
#[inline]
fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str> where
StrSearcher<'a, 'b>: ReverseSearcher<'a> {
(|&s| s)(self).strip_suffix_of(haystack)
}pattern_methods!('a, StrSearcher<'a, 'b>, |&s| s, |s| s);
957}
958959/////////////////////////////////////////////////////////////////////////////
960// Impl for &str
961/////////////////////////////////////////////////////////////////////////////
962963/// Non-allocating substring search.
964///
965/// Will handle the pattern `""` as returning empty matches at each character
966/// boundary.
967///
968/// # Examples
969///
970/// ```
971/// assert_eq!("Hello world".find("world"), Some(6));
972/// ```
973impl<'b> Patternfor &'b str {
974type Searcher<'a> = StrSearcher<'a, 'b>;
975976#[inline]
977fn into_searcher(self, haystack: &str) -> StrSearcher<'_, 'b> {
978StrSearcher::new(haystack, self)
979 }
980981/// Checks whether the pattern matches at the front of the haystack.
982#[inline]
983fn is_prefix_of(self, haystack: &str) -> bool {
984haystack.as_bytes().starts_with(self.as_bytes())
985 }
986987/// Checks whether the pattern matches anywhere in the haystack
988#[inline]
989fn is_contained_in(self, haystack: &str) -> bool {
990if self.is_empty() {
991return true;
992 }
993994match self.len().cmp(&haystack.len()) {
995 Ordering::Less => {
996if self.len() == 1 {
997return haystack.as_bytes().contains(&self.as_bytes()[0]);
998 }
9991000#[cfg(any(
1001 all(target_arch = "x86_64", target_feature = "sse2"),
1002 all(target_arch = "loongarch64", target_feature = "lsx"),
1003 all(target_arch = "aarch64", target_feature = "neon")
1004 ))]
1005if self.len() <= 32 {
1006if let Some(result) = simd_contains(self, haystack) {
1007return result;
1008 }
1009 }
10101011self.into_searcher(haystack).next_match().is_some()
1012 }
1013_ => self == haystack,
1014 }
1015 }
10161017/// Removes the pattern from the front of haystack, if it matches.
1018#[inline]
1019fn strip_prefix_of(self, haystack: &str) -> Option<&str> {
1020if self.is_prefix_of(haystack) {
1021// SAFETY: prefix was just verified to exist.
1022unsafe { Some(haystack.get_unchecked(self.len()..)) }
1023 } else {
1024None1025 }
1026 }
10271028/// Checks whether the pattern matches at the back of the haystack.
1029#[inline]
1030fn is_suffix_of<'a>(self, haystack: &'a str) -> bool1031where
1032Self::Searcher<'a>: ReverseSearcher<'a>,
1033 {
1034haystack.as_bytes().ends_with(self.as_bytes())
1035 }
10361037/// Removes the pattern from the back of haystack, if it matches.
1038#[inline]
1039fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str>
1040where
1041Self::Searcher<'a>: ReverseSearcher<'a>,
1042 {
1043if self.is_suffix_of(haystack) {
1044let i = haystack.len() - self.len();
1045// SAFETY: suffix was just verified to exist.
1046unsafe { Some(haystack.get_unchecked(..i)) }
1047 } else {
1048None1049 }
1050 }
10511052#[inline]
1053fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>> {
1054Some(Utf8Pattern::StringPattern(self))
1055 }
1056}
10571058/////////////////////////////////////////////////////////////////////////////
1059// Two Way substring searcher
1060/////////////////////////////////////////////////////////////////////////////
10611062#[derive(#[automatically_derived]
impl<'a, 'b> crate::clone::Clone for StrSearcher<'a, 'b> {
#[inline]
fn clone(&self) -> StrSearcher<'a, 'b> {
StrSearcher {
haystack: crate::clone::Clone::clone(&self.haystack),
needle: crate::clone::Clone::clone(&self.needle),
searcher: crate::clone::Clone::clone(&self.searcher),
}
}
}Clone, #[automatically_derived]
impl<'a, 'b> crate::fmt::Debug for StrSearcher<'a, 'b> {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_struct_field3_finish(f, "StrSearcher",
"haystack", &self.haystack, "needle", &self.needle, "searcher",
&&self.searcher)
}
}Debug)]
1063/// Associated type for `<&str as Pattern>::Searcher<'a>`.
1064pub struct StrSearcher<'a, 'b> {
1065 haystack: &'a str,
1066 needle: &'b str,
10671068 searcher: StrSearcherImpl,
1069}
10701071#[derive(#[automatically_derived]
impl crate::clone::Clone for StrSearcherImpl {
#[inline]
fn clone(&self) -> StrSearcherImpl {
match self {
StrSearcherImpl::Empty(__self_0) =>
StrSearcherImpl::Empty(crate::clone::Clone::clone(__self_0)),
StrSearcherImpl::Byte(__self_0) =>
StrSearcherImpl::Byte(crate::clone::Clone::clone(__self_0)),
StrSearcherImpl::TwoWay(__self_0) =>
StrSearcherImpl::TwoWay(crate::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]
impl crate::fmt::Debug for StrSearcherImpl {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
match self {
StrSearcherImpl::Empty(__self_0) =>
crate::fmt::Formatter::debug_tuple_field1_finish(f, "Empty",
&__self_0),
StrSearcherImpl::Byte(__self_0) =>
crate::fmt::Formatter::debug_tuple_field1_finish(f, "Byte",
&__self_0),
StrSearcherImpl::TwoWay(__self_0) =>
crate::fmt::Formatter::debug_tuple_field1_finish(f, "TwoWay",
&__self_0),
}
}
}Debug)]
1072enum StrSearcherImpl {
1073 Empty(EmptyNeedle),
1074 Byte(ByteNeedle),
1075 TwoWay(TwoWaySearcher),
1076}
10771078#[derive(#[automatically_derived]
impl crate::clone::Clone for EmptyNeedle {
#[inline]
fn clone(&self) -> EmptyNeedle {
EmptyNeedle {
position: crate::clone::Clone::clone(&self.position),
end: crate::clone::Clone::clone(&self.end),
is_match_fw: crate::clone::Clone::clone(&self.is_match_fw),
is_match_bw: crate::clone::Clone::clone(&self.is_match_bw),
is_finished: crate::clone::Clone::clone(&self.is_finished),
}
}
}Clone, #[automatically_derived]
impl crate::fmt::Debug for EmptyNeedle {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_struct_field5_finish(f, "EmptyNeedle",
"position", &self.position, "end", &self.end, "is_match_fw",
&self.is_match_fw, "is_match_bw", &self.is_match_bw,
"is_finished", &&self.is_finished)
}
}Debug)]
1079struct EmptyNeedle {
1080 position: usize,
1081 end: usize,
1082 is_match_fw: bool,
1083 is_match_bw: bool,
1084// Needed in case of an empty haystack, see #85462
1085is_finished: bool,
1086}
10871088/// Fast searcher for a single-byte needle using `memchr`/`memrchr`.
1089#[derive(#[automatically_derived]
impl crate::clone::Clone for ByteNeedle {
#[inline]
fn clone(&self) -> ByteNeedle {
ByteNeedle {
b: crate::clone::Clone::clone(&self.b),
position: crate::clone::Clone::clone(&self.position),
end: crate::clone::Clone::clone(&self.end),
}
}
}Clone, #[automatically_derived]
impl crate::fmt::Debug for ByteNeedle {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_struct_field3_finish(f, "ByteNeedle",
"b", &self.b, "position", &self.position, "end", &&self.end)
}
}Debug)]
1090struct ByteNeedle {
1091 b: u8,
1092/// Forward cursor: `haystack[..position]` has already been reported.
1093position: usize,
1094/// Backward cursor: `haystack[end..]` has already been reported.
1095end: usize,
1096}
10971098impl<'a, 'b> StrSearcher<'a, 'b> {
1099fn new(haystack: &'a str, needle: &'b str) -> StrSearcher<'a, 'b> {
1100if needle.is_empty() {
1101StrSearcher {
1102haystack,
1103needle,
1104 searcher: StrSearcherImpl::Empty(EmptyNeedle {
1105 position: 0,
1106 end: haystack.len(),
1107 is_match_fw: true,
1108 is_match_bw: true,
1109 is_finished: false,
1110 }),
1111 }
1112 } else if let &[b] = needle.as_bytes() {
1113StrSearcher {
1114haystack,
1115needle,
1116 searcher: StrSearcherImpl::Byte(ByteNeedle { b, position: 0, end: haystack.len() }),
1117 }
1118 } else {
1119StrSearcher {
1120haystack,
1121needle,
1122 searcher: StrSearcherImpl::TwoWay(TwoWaySearcher::new(
1123needle.as_bytes(),
1124haystack.len(),
1125 )),
1126 }
1127 }
1128 }
1129}
11301131unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> {
1132#[inline]
1133fn haystack(&self) -> &'a str {
1134self.haystack
1135 }
11361137#[inline]
1138fn next(&mut self) -> SearchStep {
1139match self.searcher {
1140 StrSearcherImpl::Empty(ref mut searcher) => {
1141if searcher.is_finished {
1142return SearchStep::Done;
1143 }
1144// empty needle rejects every char and matches every empty string between them
1145let is_match = searcher.is_match_fw;
1146searcher.is_match_fw = !searcher.is_match_fw;
1147let pos = searcher.position;
1148match self.haystack[pos..].chars().next() {
1149_ if is_match => SearchStep::Match(pos, pos),
1150None => {
1151searcher.is_finished = true;
1152 SearchStep::Done1153 }
1154Some(ch) => {
1155searcher.position += ch.len_utf8();
1156 SearchStep::Reject(pos, searcher.position)
1157 }
1158 }
1159 }
1160 StrSearcherImpl::Byte(ref mut searcher) => {
1161let bytes = self.haystack.as_bytes();
1162let pos = searcher.position;
1163if pos >= bytes.len() {
1164return SearchStep::Done;
1165 }
1166if bytes[pos] == searcher.b {
1167searcher.position = pos + 1;
1168 SearchStep::Match(pos, pos + 1)
1169 } else {
1170// `pos` is always on a char boundary, so this rejects
1171 // exactly the char starting at `pos`.
1172let end = self.haystack.ceil_char_boundary(pos + 1);
1173searcher.position = end;
1174 SearchStep::Reject(pos, end)
1175 }
1176 }
1177 StrSearcherImpl::TwoWay(ref mut searcher) => {
1178// TwoWaySearcher produces valid *Match* indices that split at char boundaries
1179 // as long as it does correct matching and that haystack and needle are
1180 // valid UTF-8
1181 // *Rejects* from the algorithm can fall on any indices, but we will walk them
1182 // manually to the next character boundary, so that they are utf-8 safe.
1183if searcher.position == self.haystack.len() {
1184return SearchStep::Done;
1185 }
1186let is_long = searcher.memory == usize::MAX;
1187match searcher.next::<RejectAndMatch>(
1188self.haystack.as_bytes(),
1189self.needle.as_bytes(),
1190is_long,
1191 ) {
1192 SearchStep::Reject(a, b) => {
1193// skip to next char boundary
1194let b = self.haystack.ceil_char_boundary(b);
1195searcher.position = cmp::max(b, searcher.position);
1196 SearchStep::Reject(a, b)
1197 }
1198 otherwise => otherwise,
1199 }
1200 }
1201 }
1202 }
12031204#[inline]
1205fn next_match(&mut self) -> Option<(usize, usize)> {
1206match self.searcher {
1207 StrSearcherImpl::Empty(..) => loop {
1208match self.next() {
1209 SearchStep::Match(a, b) => return Some((a, b)),
1210 SearchStep::Done => return None,
1211 SearchStep::Reject(..) => {}
1212 }
1213 },
1214 StrSearcherImpl::Byte(ref mut searcher) => {
1215let bytes = self.haystack.as_bytes();
1216if searcher.position >= bytes.len() {
1217return None;
1218 }
1219match memchr::memchr(searcher.b, &bytes[searcher.position..]) {
1220Some(i) => {
1221let pos = searcher.position + i;
1222searcher.position = pos + 1;
1223Some((pos, pos + 1))
1224 }
1225None => {
1226searcher.position = bytes.len();
1227None1228 }
1229 }
1230 }
1231 StrSearcherImpl::TwoWay(ref mut searcher) => {
1232let is_long = searcher.memory == usize::MAX;
1233// write out `true` and `false` cases to encourage the compiler
1234 // to specialize the two cases separately.
1235if is_long {
1236searcher.next::<MatchOnly>(
1237self.haystack.as_bytes(),
1238self.needle.as_bytes(),
1239true,
1240 )
1241 } else {
1242searcher.next::<MatchOnly>(
1243self.haystack.as_bytes(),
1244self.needle.as_bytes(),
1245false,
1246 )
1247 }
1248 }
1249 }
1250 }
1251}
12521253unsafe impl<'a, 'b> ReverseSearcher<'a> for StrSearcher<'a, 'b> {
1254#[inline]
1255fn next_back(&mut self) -> SearchStep {
1256match self.searcher {
1257 StrSearcherImpl::Empty(ref mut searcher) => {
1258if searcher.is_finished {
1259return SearchStep::Done;
1260 }
1261let is_match = searcher.is_match_bw;
1262searcher.is_match_bw = !searcher.is_match_bw;
1263let end = searcher.end;
1264match self.haystack[..end].chars().next_back() {
1265_ if is_match => SearchStep::Match(end, end),
1266None => {
1267searcher.is_finished = true;
1268 SearchStep::Done1269 }
1270Some(ch) => {
1271searcher.end -= ch.len_utf8();
1272 SearchStep::Reject(searcher.end, end)
1273 }
1274 }
1275 }
1276 StrSearcherImpl::Byte(ref mut searcher) => {
1277let end = searcher.end;
1278if end == 0 {
1279return SearchStep::Done;
1280 }
1281let bytes = self.haystack.as_bytes();
1282if bytes[end - 1] == searcher.b {
1283searcher.end = end - 1;
1284 SearchStep::Match(end - 1, end)
1285 } else {
1286let start = self.haystack.floor_char_boundary(end - 1);
1287searcher.end = start;
1288 SearchStep::Reject(start, end)
1289 }
1290 }
1291 StrSearcherImpl::TwoWay(ref mut searcher) => {
1292if searcher.end == 0 {
1293return SearchStep::Done;
1294 }
1295let is_long = searcher.memory == usize::MAX;
1296match searcher.next_back::<RejectAndMatch>(
1297self.haystack.as_bytes(),
1298self.needle.as_bytes(),
1299is_long,
1300 ) {
1301 SearchStep::Reject(a, b) => {
1302// skip to previous char boundary
1303let a = self.haystack.floor_char_boundary(a);
1304searcher.end = cmp::min(a, searcher.end);
1305 SearchStep::Reject(a, b)
1306 }
1307 otherwise => otherwise,
1308 }
1309 }
1310 }
1311 }
13121313#[inline]
1314fn next_match_back(&mut self) -> Option<(usize, usize)> {
1315match self.searcher {
1316 StrSearcherImpl::Empty(..) => loop {
1317match self.next_back() {
1318 SearchStep::Match(a, b) => return Some((a, b)),
1319 SearchStep::Done => return None,
1320 SearchStep::Reject(..) => {}
1321 }
1322 },
1323 StrSearcherImpl::Byte(ref mut searcher) => {
1324if searcher.end == 0 {
1325return None;
1326 }
1327let bytes = self.haystack.as_bytes();
1328match memchr::memrchr(searcher.b, &bytes[..searcher.end]) {
1329Some(i) => {
1330searcher.end = i;
1331Some((i, i + 1))
1332 }
1333None => {
1334searcher.end = 0;
1335None1336 }
1337 }
1338 }
1339 StrSearcherImpl::TwoWay(ref mut searcher) => {
1340let is_long = searcher.memory == usize::MAX;
1341// write out `true` and `false`, like `next_match`
1342if is_long {
1343searcher.next_back::<MatchOnly>(
1344self.haystack.as_bytes(),
1345self.needle.as_bytes(),
1346true,
1347 )
1348 } else {
1349searcher.next_back::<MatchOnly>(
1350self.haystack.as_bytes(),
1351self.needle.as_bytes(),
1352false,
1353 )
1354 }
1355 }
1356 }
1357 }
1358}
13591360/// The internal state of the two-way substring search algorithm.
1361#[derive(#[automatically_derived]
impl crate::clone::Clone for TwoWaySearcher {
#[inline]
fn clone(&self) -> TwoWaySearcher {
TwoWaySearcher {
crit_pos: crate::clone::Clone::clone(&self.crit_pos),
crit_pos_back: crate::clone::Clone::clone(&self.crit_pos_back),
period: crate::clone::Clone::clone(&self.period),
byteset: crate::clone::Clone::clone(&self.byteset),
position: crate::clone::Clone::clone(&self.position),
end: crate::clone::Clone::clone(&self.end),
memory: crate::clone::Clone::clone(&self.memory),
memory_back: crate::clone::Clone::clone(&self.memory_back),
}
}
}Clone, #[automatically_derived]
impl crate::fmt::Debug for TwoWaySearcher {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
let names: &'static _ =
&["crit_pos", "crit_pos_back", "period", "byteset", "position",
"end", "memory", "memory_back"];
let values: &[&dyn crate::fmt::Debug] =
&[&self.crit_pos, &self.crit_pos_back, &self.period,
&self.byteset, &self.position, &self.end, &self.memory,
&&self.memory_back];
crate::fmt::Formatter::debug_struct_fields_finish(f, "TwoWaySearcher",
names, values)
}
}Debug)]
1362struct TwoWaySearcher {
1363// constants
1364/// critical factorization index
1365crit_pos: usize,
1366/// critical factorization index for reversed needle
1367crit_pos_back: usize,
1368 period: usize,
1369/// `byteset` is an extension (not part of the two way algorithm);
1370 /// it's a 64-bit "fingerprint" where each set bit `j` corresponds
1371 /// to a (byte & 63) == j present in the needle.
1372byteset: u64,
13731374// variables
1375position: usize,
1376 end: usize,
1377/// index into needle before which we have already matched
1378memory: usize,
1379/// index into needle after which we have already matched
1380memory_back: usize,
1381}
13821383/*
1384 This is the Two-Way search algorithm, which was introduced in the paper:
1385 Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.
13861387 Here's some background information.
13881389 A *word* is a string of symbols. The *length* of a word should be a familiar
1390 notion, and here we denote it for any word x by |x|.
1391 (We also allow for the possibility of the *empty word*, a word of length zero).
13921393 If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
1394 *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
1395 For example, both 1 and 2 are periods for the string "aa". As another example,
1396 the only period of the string "abcd" is 4.
13971398 We denote by period(x) the *smallest* period of x (provided that x is non-empty).
1399 This is always well-defined since every non-empty word x has at least one period,
1400 |x|. We sometimes call this *the period* of x.
14011402 If u, v and x are words such that x = uv, where uv is the concatenation of u and
1403 v, then we say that (u, v) is a *factorization* of x.
14041405 Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
1406 that both of the following hold
14071408 - either w is a suffix of u or u is a suffix of w
1409 - either w is a prefix of v or v is a prefix of w
14101411 then w is said to be a *repetition* for the factorization (u, v).
14121413 Just to unpack this, there are four possibilities here. Let w = "abc". Then we
1414 might have:
14151416 - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
1417 - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
1418 - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
1419 - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")
14201421 Note that the word vu is a repetition for any factorization (u,v) of x = uv,
1422 so every factorization has at least one repetition.
14231424 If x is a string and (u, v) is a factorization for x, then a *local period* for
1425 (u, v) is an integer r such that there is some word w such that |w| = r and w is
1426 a repetition for (u, v).
14271428 We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
1429 call this *the local period* of (u, v). Provided that x = uv is non-empty, this
1430 is well-defined (because each non-empty word has at least one factorization, as
1431 noted above).
14321433 It can be proven that the following is an equivalent definition of a local period
1434 for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
1435 all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
1436 defined. (i.e., i > 0 and i + r < |x|).
14371438 Using the above reformulation, it is easy to prove that
14391440 1 <= local_period(u, v) <= period(uv)
14411442 A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
1443 *critical factorization*.
14441445 The algorithm hinges on the following theorem, which is stated without proof:
14461447 **Critical Factorization Theorem** Any word x has at least one critical
1448 factorization (u, v) such that |u| < period(x).
14491450 The purpose of maximal_suffix is to find such a critical factorization.
14511452 If the period is short, compute another factorization x = u' v' to use
1453 for reverse search, chosen instead so that |v'| < period(x).
14541455*/
1456impl TwoWaySearcher {
1457fn new(needle: &[u8], end: usize) -> TwoWaySearcher {
1458let (crit_pos_false, period_false) = TwoWaySearcher::maximal_suffix(needle, false);
1459let (crit_pos_true, period_true) = TwoWaySearcher::maximal_suffix(needle, true);
14601461let (crit_pos, period) = if crit_pos_false > crit_pos_true {
1462 (crit_pos_false, period_false)
1463 } else {
1464 (crit_pos_true, period_true)
1465 };
14661467// A particularly readable explanation of what's going on here can be found
1468 // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
1469 // see the code for "Algorithm CP" on p. 323.
1470 //
1471 // What's going on is we have some critical factorization (u, v) of the
1472 // needle, and we want to determine whether u is a suffix of
1473 // &v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
1474 // "Algorithm CP2", which is optimized for when the period of the needle
1475 // is large.
1476if needle[..crit_pos] == needle[period..period + crit_pos] {
1477// short period case -- the period is exact
1478 // compute a separate critical factorization for the reversed needle
1479 // x = u' v' where |v'| < period(x).
1480 //
1481 // This is sped up by the period being known already.
1482 // Note that a case like x = "acba" may be factored exactly forwards
1483 // (crit_pos = 1, period = 3) while being factored with approximate
1484 // period in reverse (crit_pos = 2, period = 2). We use the given
1485 // reverse factorization but keep the exact period.
1486let crit_pos_back = needle.len()
1487 - cmp::max(
1488TwoWaySearcher::reverse_maximal_suffix(needle, period, false),
1489TwoWaySearcher::reverse_maximal_suffix(needle, period, true),
1490 );
14911492TwoWaySearcher {
1493crit_pos,
1494crit_pos_back,
1495period,
1496 byteset: Self::byteset_create(&needle[..period]),
14971498 position: 0,
1499end,
1500 memory: 0,
1501 memory_back: needle.len(),
1502 }
1503 } else {
1504// long period case -- we have an approximation to the actual period,
1505 // and don't use memorization.
1506 //
1507 // Approximate the period by lower bound max(|u|, |v|) + 1.
1508 // The critical factorization is efficient to use for both forward and
1509 // reverse search.
15101511TwoWaySearcher {
1512crit_pos,
1513 crit_pos_back: crit_pos,
1514 period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
1515 byteset: Self::byteset_create(needle),
15161517 position: 0,
1518end,
1519 memory: usize::MAX, // Dummy value to signify that the period is long
1520memory_back: usize::MAX,
1521 }
1522 }
1523 }
15241525#[inline]
1526fn byteset_create(bytes: &[u8]) -> u64 {
1527bytes.iter().fold(0, |a, &b| (1 << (b & 0x3f)) | a)
1528 }
15291530#[inline]
1531fn byteset_contains(&self, byte: u8) -> bool {
1532 (self.byteset >> ((byte & 0x3f) as usize)) & 1 != 0
1533}
15341535// One of the main ideas of Two-Way is that we factorize the needle into
1536 // two halves, (u, v), and begin trying to find v in the haystack by scanning
1537 // left to right. If v matches, we try to match u by scanning right to left.
1538 // How far we can jump when we encounter a mismatch is all based on the fact
1539 // that (u, v) is a critical factorization for the needle.
1540#[inline]
1541fn next<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> S::Output
1542where
1543S: TwoWayStrategy,
1544 {
1545// `next()` uses `self.position` as its cursor
1546let old_pos = self.position;
1547let needle_last = needle.len() - 1;
1548'search: loop {
1549// Check that we have room to search in
1550 // position + needle_last can not overflow if we assume slices
1551 // are bounded by isize's range.
1552let tail_byte = match haystack.get(self.position + needle_last) {
1553Some(&b) => b,
1554None => {
1555self.position = haystack.len();
1556return S::rejecting(old_pos, self.position);
1557 }
1558 };
15591560if S::use_early_reject() && old_pos != self.position {
1561return S::rejecting(old_pos, self.position);
1562 }
15631564// Quickly skip by large portions unrelated to our substring
1565if !self.byteset_contains(tail_byte) {
1566self.position += needle.len();
1567if !long_period {
1568self.memory = 0;
1569 }
1570continue 'search;
1571 }
15721573// See if the right part of the needle matches
1574let start =
1575if long_period { self.crit_pos } else { cmp::max(self.crit_pos, self.memory) };
1576for i in start..needle.len() {
1577// SAFETY: on every iteration of `'search`, the `haystack.get(self.position + needle_last)`
1578 // check returned `Some`, so `self.position + needle_last < haystack.len()`.
1579 // Since `i < needle.len()` implies `i <= needle_last`, we have
1580 // `self.position + i < haystack.len()`.
1581 // Every path that mutates `self.position` below either returns or re-enters `'search`,
1582 // which re-runs the check before reaching the loop again.
1583if needle[i] != unsafe { *haystack.get_unchecked(self.position + i) } {
1584self.position += i - self.crit_pos + 1;
1585if !long_period {
1586self.memory = 0;
1587 }
1588continue 'search;
1589 }
1590 }
15911592// See if the left part of the needle matches
1593let start = if long_period { 0 } else { self.memory };
1594for i in (start..self.crit_pos).rev() {
1595// SAFETY: on every iteration of `'search`, the `haystack.get(self.position + needle_last)`
1596 // check returned `Some`, so `self.position + needle_last < haystack.len()`.
1597 // Since `i < self.crit_pos <= needle.len()`, we have `i <= needle_last`, and thus
1598 // `self.position + i <= self.position + needle_last < haystack.len()`.
1599 // Every path that mutates `self.position` below either returns or re-enters `'search`,
1600 // which re-runs the check before reaching the loop again.
1601if needle[i] != unsafe { *haystack.get_unchecked(self.position + i) } {
1602self.position += self.period;
1603if !long_period {
1604self.memory = needle.len() - self.period;
1605 }
1606continue 'search;
1607 }
1608 }
16091610// We have found a match!
1611let match_pos = self.position;
16121613// Note: add self.period instead of needle.len() to have overlapping matches
1614self.position += needle.len();
1615if !long_period {
1616self.memory = 0; // set to needle.len() - self.period for overlapping matches
1617}
16181619return S::matching(match_pos, match_pos + needle.len());
1620 }
1621 }
16221623// Follows the ideas in `next()`.
1624 //
1625 // The definitions are symmetrical, with period(x) = period(reverse(x))
1626 // and local_period(u, v) = local_period(reverse(v), reverse(u)), so if (u, v)
1627 // is a critical factorization, so is (reverse(v), reverse(u)).
1628 //
1629 // For the reverse case we have computed a critical factorization x = u' v'
1630 // (field `crit_pos_back`). We need |u| < period(x) for the forward case and
1631 // thus |v'| < period(x) for the reverse.
1632 //
1633 // To search in reverse through the haystack, we search forward through
1634 // a reversed haystack with a reversed needle, matching first u' and then v'.
1635#[inline]
1636fn next_back<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> S::Output
1637where
1638S: TwoWayStrategy,
1639 {
1640// `next_back()` uses `self.end` as its cursor -- so that `next()` and `next_back()`
1641 // are independent.
1642let old_end = self.end;
1643'search: loop {
1644// Check that we have room to search in
1645 // end - needle.len() will wrap around when there is no more room,
1646 // but due to slice length limits it can never wrap all the way back
1647 // into the length of haystack.
1648let front_byte = match haystack.get(self.end.wrapping_sub(needle.len())) {
1649Some(&b) => b,
1650None => {
1651self.end = 0;
1652return S::rejecting(0, old_end);
1653 }
1654 };
16551656if S::use_early_reject() && old_end != self.end {
1657return S::rejecting(self.end, old_end);
1658 }
16591660// Quickly skip by large portions unrelated to our substring
1661if !self.byteset_contains(front_byte) {
1662self.end -= needle.len();
1663if !long_period {
1664self.memory_back = needle.len();
1665 }
1666continue 'search;
1667 }
16681669// See if the left part of the needle matches
1670let crit = if long_period {
1671self.crit_pos_back
1672 } else {
1673 cmp::min(self.crit_pos_back, self.memory_back)
1674 };
1675for i in (0..crit).rev() {
1676// SAFETY: On every iteration of `'search`, `haystack.get(self.end.wrapping_sub(needle.len()))`
1677 // returned `Some`, so `self.end >= needle.len()` and `self.end - needle.len() < haystack.len()`.
1678 // Since `self.end <= haystack.len()` and `i < needle.len()`, we have
1679 // `self.end - needle.len() + i < self.end <= haystack.len()`, so
1680 // `haystack.get_unchecked(self.end - needle.len() + i)` is safe.
1681 // - The path that mutates `self.end` either re-enters `'search`, which re-runs the checks
1682 // before reaching this loop again, or returns on match, so the invariant holds.
1683if needle[i] != unsafe { *haystack.get_unchecked(self.end - needle.len() + i) } {
1684self.end -= self.crit_pos_back - i;
1685if !long_period {
1686self.memory_back = needle.len();
1687 }
1688continue 'search;
1689 }
1690 }
16911692// See if the right part of the needle matches
1693let needle_end = if long_period { needle.len() } else { self.memory_back };
1694for i in self.crit_pos_back..needle_end {
1695// SAFETY: The same `self.end - needle.len() + i < haystack.len()` argument as the
1696 // left-part loop applies: the `haystack.get(self.end.wrapping_sub(needle.len()))`
1697 // check at the top of `'search` established the bound for this iteration, and
1698 // every mutation of `self.end` is followed by `continue 'search` (which re-runs
1699 // the check) or a `return` (which exits before any further unsafe access).
1700if needle[i] != unsafe { *haystack.get_unchecked(self.end - needle.len() + i) } {
1701self.end -= self.period;
1702if !long_period {
1703self.memory_back = self.period;
1704 }
1705continue 'search;
1706 }
1707 }
17081709// We have found a match!
1710let match_pos = self.end - needle.len();
1711// Note: sub self.period instead of needle.len() to have overlapping matches
1712self.end -= needle.len();
1713if !long_period {
1714self.memory_back = needle.len();
1715 }
17161717return S::matching(match_pos, match_pos + needle.len());
1718 }
1719 }
17201721// Compute the maximal suffix of `arr`.
1722 //
1723 // The maximal suffix is a possible critical factorization (u, v) of `arr`.
1724 //
1725 // Returns (`i`, `p`) where `i` is the starting index of v and `p` is the
1726 // period of v.
1727 //
1728 // `order_greater` determines if lexical order is `<` or `>`. Both
1729 // orders must be computed -- the ordering with the largest `i` gives
1730 // a critical factorization.
1731 //
1732 // For long period cases, the resulting period is not exact (it is too short).
1733#[inline]
1734fn maximal_suffix(arr: &[u8], order_greater: bool) -> (usize, usize) {
1735let mut left = 0; // Corresponds to i in the paper
1736let mut right = 1; // Corresponds to j in the paper
1737let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1738 // to match 0-based indexing.
1739let mut period = 1; // Corresponds to p in the paper
17401741while let Some(&a) = arr.get(right + offset) {
1742// `left` will be inbounds when `right` is.
1743let b = arr[left + offset];
1744if (a < b && !order_greater) || (a > b && order_greater) {
1745// Suffix is smaller, period is entire prefix so far.
1746right += offset + 1;
1747 offset = 0;
1748 period = right - left;
1749 } else if a == b {
1750// Advance through repetition of the current period.
1751if offset + 1 == period {
1752 right += offset + 1;
1753 offset = 0;
1754 } else {
1755 offset += 1;
1756 }
1757 } else {
1758// Suffix is larger, start over from current location.
1759left = right;
1760 right += 1;
1761 offset = 0;
1762 period = 1;
1763 }
1764 }
1765 (left, period)
1766 }
17671768// Compute the maximal suffix of the reverse of `arr`.
1769 //
1770 // The maximal suffix is a possible critical factorization (u', v') of `arr`.
1771 //
1772 // Returns `i` where `i` is the starting index of v', from the back;
1773 // returns immediately when a period of `known_period` is reached.
1774 //
1775 // `order_greater` determines if lexical order is `<` or `>`. Both
1776 // orders must be computed -- the ordering with the largest `i` gives
1777 // a critical factorization.
1778 //
1779 // For long period cases, the resulting period is not exact (it is too short).
1780fn reverse_maximal_suffix(arr: &[u8], known_period: usize, order_greater: bool) -> usize {
1781let mut left = 0; // Corresponds to i in the paper
1782let mut right = 1; // Corresponds to j in the paper
1783let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1784 // to match 0-based indexing.
1785let mut period = 1; // Corresponds to p in the paper
1786let n = arr.len();
17871788while right + offset < n {
1789let a = arr[n - (1 + right + offset)];
1790let b = arr[n - (1 + left + offset)];
1791if (a < b && !order_greater) || (a > b && order_greater) {
1792// Suffix is smaller, period is entire prefix so far.
1793right += offset + 1;
1794 offset = 0;
1795 period = right - left;
1796 } else if a == b {
1797// Advance through repetition of the current period.
1798if offset + 1 == period {
1799 right += offset + 1;
1800 offset = 0;
1801 } else {
1802 offset += 1;
1803 }
1804 } else {
1805// Suffix is larger, start over from current location.
1806left = right;
1807 right += 1;
1808 offset = 0;
1809 period = 1;
1810 }
1811if period == known_period {
1812break;
1813 }
1814 }
1815if true {
if !(period <= known_period) {
crate::panicking::panic("assertion failed: period <= known_period")
};
};debug_assert!(period <= known_period);
1816left1817 }
1818}
18191820// TwoWayStrategy allows the algorithm to either skip non-matches as quickly
1821// as possible, or to work in a mode where it emits Rejects relatively quickly.
1822trait TwoWayStrategy {
1823type Output;
1824fn use_early_reject() -> bool;
1825fn rejecting(a: usize, b: usize) -> Self::Output;
1826fn matching(a: usize, b: usize) -> Self::Output;
1827}
18281829/// Skip to match intervals as quickly as possible
1830enum MatchOnly {}
18311832impl TwoWayStrategyfor MatchOnly {
1833type Output = Option<(usize, usize)>;
18341835#[inline]
1836fn use_early_reject() -> bool {
1837false
1838}
1839#[inline]
1840fn rejecting(_a: usize, _b: usize) -> Self::Output {
1841None1842 }
1843#[inline]
1844fn matching(a: usize, b: usize) -> Self::Output {
1845Some((a, b))
1846 }
1847}
18481849/// Emit Rejects regularly
1850enum RejectAndMatch {}
18511852impl TwoWayStrategyfor RejectAndMatch {
1853type Output = SearchStep;
18541855#[inline]
1856fn use_early_reject() -> bool {
1857true
1858}
1859#[inline]
1860fn rejecting(a: usize, b: usize) -> Self::Output {
1861 SearchStep::Reject(a, b)
1862 }
1863#[inline]
1864fn matching(a: usize, b: usize) -> Self::Output {
1865 SearchStep::Match(a, b)
1866 }
1867}
18681869/// SIMD search for short needles based on
1870/// Wojciech Muła's "SIMD-friendly algorithms for substring searching"[0]
1871///
1872/// It skips ahead by the vector width on each iteration (rather than the needle length as two-way
1873/// does) by probing the first and last byte of the needle for the whole vector width
1874/// and only doing full needle comparisons when the vectorized probe indicated potential matches.
1875///
1876/// Since the x86_64 baseline only offers SSE2 we only use u8x16 here.
1877/// If we ever ship std with for x86-64-v3 or adapt this for other platforms then wider vectors
1878/// should be evaluated.
1879///
1880/// Similarly, on LoongArch the 128-bit LSX vector extension is the baseline,
1881/// so we also use `u8x16` there. Wider vector widths may be considered
1882/// for future LoongArch extensions (e.g., LASX).
1883///
1884/// For haystacks smaller than vector-size + needle length it falls back to
1885/// a naive O(n*m) search so this implementation should not be called on larger needles.
1886///
1887/// [0]: http://0x80.pl/articles/simd-strfind.html#sse-avx2
1888#[cfg(any(
1889 all(target_arch = "x86_64", target_feature = "sse2"),
1890 all(target_arch = "loongarch64", target_feature = "lsx"),
1891 all(target_arch = "aarch64", target_feature = "neon")
1892))]
1893#[inline]
1894fn simd_contains(needle: &str, haystack: &str) -> Option<bool> {
1895let needle = needle.as_bytes();
1896let haystack = haystack.as_bytes();
18971898if true {
if !(needle.len() > 1) {
crate::panicking::panic("assertion failed: needle.len() > 1")
};
};debug_assert!(needle.len() > 1);
18991900use crate::ops::BitAnd;
1901use crate::simd::cmp::SimdPartialEq;
1902use crate::simd::{mask8x16as Mask, u8x16as Block};
19031904let first_probe = needle[0];
1905let last_byte_offset = needle.len() - 1;
19061907// the offset used for the 2nd vector
1908let second_probe_offset = if needle.len() == 2 {
1909// never bail out on len=2 needles because the probes will fully cover them and have
1910 // no degenerate cases.
19111
1912} else {
1913// try a few bytes in case first and last byte of the needle are the same
1914let Some(second_probe_offset) =
1915 (needle.len().saturating_sub(4)..needle.len()).rfind(|&idx| needle[idx] != first_probe)
1916else {
1917// fall back to other search methods if we can't find any different bytes
1918 // since we could otherwise hit some degenerate cases
1919return None;
1920 };
1921second_probe_offset1922 };
19231924// do a naive search if the haystack is too small to fit
1925if haystack.len() < Block::LEN + last_byte_offset {
1926return Some(haystack.windows(needle.len()).any(|c| c == needle));
1927 }
19281929let first_probe: Block = Block::splat(first_probe);
1930let second_probe: Block = Block::splat(needle[second_probe_offset]);
1931// first byte are already checked by the outer loop. to verify a match only the
1932 // remainder has to be compared.
1933let trimmed_needle = &needle[1..];
19341935// this #[cold] is load-bearing, benchmark before removing it...
1936let check_mask = #[cold]
1937|idx, mask: u16, skip: bool| -> bool {
1938if skip {
1939return false;
1940 }
19411942// and so is this. optimizations are weird.
1943let mut mask = mask;
19441945while mask != 0 {
1946let trailing = mask.trailing_zeros();
1947let offset = idx + trailing as usize + 1;
1948// SAFETY: mask is between 0 and 15 trailing zeroes, we skip one additional byte that was already compared
1949 // and then take trimmed_needle.len() bytes. This is within the bounds defined by the outer loop
1950unsafe {
1951let sub = haystack.get_unchecked(offset..).get_unchecked(..trimmed_needle.len());
1952if small_slice_eq(sub, trimmed_needle) {
1953return true;
1954 }
1955 }
1956 mask &= !(1 << trailing);
1957 }
1958false
1959};
19601961let test_chunk = |idx| -> u16 {
1962// SAFETY: this requires at least LANES bytes being readable at idx
1963 // that is ensured by the loop ranges (see comments below)
1964let a: Block = unsafe { haystack.as_ptr().add(idx).cast::<Block>().read_unaligned() };
1965// SAFETY: this requires LANES + block_offset bytes being readable at idx
1966let b: Block = unsafe {
1967haystack.as_ptr().add(idx).add(second_probe_offset).cast::<Block>().read_unaligned()
1968 };
1969let eq_first: Mask = a.simd_eq(first_probe);
1970let eq_last: Mask = b.simd_eq(second_probe);
1971let both = eq_first.bitand(eq_last);
1972both.to_bitmask() as u161973 };
19741975let mut i = 0;
1976let mut result = false;
1977// The loop condition must ensure that there's enough headroom to read LANE bytes,
1978 // and not only at the current index but also at the index shifted by block_offset
1979const UNROLL: usize = 4;
1980while i + last_byte_offset + UNROLL * Block::LEN < haystack.len() && !result {
1981let mut masks = [0u16; UNROLL];
1982for j in 0..UNROLL {
1983 masks[j] = test_chunk(i + j * Block::LEN);
1984 }
1985for j in 0..UNROLL {
1986let mask = masks[j];
1987if mask != 0 {
1988 result |= check_mask(i + j * Block::LEN, mask, result);
1989 }
1990 }
1991 i += UNROLL * Block::LEN;
1992 }
1993while i + last_byte_offset + Block::LEN < haystack.len() && !result {
1994let mask = test_chunk(i);
1995if mask != 0 {
1996 result |= check_mask(i, mask, result);
1997 }
1998 i += Block::LEN;
1999 }
20002001// Process the tail that didn't fit into LANES-sized steps.
2002 // This simply repeats the same procedure but as right-aligned chunk instead
2003 // of a left-aligned one. The last byte must be exactly flush with the string end so
2004 // we don't miss a single byte or read out of bounds.
2005let i = haystack.len() - last_byte_offset - Block::LEN;
2006let mask = test_chunk(i);
2007if mask != 0 {
2008result |= check_mask(i, mask, result);
2009 }
20102011Some(result)
2012}
20132014/// Compares short slices for equality.
2015///
2016/// It avoids a call to libc's memcmp which is faster on long slices
2017/// due to SIMD optimizations but it incurs a function call overhead.
2018///
2019/// # Safety
2020///
2021/// Both slices must have the same length.
2022#[cfg(any(
2023 all(target_arch = "x86_64", target_feature = "sse2"),
2024 all(target_arch = "loongarch64", target_feature = "lsx"),
2025 all(target_arch = "aarch64", target_feature = "neon")
2026))]
2027#[inline]
2028unsafe fn small_slice_eq(x: &[u8], y: &[u8]) -> bool {
2029if true {
{
match (&x.len(), &y.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = crate::panicking::AssertKind::Eq;
crate::panicking::assert_failed(kind, &*left_val,
&*right_val, crate::option::Option::None);
}
}
}
};
};debug_assert_eq!(x.len(), y.len());
2030// This function is adapted from
2031 // https://github.com/BurntSushi/memchr/blob/8037d11b4357b0f07be2bb66dc2659d9cf28ad32/src/memmem/util.rs#L32
20322033 // If we don't have enough bytes to do 4-byte at a time loads, then
2034 // fall back to the naive slow version.
2035 //
2036 // Potential alternative: We could do a copy_nonoverlapping combined with a mask instead
2037 // of a loop. Benchmark it.
2038if x.len() < 4 {
2039for (&b1, &b2) in x.iter().zip(y) {
2040if b1 != b2 {
2041return false;
2042 }
2043 }
2044return true;
2045 }
2046// When we have 4 or more bytes to compare, then proceed in chunks of 4 at
2047 // a time using unaligned loads.
2048 //
2049 // Also, why do 4 byte loads instead of, say, 8 byte loads? The reason is
2050 // that this particular version of memcmp is likely to be called with tiny
2051 // needles. That means that if we do 8 byte loads, then a higher proportion
2052 // of memcmp calls will use the slower variant above. With that said, this
2053 // is a hypothesis and is only loosely supported by benchmarks. There's
2054 // likely some improvement that could be made here. The main thing here
2055 // though is to optimize for latency, not throughput.
20562057 // SAFETY: Via the conditional above, we know that both `px` and `py`
2058 // have the same length, so `px < pxend` implies that `py < pyend`.
2059 // Thus, dereferencing both `px` and `py` in the loop below is safe.
2060 //
2061 // Moreover, we set `pxend` and `pyend` to be 4 bytes before the actual
2062 // end of `px` and `py`. Thus, the final dereference outside of the
2063 // loop is guaranteed to be valid. (The final comparison will overlap with
2064 // the last comparison done in the loop for lengths that aren't multiples
2065 // of four.)
2066 //
2067 // Finally, we needn't worry about alignment here, since we do unaligned
2068 // loads.
2069unsafe {
2070let (mut px, mut py) = (x.as_ptr(), y.as_ptr());
2071let (pxend, pyend) = (px.add(x.len() - 4), py.add(y.len() - 4));
2072while px < pxend {
2073let vx = (px as *const u32).read_unaligned();
2074let vy = (py as *const u32).read_unaligned();
2075if vx != vy {
2076return false;
2077 }
2078 px = px.add(4);
2079 py = py.add(4);
2080 }
2081let vx = (pxendas *const u32).read_unaligned();
2082let vy = (pyendas *const u32).read_unaligned();
2083vx == vy2084 }
2085}