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/// # Safety
74///
75/// Implementers must uphold the guarantees documented on `into_searcher`.
76///
77/// # Examples
78///
79/// ```
80/// // &str
81/// assert_eq!("abaaa".find("ba"), Some(1));
82/// assert_eq!("abaaa".find("bac"), None);
83///
84/// // char
85/// assert_eq!("abaaa".find('a'), Some(0));
86/// assert_eq!("abaaa".find('b'), Some(1));
87/// assert_eq!("abaaa".find('c'), None);
88///
89/// // &[char; N]
90/// assert_eq!("ab".find(&['b', 'a']), Some(0));
91/// assert_eq!("abaaa".find(&['a', 'z']), Some(0));
92/// assert_eq!("abaaa".find(&['c', 'd']), None);
93///
94/// // &[char]
95/// assert_eq!("ab".find(&['b', 'a'][..]), Some(0));
96/// assert_eq!("abaaa".find(&['a', 'z'][..]), Some(0));
97/// assert_eq!("abaaa".find(&['c', 'd'][..]), None);
98///
99/// // FnMut(char) -> bool
100/// assert_eq!("abcdef_z".find(|ch| ch > 'd' && ch < 'y'), Some(4));
101/// assert_eq!("abcddd_z".find(|ch| ch > 'd' && ch < 'y'), None);
102/// ```
103pub unsafe trait Pattern: Sized {
104/// Associated searcher for this pattern
105type Searcher<'a>: Searcher<'a>;
106107/// Constructs the associated searcher from
108 /// `self` and the `haystack` to search in.
109 ///
110 /// # Guarantees
111 ///
112 /// - The returned searcher must search the provided `haystack`.
113 /// In particular, [`Searcher::haystack()`] must return the
114 /// same string slice passed to this method.
115fn into_searcher(self, haystack: &str) -> Self::Searcher<'_>;
116117/// Checks whether the pattern matches anywhere in the haystack
118#[inline]
119fn is_contained_in(self, haystack: &str) -> bool {
120self.into_searcher(haystack).next_match().is_some()
121 }
122123/// Checks whether the pattern matches at the front of the haystack
124#[inline]
125fn is_prefix_of(self, haystack: &str) -> bool {
126#[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, _))127 }
128129/// Checks whether the pattern matches at the back of the haystack
130#[inline]
131fn is_suffix_of<'a>(self, haystack: &'a str) -> bool132where
133Self::Searcher<'a>: ReverseSearcher<'a>,
134 {
135#[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)136 }
137138/// Removes the pattern from the front of haystack, if it matches.
139#[inline]
140fn strip_prefix_of(self, haystack: &str) -> Option<&str> {
141if let SearchStep::Match(start, len) = self.into_searcher(haystack).next() {
142if 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!(
143 start, 0,
144"The first search step from Searcher \
145 must include the first character"
146);
147// SAFETY: `Searcher` is known to return valid indices.
148unsafe { Some(haystack.get_unchecked(len..)) }
149 } else {
150None151 }
152 }
153154/// Removes the pattern from the back of haystack, if it matches.
155#[inline]
156fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str>
157where
158Self::Searcher<'a>: ReverseSearcher<'a>,
159 {
160if let SearchStep::Match(start, end) = self.into_searcher(haystack).next_back() {
161if 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!(
162 end,
163 haystack.len(),
164"The first search step from ReverseSearcher \
165 must include the last character"
166);
167// SAFETY: `Searcher` is known to return valid indices.
168unsafe { Some(haystack.get_unchecked(..start)) }
169 } else {
170None171 }
172 }
173174/// Returns the pattern as UTF-8 if possible.
175fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>> {
176None177 }
178}
179/// Result of calling [`Pattern::as_utf8_pattern()`].
180/// Can be used for inspecting the contents of a [`Pattern`] in cases
181/// where the underlying representation can be represented as UTF-8.
182#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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: &Self) -> bool {
crate::intrinsics::discriminant_value(self) ==
crate::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::StringPattern(__self_0), Self::StringPattern(__arg1_0))
=> __self_0 == __arg1_0,
(Self::CharPattern(__self_0), Self::CharPattern(__arg1_0)) =>
__self_0 == __arg1_0,
_ => unsafe { crate::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]impl<'a> crate::fmt::Debug for Utf8Pattern<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
match self {
Self::StringPattern(__self_0) =>
crate::fmt::Formatter::debug_struct_field1_finish(f,
"StringPattern", &__self_0),
Self::CharPattern(__self_0) =>
crate::fmt::Formatter::debug_struct_field1_finish(f,
"CharPattern", &__self_0),
}
}
}Debug)]
183pub enum Utf8Pattern<'a> {
184/// Type returned by String and str types.
185 /// This stores `str` rather than bytes so callers cannot describe
186 /// non-UTF-8 string patterns through this API.
187StringPattern(&'a str),
188/// Type returned by char types.
189CharPattern(char),
190}
191192// Searcher
193194/// Result of calling [`Searcher::next()`] or [`ReverseSearcher::next_back()`].
195#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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: &Self) -> bool {
crate::intrinsics::discriminant_value(self) ==
crate::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Match(__self_0, __self_1),
Self::Match(__arg1_0, __arg1_1)) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
(Self::Reject(__self_0, __self_1),
Self::Reject(__arg1_0, __arg1_1)) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
_ => true,
}
}
}PartialEq, #[automatically_derived]impl crate::fmt::Debug for SearchStep {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
match self {
Self::Match(__self_0, __self_1) =>
crate::fmt::Formatter::debug_struct_field2_finish(f, "Match",
__self_0, &__self_1),
Self::Reject(__self_0, __self_1) =>
crate::fmt::Formatter::debug_struct_field2_finish(f, "Reject",
__self_0, &__self_1),
Self::Done => crate::fmt::Formatter::write_str(f, "Done"),
}
}
}Debug)]
196pub enum SearchStep {
197/// Expresses that a match of the pattern has been found at
198 /// `haystack[a..b]`.
199Match(usize, usize),
200/// Expresses that `haystack[a..b]` has been rejected as a possible match
201 /// of the pattern.
202 ///
203 /// Note that there might be more than one `Reject` between two `Match`es,
204 /// there is no requirement for them to be combined into one.
205Reject(usize, usize),
206/// Expresses that every byte of the haystack has been visited, ending
207 /// the iteration.
208Done,
209}
210211/// A searcher for a string pattern.
212///
213/// This trait provides methods for searching for non-overlapping
214/// matches of a pattern starting from the front (left) of a string.
215///
216/// It will be implemented by associated `Searcher`
217/// types of the [`Pattern`] trait.
218///
219/// # Safety
220///
221/// Implementers must ensure that all trait functions abide by the
222/// guarantees documented in the `# Guarantees` sections. The provided
223/// methods automatically satisfy their guarantees.
224pub unsafe trait Searcher<'a> {
225/// Getter for the underlying string to be searched in
226 ///
227 /// # Guarantees
228 ///
229 /// Will always return the same [`&str`][str].
230fn haystack(&self) -> &'a str;
231232/// Performs the next search step starting from the front.
233 ///
234 /// - Returns [`Match(a, b)`][SearchStep::Match] if `haystack[a..b]` matches
235 /// the pattern.
236 /// - Returns [`Reject(a, b)`][SearchStep::Reject] if `haystack[a..b]` can
237 /// not match the pattern, even partially.
238 /// - Returns [`Done`][SearchStep::Done] if every byte of the haystack has
239 /// been visited.
240 ///
241 /// # Guarantees
242 ///
243 /// - The stream of [`Match`][SearchStep::Match] and
244 /// [`Reject`][SearchStep::Reject] values up to a [`Done`][SearchStep::Done]
245 /// will contain index ranges that are adjacent, non-overlapping,
246 /// covering the whole haystack, and lying on utf8 boundaries. This enables
247 /// consumers of this trait to slice the haystack without additional runtime checks.
248 ///
249 /// A [`Match`][SearchStep::Match] result needs to contain the whole matched
250 /// pattern, however [`Reject`][SearchStep::Reject] results may be split up
251 /// into arbitrary many adjacent fragments. Both ranges may have zero length.
252 ///
253 /// As an example, the pattern `"aaa"` and the haystack `"cbaaaaab"`
254 /// might produce the stream
255 /// `[Reject(0, 1), Reject(1, 2), Match(2, 5), Reject(5, 8)]`
256fn next(&mut self) -> SearchStep;
257258/// Finds the next [`Match`][SearchStep::Match] result. See [`next()`][Searcher::next].
259 ///
260 /// # Guarantees
261 ///
262 /// - Every returned `Some((a, b))` must satisfy `a <= b <= self.haystack().len()`,
263 /// and both endpoints must lie on UTF-8 character boundaries.
264 /// - Matched ranges must be returned in forward order, without revisiting
265 /// previously consumed portions of the haystack.
266 ///
267 /// Unlike [`next()`][Searcher::next], there is no guarantee that the returned ranges
268 /// of this and [`next_reject`][Searcher::next_reject] will not overlap. This will return
269 /// `(start_match, end_match)`, where start_match is the index of where
270 /// the match begins, and end_match is the index after the end of the match.
271#[inline]
272fn next_match(&mut self) -> Option<(usize, usize)> {
273loop {
274match self.next() {
275 SearchStep::Match(a, b) => return Some((a, b)),
276 SearchStep::Done => return None,
277_ => continue,
278 }
279 }
280 }
281282/// Finds the next [`Reject`][SearchStep::Reject] result. See [`next()`][Searcher::next]
283 /// and [`next_match()`][Searcher::next_match].
284 ///
285 /// # Guarantees
286 ///
287 /// - Every returned `Some((a, b))` must satisfy `a <= b <= self.haystack().len()`,
288 /// and both endpoints must lie on UTF-8 character boundaries.
289 /// - Matched ranges must be returned in forward order, without revisiting
290 /// previously consumed portions of the haystack.
291 ///
292 /// Unlike [`next()`][Searcher::next], there is no guarantee that the returned ranges
293 /// of this and [`next_match`][Searcher::next_match] will overlap.
294#[inline]
295fn next_reject(&mut self) -> Option<(usize, usize)> {
296loop {
297match self.next() {
298 SearchStep::Reject(a, b) => return Some((a, b)),
299 SearchStep::Done => return None,
300_ => continue,
301 }
302 }
303 }
304}
305306/// A reverse searcher for a string pattern.
307///
308/// This trait provides methods for searching for non-overlapping
309/// matches of a pattern starting from the back (right) of a string.
310///
311/// It will be implemented by associated [`Searcher`]
312/// types of the [`Pattern`] trait if the pattern supports searching
313/// for it from the back.
314///
315/// The index ranges returned by this trait are not required
316/// to exactly match those of the forward search in reverse.
317///
318/// # Safety
319///
320/// Implementers must ensure that all trait functions abide by the
321/// guarantees documented in the `# Guarantees` sections. The provided
322/// methods automatically satisfy their guarantees.
323pub unsafe trait ReverseSearcher<'a>: Searcher<'a> {
324/// Performs the next search step starting from the back.
325 ///
326 /// - Returns [`Match(a, b)`][SearchStep::Match] if `haystack[a..b]`
327 /// matches the pattern.
328 /// - Returns [`Reject(a, b)`][SearchStep::Reject] if `haystack[a..b]`
329 /// can not match the pattern, even partially.
330 /// - Returns [`Done`][SearchStep::Done] if every byte of the haystack
331 /// has been visited
332 ///
333 /// # Guarantees
334 ///
335 /// - The stream of [`Match`][SearchStep::Match] and
336 /// [`Reject`][SearchStep::Reject] values up to a [`Done`][SearchStep::Done]
337 /// will contain index ranges that are adjacent, non-overlapping,
338 /// covering the whole haystack, and lying on utf8 boundaries.
339 ///
340 /// A [`Match`][SearchStep::Match] result needs to contain the whole matched
341 /// pattern, however [`Reject`][SearchStep::Reject] results may be split up
342 /// into arbitrary many adjacent fragments. Both ranges may have zero length.
343 ///
344 /// As an example, the pattern `"aaa"` and the haystack `"cbaaaaab"`
345 /// might produce the stream
346 /// `[Reject(7, 8), Match(4, 7), Reject(1, 4), Reject(0, 1)]`.
347fn next_back(&mut self) -> SearchStep;
348349/// Finds the next [`Match`][SearchStep::Match] result. See [`next_back()`][ReverseSearcher::next_back].
350 ///
351 /// # Guarantees
352 ///
353 /// - Every returned `Some((a, b))` must satisfy `a <= b <= self.haystack().len()`,
354 /// and both endpoints must lie on UTF-8 character boundaries.
355 /// - Matched ranges must be returned in forward order, without revisiting
356 /// previously consumed portions of the haystack.
357#[inline]
358fn next_match_back(&mut self) -> Option<(usize, usize)> {
359loop {
360match self.next_back() {
361 SearchStep::Match(a, b) => return Some((a, b)),
362 SearchStep::Done => return None,
363_ => continue,
364 }
365 }
366 }
367368/// Finds the next [`Reject`][SearchStep::Reject] result. See [`next_back()`][ReverseSearcher::next_back].
369 ///
370 /// # Guarantees
371 ///
372 /// - Every returned `Some((a, b))` must satisfy `a <= b <= self.haystack().len()`,
373 /// and both endpoints must lie on UTF-8 character boundaries.
374 /// - Matched ranges must be returned in forward order, without revisiting
375 /// previously consumed portions of the haystack.
376#[inline]
377fn next_reject_back(&mut self) -> Option<(usize, usize)> {
378loop {
379match self.next_back() {
380 SearchStep::Reject(a, b) => return Some((a, b)),
381 SearchStep::Done => return None,
382_ => continue,
383 }
384 }
385 }
386}
387388/// A marker trait to express that a [`ReverseSearcher`]
389/// can be used for a [`DoubleEndedIterator`] implementation.
390///
391/// For this, the impl of [`Searcher`] and [`ReverseSearcher`] need
392/// to follow these conditions:
393///
394/// - All results of `next()` need to be identical
395/// to the results of `next_back()` in reverse order.
396/// - `next()` and `next_back()` need to behave as
397/// the two ends of a range of values, that is they
398/// can not "walk past each other".
399///
400/// # Examples
401///
402/// `char::Searcher` is a `DoubleEndedSearcher` because searching for a
403/// [`char`] only requires looking at one at a time, which behaves the same
404/// from both ends.
405///
406/// `(&str)::Searcher` is not a `DoubleEndedSearcher` because
407/// the pattern `"aa"` in the haystack `"aaa"` matches as either
408/// `"[aa]a"` or `"a[aa]"`, depending on which side it is searched.
409pub trait DoubleEndedSearcher<'a>: ReverseSearcher<'a> {}
410411/////////////////////////////////////////////////////////////////////////////
412// Impl for char
413/////////////////////////////////////////////////////////////////////////////
414415/// Associated type for `<char as Pattern>::Searcher<'a>`.
416#[derive(#[automatically_derived]impl<'a> crate::clone::Clone for CharSearcher<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_struct_fields_finish(f,
"CharSearcher haystack finger finger_back needle utf8_size utf8_encoded",
&[&self.haystack, &self.finger, &self.finger_back, &self.needle,
&self.utf8_size, &&self.utf8_encoded])
}
}Debug)]
417pub struct CharSearcher<'a> {
418 haystack: &'a str,
419// safety invariant: `finger`/`finger_back` must be a valid utf8 byte index of `haystack`
420 // This invariant can be broken *within* next_match and next_match_back, however
421 // they must exit with fingers on valid code point boundaries.
422/// `finger` is the current byte index of the forward search.
423 /// Imagine that it exists before the byte at its index, i.e.
424 /// `haystack[finger]` is the first byte of the slice we must inspect during
425 /// forward searching
426finger: usize,
427/// `finger_back` is the current byte index of the reverse search.
428 /// Imagine that it exists after the byte at its index, i.e.
429 /// haystack[finger_back - 1] is the last byte of the slice we must inspect during
430 /// forward searching (and thus the first byte to be inspected when calling next_back()).
431finger_back: usize,
432/// The character being searched for
433needle: char,
434435// safety invariant: `utf8_size` must be less than 5
436/// The number of bytes `needle` takes up when encoded in utf8.
437utf8_size: u8,
438/// A utf8 encoded copy of the `needle`
439utf8_encoded: [u8; 4],
440}
441442impl CharSearcher<'_> {
443fn utf8_size(&self) -> usize {
444self.utf8_size.into()
445 }
446}
447448unsafe impl<'a> Searcher<'a> for CharSearcher<'a> {
449#[inline]
450fn haystack(&self) -> &'a str {
451self.haystack
452 }
453#[inline]
454fn next(&mut self) -> SearchStep {
455let old_finger = self.finger;
456// SAFETY: 1-4 guarantee safety of `get_unchecked`
457 // 1. `self.finger` and `self.finger_back` are kept on unicode boundaries
458 // (this is invariant)
459 // 2. `self.finger >= 0` since it starts at 0 and only increases
460 // 3. `self.finger < self.finger_back` because otherwise the char `iter`
461 // would return `SearchStep::Done`
462 // 4. `self.finger` comes before the end of the haystack because `self.finger_back`
463 // starts at the end and only decreases
464let slice = unsafe { self.haystack.get_unchecked(old_finger..self.finger_back) };
465let mut iter = slice.chars();
466let old_len = iter.iter.len();
467if let Some(ch) = iter.next() {
468// add byte offset of current character
469 // without re-encoding as utf-8
470self.finger += old_len - iter.iter.len();
471if ch == self.needle {
472 SearchStep::Match(old_finger, self.finger)
473 } else {
474 SearchStep::Reject(old_finger, self.finger)
475 }
476 } else {
477 SearchStep::Done478 }
479 }
480#[inline]
481fn next_match(&mut self) -> Option<(usize, usize)> {
482loop {
483// get the haystack after the last character found
484let bytes = self.haystack.as_bytes().get(self.finger..self.finger_back)?;
485// the last byte of the utf8 encoded needle
486 // SAFETY: we have an invariant that `utf8_size < 5`
487let last_byte = unsafe { *self.utf8_encoded.get_unchecked(self.utf8_size() - 1) };
488if let Some(index) = memchr::memchr(last_byte, bytes) {
489// The new finger is the index of the byte we found,
490 // plus one, since we memchr'd for the last byte of the character.
491 //
492 // Note that this doesn't always give us a finger on a UTF8 boundary.
493 // If we *didn't* find our character
494 // we may have indexed to the non-last byte of a 3-byte or 4-byte character.
495 // We can't just skip to the next valid starting byte because a character like
496 // ꁁ (U+A041 YI SYLLABLE PA), utf-8 `EA 81 81` will have us always find
497 // the second byte when searching for the third.
498 //
499 // However, this is totally okay. While we have the invariant that
500 // self.finger is on a UTF8 boundary, this invariant is not relied upon
501 // within this method (it is relied upon in CharSearcher::next()).
502 //
503 // We only exit this method when we reach the end of the string, or if we
504 // find something. When we find something the `finger` will be set
505 // to a UTF8 boundary.
506self.finger += index + 1;
507if self.finger >= self.utf8_size() {
508let found_char = self.finger - self.utf8_size();
509if let Some(slice) = self.haystack.as_bytes().get(found_char..self.finger) {
510if slice == &self.utf8_encoded[0..self.utf8_size()] {
511return Some((found_char, self.finger));
512 }
513 }
514 }
515 } else {
516// found nothing, exit
517self.finger = self.finger_back;
518return None;
519 }
520 }
521 }
522523// let next_reject use the default implementation from the Searcher trait
524}
525526unsafe impl<'a> ReverseSearcher<'a> for CharSearcher<'a> {
527#[inline]
528fn next_back(&mut self) -> SearchStep {
529let old_finger = self.finger_back;
530// SAFETY: see the comment for next() above
531let slice = unsafe { self.haystack.get_unchecked(self.finger..old_finger) };
532let mut iter = slice.chars();
533let old_len = iter.iter.len();
534if let Some(ch) = iter.next_back() {
535// subtract byte offset of current character
536 // without re-encoding as utf-8
537self.finger_back -= old_len - iter.iter.len();
538if ch == self.needle {
539 SearchStep::Match(self.finger_back, old_finger)
540 } else {
541 SearchStep::Reject(self.finger_back, old_finger)
542 }
543 } else {
544 SearchStep::Done545 }
546 }
547#[inline]
548fn next_match_back(&mut self) -> Option<(usize, usize)> {
549let haystack = self.haystack.as_bytes();
550loop {
551// get the haystack up to but not including the last character searched
552let bytes = haystack.get(self.finger..self.finger_back)?;
553// the last byte of the utf8 encoded needle
554 // SAFETY: we have an invariant that `utf8_size < 5`
555let last_byte = unsafe { *self.utf8_encoded.get_unchecked(self.utf8_size() - 1) };
556if let Some(index) = memchr::memrchr(last_byte, bytes) {
557// we searched a slice that was offset by self.finger,
558 // add self.finger to recoup the original index
559let index = self.finger + index;
560// memrchr will return the index of the byte we wish to
561 // find. In case of an ASCII character, this is indeed
562 // were we wish our new finger to be ("after" the found
563 // char in the paradigm of reverse iteration). For
564 // multibyte chars we need to skip down by the number of more
565 // bytes they have than ASCII
566let shift = self.utf8_size() - 1;
567if index >= shift {
568let found_char = index - shift;
569if let Some(slice) = haystack.get(found_char..(found_char + self.utf8_size())) {
570if slice == &self.utf8_encoded[0..self.utf8_size()] {
571// move finger to before the character found (i.e., at its start index)
572self.finger_back = found_char;
573return Some((self.finger_back, self.finger_back + self.utf8_size()));
574 }
575 }
576 }
577// We can't use finger_back = index - size + 1 here. If we found the last char
578 // of a different-sized character (or the middle byte of a different character)
579 // we need to bump the finger_back down to `index`. This similarly makes
580 // `finger_back` have the potential to no longer be on a boundary,
581 // but this is OK since we only exit this function on a boundary
582 // or when the haystack has been searched completely.
583 //
584 // Unlike next_match this does not
585 // have the problem of repeated bytes in utf-8 because
586 // we're searching for the last byte, and we can only have
587 // found the last byte when searching in reverse.
588self.finger_back = index;
589 } else {
590self.finger_back = self.finger;
591// found nothing, exit
592return None;
593 }
594 }
595 }
596597// let next_reject_back use the default implementation from the Searcher trait
598}
599600impl<'a> DoubleEndedSearcher<'a> for CharSearcher<'a> {}
601602/// Searches for chars that are equal to a given [`char`].
603///
604/// # Examples
605///
606/// ```
607/// assert_eq!("Hello world".find('o'), Some(4));
608/// ```
609unsafe impl Patternfor char {
610type Searcher<'a> = CharSearcher<'a>;
611612#[inline]
613fn into_searcher<'a>(self, haystack: &'a str) -> Self::Searcher<'a> {
614let mut utf8_encoded = [0; char::MAX_LEN_UTF8];
615let utf8_size = self616 .encode_utf8(&mut utf8_encoded)
617 .len()
618 .try_into()
619 .expect("char len should be less than 255");
620621CharSearcher {
622haystack,
623 finger: 0,
624 finger_back: haystack.len(),
625 needle: self,
626utf8_size,
627utf8_encoded,
628 }
629 }
630631#[inline]
632fn is_contained_in(self, haystack: &str) -> bool {
633if (selfas u32) < 128 {
634haystack.as_bytes().contains(&(selfas u8))
635 } else {
636let mut buffer = [0u8; 4];
637self.encode_utf8(&mut buffer).is_contained_in(haystack)
638 }
639 }
640641#[inline]
642fn is_prefix_of(self, haystack: &str) -> bool {
643self.encode_utf8(&mut [0u8; 4]).is_prefix_of(haystack)
644 }
645646#[inline]
647fn strip_prefix_of(self, haystack: &str) -> Option<&str> {
648self.encode_utf8(&mut [0u8; 4]).strip_prefix_of(haystack)
649 }
650651#[inline]
652fn is_suffix_of<'a>(self, haystack: &'a str) -> bool653where
654Self::Searcher<'a>: ReverseSearcher<'a>,
655 {
656self.encode_utf8(&mut [0u8; 4]).is_suffix_of(haystack)
657 }
658659#[inline]
660fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str>
661where
662Self::Searcher<'a>: ReverseSearcher<'a>,
663 {
664self.encode_utf8(&mut [0u8; 4]).strip_suffix_of(haystack)
665 }
666667#[inline]
668fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>> {
669Some(Utf8Pattern::CharPattern(*self))
670 }
671}
672673/////////////////////////////////////////////////////////////////////////////
674// Impl for a MultiCharEq wrapper
675/////////////////////////////////////////////////////////////////////////////
676677#[doc(hidden)]
678trait MultiCharEq {
679fn matches(&mut self, c: char) -> bool;
680}
681682impl<F> MultiCharEqfor F
683where
684F: FnMut(char) -> bool,
685{
686#[inline]
687fn matches(&mut self, c: char) -> bool {
688 (*self)(c)
689 }
690}
691692impl<const N: usize> MultiCharEqfor [char; N] {
693#[inline]
694fn matches(&mut self, c: char) -> bool {
695self.contains(&c)
696 }
697}
698699impl<const N: usize> MultiCharEqfor &[char; N] {
700#[inline]
701fn matches(&mut self, c: char) -> bool {
702self.contains(&c)
703 }
704}
705706impl MultiCharEqfor &[char] {
707#[inline]
708fn matches(&mut self, c: char) -> bool {
709self.contains(&c)
710 }
711}
712713struct MultiCharEqPattern<C: MultiCharEq>(C);
714715#[derive(#[automatically_derived]impl<'a, C: crate::clone::Clone + MultiCharEq>
crate::clone::Clone for MultiCharEqSearcher<'a, C> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_struct_field3_finish(f,
"MultiCharEqSearcher char_eq haystack char_indices",
&self.char_eq, &self.haystack, &&self.char_indices)
}
}Debug)]
716struct MultiCharEqSearcher<'a, C: MultiCharEq> {
717 char_eq: C,
718 haystack: &'a str,
719 char_indices: super::CharIndices<'a>,
720}
721722unsafe impl<C: MultiCharEq> Patternfor MultiCharEqPattern<C> {
723type Searcher<'a> = MultiCharEqSearcher<'a, C>;
724725#[inline]
726fn into_searcher(self, haystack: &str) -> MultiCharEqSearcher<'_, C> {
727MultiCharEqSearcher { haystack, char_eq: self.0, char_indices: haystack.char_indices() }
728 }
729}
730731unsafe impl<'a, C: MultiCharEq> Searcher<'a> for MultiCharEqSearcher<'a, C> {
732#[inline]
733fn haystack(&self) -> &'a str {
734self.haystack
735 }
736737#[inline]
738fn next(&mut self) -> SearchStep {
739let s = &mut self.char_indices;
740// Compare lengths of the internal byte slice iterator
741 // to find length of current char
742let pre_len = s.iter.iter.len();
743if let Some((i, c)) = s.next() {
744let len = s.iter.iter.len();
745let char_len = pre_len - len;
746if self.char_eq.matches(c) {
747return SearchStep::Match(i, i + char_len);
748 } else {
749return SearchStep::Reject(i, i + char_len);
750 }
751 }
752 SearchStep::Done753 }
754}
755756unsafe impl<'a, C: MultiCharEq> ReverseSearcher<'a> for MultiCharEqSearcher<'a, C> {
757#[inline]
758fn next_back(&mut self) -> SearchStep {
759let s = &mut self.char_indices;
760// Compare lengths of the internal byte slice iterator
761 // to find length of current char
762let pre_len = s.iter.iter.len();
763if let Some((i, c)) = s.next_back() {
764let len = s.iter.iter.len();
765let char_len = pre_len - len;
766if self.char_eq.matches(c) {
767return SearchStep::Match(i, i + char_len);
768 } else {
769return SearchStep::Reject(i, i + char_len);
770 }
771 }
772 SearchStep::Done773 }
774}
775776impl<'a, C: MultiCharEq> DoubleEndedSearcher<'a> for MultiCharEqSearcher<'a, C> {}
777778/////////////////////////////////////////////////////////////////////////////
779780macro_rules!pattern_methods {
781 ($a:lifetime, $t:ty, $pmap:expr, $smap:expr) => {
782type Searcher<$a> = $t;
783784#[inline]
785fn into_searcher<$a>(self, haystack: &$a str) -> $t {
786 ($smap)(($pmap)(self).into_searcher(haystack))
787 }
788789#[inline]
790fn is_contained_in<$a>(self, haystack: &$a str) -> bool {
791 ($pmap)(self).is_contained_in(haystack)
792 }
793794#[inline]
795fn is_prefix_of<$a>(self, haystack: &$a str) -> bool {
796 ($pmap)(self).is_prefix_of(haystack)
797 }
798799#[inline]
800fn strip_prefix_of<$a>(self, haystack: &$a str) -> Option<&$a str> {
801 ($pmap)(self).strip_prefix_of(haystack)
802 }
803804#[inline]
805fn is_suffix_of<$a>(self, haystack: &$a str) -> bool806where
807$t: ReverseSearcher<$a>,
808 {
809 ($pmap)(self).is_suffix_of(haystack)
810 }
811812#[inline]
813fn strip_suffix_of<$a>(self, haystack: &$a str) -> Option<&$a str>
814where
815$t: ReverseSearcher<$a>,
816 {
817 ($pmap)(self).strip_suffix_of(haystack)
818 }
819 };
820}
821822macro_rules!searcher_methods {
823 (forward) => {
824#[inline]
825fn haystack(&self) -> &'a str {
826self.0.haystack()
827 }
828#[inline]
829fn next(&mut self) -> SearchStep {
830self.0.next()
831 }
832#[inline]
833fn next_match(&mut self) -> Option<(usize, usize)> {
834self.0.next_match()
835 }
836#[inline]
837fn next_reject(&mut self) -> Option<(usize, usize)> {
838self.0.next_reject()
839 }
840 };
841 (reverse) => {
842#[inline]
843fn next_back(&mut self) -> SearchStep {
844self.0.next_back()
845 }
846#[inline]
847fn next_match_back(&mut self) -> Option<(usize, usize)> {
848self.0.next_match_back()
849 }
850#[inline]
851fn next_reject_back(&mut self) -> Option<(usize, usize)> {
852self.0.next_reject_back()
853 }
854 };
855}
856857/// Associated type for `<[char; N] as Pattern>::Searcher<'a>`.
858#[derive(#[automatically_derived]impl<'a, const N : usize> crate::clone::Clone for
CharArraySearcher<'a, N> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
CharArraySearcher(crate::clone::Clone::clone(&self.0))
}
}Clone, #[automatically_derived]impl<'a, const N : usize> crate::fmt::Debug for
CharArraySearcher<'a, N> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_struct_field1_finish(f,
"CharArraySearcher", &&self.0)
}
}Debug)]
859pub struct CharArraySearcher<'a, const N: usize>(
860 <MultiCharEqPattern<[char; N]> as Pattern>::Searcher<'a>,
861);
862863/// Associated type for `<&[char; N] as Pattern>::Searcher<'a>`.
864#[derive(#[automatically_derived]impl<'a, 'b, const N : usize> crate::clone::Clone for
CharArrayRefSearcher<'a, 'b, N> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_struct_field1_finish(f,
"CharArrayRefSearcher", &&self.0)
}
}Debug)]
865pub struct CharArrayRefSearcher<'a, 'b, const N: usize>(
866 <MultiCharEqPattern<&'b [char; N]> as Pattern>::Searcher<'a>,
867);
868869/// Searches for chars that are equal to any of the [`char`]s in the array.
870///
871/// # Examples
872///
873/// ```
874/// assert_eq!("Hello world".find(['o', 'l']), Some(2));
875/// assert_eq!("Hello world".find(['h', 'w']), Some(6));
876/// ```
877unsafe impl<const N: usize> Patternfor [char; N] {
878type 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);
879}
880881unsafe impl<'a, const N: usize> Searcher<'a> for CharArraySearcher<'a, N> {
882#[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);
883}
884885unsafe impl<'a, const N: usize> ReverseSearcher<'a> for CharArraySearcher<'a, N> {
886#[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);
887}
888889impl<'a, const N: usize> DoubleEndedSearcher<'a> for CharArraySearcher<'a, N> {}
890891/// Searches for chars that are equal to any of the [`char`]s in the array.
892///
893/// # Examples
894///
895/// ```
896/// assert_eq!("Hello world".find(&['o', 'l']), Some(2));
897/// assert_eq!("Hello world".find(&['h', 'w']), Some(6));
898/// ```
899unsafe impl<'b, const N: usize> Patternfor &'b [char; N] {
900type 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);
901}
902903unsafe impl<'a, 'b, const N: usize> Searcher<'a> for CharArrayRefSearcher<'a, 'b, N> {
904#[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);
905}
906907unsafe impl<'a, 'b, const N: usize> ReverseSearcher<'a> for CharArrayRefSearcher<'a, 'b, N> {
908#[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);
909}
910911impl<'a, 'b, const N: usize> DoubleEndedSearcher<'a> for CharArrayRefSearcher<'a, 'b, N> {}
912913/////////////////////////////////////////////////////////////////////////////
914// Impl for &[char]
915/////////////////////////////////////////////////////////////////////////////
916917// Todo: Change / Remove due to ambiguity in meaning.
918919/// Associated type for `<&[char] as Pattern>::Searcher<'a>`.
920#[derive(#[automatically_derived]impl<'a, 'b> crate::clone::Clone for
CharSliceSearcher<'a, 'b> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
CharSliceSearcher(crate::clone::Clone::clone(&self.0))
}
}Clone, #[automatically_derived]impl<'a, 'b> crate::fmt::Debug for
CharSliceSearcher<'a, 'b> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_struct_field1_finish(f,
"CharSliceSearcher", &&self.0)
}
}Debug)]
921pub struct CharSliceSearcher<'a, 'b>(<MultiCharEqPattern<&'b [char]> as Pattern>::Searcher<'a>);
922923unsafe impl<'a, 'b> Searcher<'a> for CharSliceSearcher<'a, 'b> {
924#[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);
925}
926927unsafe impl<'a, 'b> ReverseSearcher<'a> for CharSliceSearcher<'a, 'b> {
928#[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);
929}
930931impl<'a, 'b> DoubleEndedSearcher<'a> for CharSliceSearcher<'a, 'b> {}
932933/// Searches for chars that are equal to any of the [`char`]s in the slice.
934///
935/// # Examples
936///
937/// ```
938/// assert_eq!("Hello world".find(&['o', 'l'][..]), Some(2));
939/// assert_eq!("Hello world".find(&['h', 'w'][..]), Some(6));
940/// ```
941unsafe impl<'b> Patternfor &'b [char] {
942type 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);
943}
944945/////////////////////////////////////////////////////////////////////////////
946// Impl for F: FnMut(char) -> bool
947/////////////////////////////////////////////////////////////////////////////
948949/// Associated type for `<F as Pattern>::Searcher<'a>`.
950#[derive(#[automatically_derived]impl<'a, F: crate::clone::Clone> crate::clone::Clone
for CharPredicateSearcher<'a, F> where F: FnMut(char) -> bool {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
CharPredicateSearcher(crate::clone::Clone::clone(&self.0))
}
}Clone)]
951pub struct CharPredicateSearcher<'a, F>(<MultiCharEqPattern<F> as Pattern>::Searcher<'a>)
952where
953F: FnMut(char) -> bool;
954955impl<F> fmt::Debugfor CharPredicateSearcher<'_, F>
956where
957F: FnMut(char) -> bool,
958{
959fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
960f.debug_struct("CharPredicateSearcher")
961 .field("haystack", &self.0.haystack)
962 .field("char_indices", &self.0.char_indices)
963 .finish()
964 }
965}
966unsafe impl<'a, F> Searcher<'a> for CharPredicateSearcher<'a, F>
967where
968F: FnMut(char) -> bool,
969{
970#[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);
971}
972973unsafe impl<'a, F> ReverseSearcher<'a> for CharPredicateSearcher<'a, F>
974where
975F: FnMut(char) -> bool,
976{
977#[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);
978}
979980impl<'a, F> DoubleEndedSearcher<'a> for CharPredicateSearcher<'a, F> where F: FnMut(char) -> bool {}
981982/// Searches for [`char`]s that match the given predicate.
983///
984/// # Examples
985///
986/// ```
987/// assert_eq!("Hello world".find(char::is_uppercase), Some(0));
988/// assert_eq!("Hello world".find(|c| "aeiou".contains(c)), Some(1));
989/// ```
990unsafe impl<F> Patternfor F
991where
992F: FnMut(char) -> bool,
993{
994type 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);
995}
996997/////////////////////////////////////////////////////////////////////////////
998// Impl for &&str
999/////////////////////////////////////////////////////////////////////////////
10001001/// Delegates to the `&str` impl.
1002unsafe impl<'b, 'c> Patternfor &'c &'b str {
1003type 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);
1004}
10051006/////////////////////////////////////////////////////////////////////////////
1007// Impl for &str
1008/////////////////////////////////////////////////////////////////////////////
10091010/// Non-allocating substring search.
1011///
1012/// Will handle the pattern `""` as returning empty matches at each character
1013/// boundary.
1014///
1015/// # Examples
1016///
1017/// ```
1018/// assert_eq!("Hello world".find("world"), Some(6));
1019/// ```
1020unsafe impl<'b> Patternfor &'b str {
1021type Searcher<'a> = StrSearcher<'a, 'b>;
10221023#[inline]
1024fn into_searcher(self, haystack: &str) -> StrSearcher<'_, 'b> {
1025StrSearcher::new(haystack, self)
1026 }
10271028/// Checks whether the pattern matches at the front of the haystack.
1029#[inline]
1030fn is_prefix_of(self, haystack: &str) -> bool {
1031haystack.as_bytes().starts_with(self.as_bytes())
1032 }
10331034/// Checks whether the pattern matches anywhere in the haystack
1035#[inline]
1036fn is_contained_in(self, haystack: &str) -> bool {
1037if self.is_empty() {
1038return true;
1039 }
10401041match self.len().cmp(&haystack.len()) {
1042 Ordering::Less => {
1043if self.len() == 1 {
1044return haystack.as_bytes().contains(&self.as_bytes()[0]);
1045 }
10461047#[cfg(any(
1048 all(target_arch = "x86_64", target_feature = "sse2"),
1049 all(target_arch = "loongarch64", target_feature = "lsx"),
1050 all(target_arch = "aarch64", target_feature = "neon")
1051 ))]
1052if self.len() <= 32 {
1053if let Some(result) = simd_contains(self, haystack) {
1054return result;
1055 }
1056 }
10571058self.into_searcher(haystack).next_match().is_some()
1059 }
1060_ => self == haystack,
1061 }
1062 }
10631064/// Removes the pattern from the front of haystack, if it matches.
1065#[inline]
1066fn strip_prefix_of(self, haystack: &str) -> Option<&str> {
1067if self.is_prefix_of(haystack) {
1068// SAFETY: prefix was just verified to exist.
1069unsafe { Some(haystack.get_unchecked(self.len()..)) }
1070 } else {
1071None1072 }
1073 }
10741075/// Checks whether the pattern matches at the back of the haystack.
1076#[inline]
1077fn is_suffix_of<'a>(self, haystack: &'a str) -> bool1078where
1079Self::Searcher<'a>: ReverseSearcher<'a>,
1080 {
1081haystack.as_bytes().ends_with(self.as_bytes())
1082 }
10831084/// Removes the pattern from the back of haystack, if it matches.
1085#[inline]
1086fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str>
1087where
1088Self::Searcher<'a>: ReverseSearcher<'a>,
1089 {
1090if self.is_suffix_of(haystack) {
1091let i = haystack.len() - self.len();
1092// SAFETY: suffix was just verified to exist.
1093unsafe { Some(haystack.get_unchecked(..i)) }
1094 } else {
1095None1096 }
1097 }
10981099#[inline]
1100fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>> {
1101Some(Utf8Pattern::StringPattern(self))
1102 }
1103}
11041105/////////////////////////////////////////////////////////////////////////////
1106// Two Way substring searcher
1107/////////////////////////////////////////////////////////////////////////////
11081109#[derive(#[automatically_derived]impl<'a, 'b> crate::clone::Clone for
StrSearcher<'a, 'b> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_struct_field3_finish(f,
"StrSearcher haystack needle searcher", &self.haystack,
&self.needle, &&self.searcher)
}
}Debug)]
1110/// Associated type for `<&str as Pattern>::Searcher<'a>`.
1111pub struct StrSearcher<'a, 'b> {
1112 haystack: &'a str,
1113 needle: &'b str,
11141115 searcher: StrSearcherImpl,
1116}
11171118#[derive(#[automatically_derived]impl crate::clone::Clone for StrSearcherImpl {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::Empty(__self_0) =>
StrSearcherImpl::Empty(crate::clone::Clone::clone(__self_0)),
Self::Byte(__self_0) =>
StrSearcherImpl::Byte(crate::clone::Clone::clone(__self_0)),
Self::TwoWay(__self_0) =>
StrSearcherImpl::TwoWay(crate::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]impl crate::fmt::Debug for StrSearcherImpl {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
match self {
Self::Empty(__self_0) =>
crate::fmt::Formatter::debug_struct_field1_finish(f, "Empty",
&__self_0),
Self::Byte(__self_0) =>
crate::fmt::Formatter::debug_struct_field1_finish(f, "Byte",
&__self_0),
Self::TwoWay(__self_0) =>
crate::fmt::Formatter::debug_struct_field1_finish(f, "TwoWay",
&__self_0),
}
}
}Debug)]
1119enum StrSearcherImpl {
1120 Empty(EmptyNeedle),
1121 Byte(ByteNeedle),
1122 TwoWay(TwoWaySearcher),
1123}
11241125#[derive(#[automatically_derived]impl crate::clone::Clone for EmptyNeedle {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_struct_field5_finish(f,
"EmptyNeedle position end is_match_fw is_match_bw is_finished",
&self.position, &self.end, &self.is_match_fw, &self.is_match_bw,
&&self.is_finished)
}
}Debug)]
1126struct EmptyNeedle {
1127 position: usize,
1128 end: usize,
1129 is_match_fw: bool,
1130 is_match_bw: bool,
1131// Needed in case of an empty haystack, see #85462
1132is_finished: bool,
1133}
11341135/// Fast searcher for a single-byte needle using `memchr`/`memrchr`.
1136#[derive(#[automatically_derived]impl crate::clone::Clone for ByteNeedle {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_struct_field3_finish(f,
"ByteNeedle b position end", &self.b, &self.position, &&self.end)
}
}Debug)]
1137struct ByteNeedle {
1138 b: u8,
1139/// Forward cursor: `haystack[..position]` has already been reported.
1140position: usize,
1141/// Backward cursor: `haystack[end..]` has already been reported.
1142end: usize,
1143}
11441145impl<'a, 'b> StrSearcher<'a, 'b> {
1146fn new(haystack: &'a str, needle: &'b str) -> StrSearcher<'a, 'b> {
1147if needle.is_empty() {
1148StrSearcher {
1149haystack,
1150needle,
1151 searcher: StrSearcherImpl::Empty(EmptyNeedle {
1152 position: 0,
1153 end: haystack.len(),
1154 is_match_fw: true,
1155 is_match_bw: true,
1156 is_finished: false,
1157 }),
1158 }
1159 } else if let &[b] = needle.as_bytes() {
1160StrSearcher {
1161haystack,
1162needle,
1163 searcher: StrSearcherImpl::Byte(ByteNeedle { b, position: 0, end: haystack.len() }),
1164 }
1165 } else {
1166StrSearcher {
1167haystack,
1168needle,
1169 searcher: StrSearcherImpl::TwoWay(TwoWaySearcher::new(
1170needle.as_bytes(),
1171haystack.len(),
1172 )),
1173 }
1174 }
1175 }
1176}
11771178unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> {
1179#[inline]
1180fn haystack(&self) -> &'a str {
1181self.haystack
1182 }
11831184#[inline]
1185fn next(&mut self) -> SearchStep {
1186match self.searcher {
1187 StrSearcherImpl::Empty(ref mut searcher) => {
1188if searcher.is_finished {
1189return SearchStep::Done;
1190 }
1191// empty needle rejects every char and matches every empty string between them
1192let is_match = searcher.is_match_fw;
1193searcher.is_match_fw = !searcher.is_match_fw;
1194let pos = searcher.position;
1195match self.haystack[pos..].chars().next() {
1196_ if is_match => SearchStep::Match(pos, pos),
1197None => {
1198searcher.is_finished = true;
1199 SearchStep::Done1200 }
1201Some(ch) => {
1202searcher.position += ch.len_utf8();
1203 SearchStep::Reject(pos, searcher.position)
1204 }
1205 }
1206 }
1207 StrSearcherImpl::Byte(ref mut searcher) => {
1208let bytes = self.haystack.as_bytes();
1209let pos = searcher.position;
1210if pos >= bytes.len() {
1211return SearchStep::Done;
1212 }
1213if bytes[pos] == searcher.b {
1214searcher.position = pos + 1;
1215 SearchStep::Match(pos, pos + 1)
1216 } else {
1217// `pos` is always on a char boundary, so this rejects
1218 // exactly the char starting at `pos`.
1219let end = self.haystack.ceil_char_boundary(pos + 1);
1220searcher.position = end;
1221 SearchStep::Reject(pos, end)
1222 }
1223 }
1224 StrSearcherImpl::TwoWay(ref mut searcher) => {
1225// TwoWaySearcher produces valid *Match* indices that split at char boundaries
1226 // as long as it does correct matching and that haystack and needle are
1227 // valid UTF-8
1228 // *Rejects* from the algorithm can fall on any indices, but we will walk them
1229 // manually to the next character boundary, so that they are utf-8 safe.
1230if searcher.position == self.haystack.len() {
1231return SearchStep::Done;
1232 }
1233let is_long = searcher.memory == usize::MAX;
1234match searcher.next::<RejectAndMatch>(
1235self.haystack.as_bytes(),
1236self.needle.as_bytes(),
1237is_long,
1238 ) {
1239 SearchStep::Reject(a, b) => {
1240// skip to next char boundary
1241let b = self.haystack.ceil_char_boundary(b);
1242searcher.position = cmp::max(b, searcher.position);
1243 SearchStep::Reject(a, b)
1244 }
1245 otherwise => otherwise,
1246 }
1247 }
1248 }
1249 }
12501251#[inline]
1252fn next_match(&mut self) -> Option<(usize, usize)> {
1253match self.searcher {
1254 StrSearcherImpl::Empty(..) => loop {
1255match self.next() {
1256 SearchStep::Match(a, b) => return Some((a, b)),
1257 SearchStep::Done => return None,
1258 SearchStep::Reject(..) => {}
1259 }
1260 },
1261 StrSearcherImpl::Byte(ref mut searcher) => {
1262let bytes = self.haystack.as_bytes();
1263if searcher.position >= bytes.len() {
1264return None;
1265 }
1266match memchr::memchr(searcher.b, &bytes[searcher.position..]) {
1267Some(i) => {
1268let pos = searcher.position + i;
1269searcher.position = pos + 1;
1270Some((pos, pos + 1))
1271 }
1272None => {
1273searcher.position = bytes.len();
1274None1275 }
1276 }
1277 }
1278 StrSearcherImpl::TwoWay(ref mut searcher) => {
1279let is_long = searcher.memory == usize::MAX;
1280// write out `true` and `false` cases to encourage the compiler
1281 // to specialize the two cases separately.
1282if is_long {
1283searcher.next::<MatchOnly>(
1284self.haystack.as_bytes(),
1285self.needle.as_bytes(),
1286true,
1287 )
1288 } else {
1289searcher.next::<MatchOnly>(
1290self.haystack.as_bytes(),
1291self.needle.as_bytes(),
1292false,
1293 )
1294 }
1295 }
1296 }
1297 }
1298}
12991300unsafe impl<'a, 'b> ReverseSearcher<'a> for StrSearcher<'a, 'b> {
1301#[inline]
1302fn next_back(&mut self) -> SearchStep {
1303match self.searcher {
1304 StrSearcherImpl::Empty(ref mut searcher) => {
1305if searcher.is_finished {
1306return SearchStep::Done;
1307 }
1308let is_match = searcher.is_match_bw;
1309searcher.is_match_bw = !searcher.is_match_bw;
1310let end = searcher.end;
1311match self.haystack[..end].chars().next_back() {
1312_ if is_match => SearchStep::Match(end, end),
1313None => {
1314searcher.is_finished = true;
1315 SearchStep::Done1316 }
1317Some(ch) => {
1318searcher.end -= ch.len_utf8();
1319 SearchStep::Reject(searcher.end, end)
1320 }
1321 }
1322 }
1323 StrSearcherImpl::Byte(ref mut searcher) => {
1324let end = searcher.end;
1325if end == 0 {
1326return SearchStep::Done;
1327 }
1328let bytes = self.haystack.as_bytes();
1329if bytes[end - 1] == searcher.b {
1330searcher.end = end - 1;
1331 SearchStep::Match(end - 1, end)
1332 } else {
1333let start = self.haystack.floor_char_boundary(end - 1);
1334searcher.end = start;
1335 SearchStep::Reject(start, end)
1336 }
1337 }
1338 StrSearcherImpl::TwoWay(ref mut searcher) => {
1339if searcher.end == 0 {
1340return SearchStep::Done;
1341 }
1342let is_long = searcher.memory == usize::MAX;
1343match searcher.next_back::<RejectAndMatch>(
1344self.haystack.as_bytes(),
1345self.needle.as_bytes(),
1346is_long,
1347 ) {
1348 SearchStep::Reject(a, b) => {
1349// skip to previous char boundary
1350let a = self.haystack.floor_char_boundary(a);
1351searcher.end = cmp::min(a, searcher.end);
1352 SearchStep::Reject(a, b)
1353 }
1354 otherwise => otherwise,
1355 }
1356 }
1357 }
1358 }
13591360#[inline]
1361fn next_match_back(&mut self) -> Option<(usize, usize)> {
1362match self.searcher {
1363 StrSearcherImpl::Empty(..) => loop {
1364match self.next_back() {
1365 SearchStep::Match(a, b) => return Some((a, b)),
1366 SearchStep::Done => return None,
1367 SearchStep::Reject(..) => {}
1368 }
1369 },
1370 StrSearcherImpl::Byte(ref mut searcher) => {
1371if searcher.end == 0 {
1372return None;
1373 }
1374let bytes = self.haystack.as_bytes();
1375match memchr::memrchr(searcher.b, &bytes[..searcher.end]) {
1376Some(i) => {
1377searcher.end = i;
1378Some((i, i + 1))
1379 }
1380None => {
1381searcher.end = 0;
1382None1383 }
1384 }
1385 }
1386 StrSearcherImpl::TwoWay(ref mut searcher) => {
1387let is_long = searcher.memory == usize::MAX;
1388// write out `true` and `false`, like `next_match`
1389if is_long {
1390searcher.next_back::<MatchOnly>(
1391self.haystack.as_bytes(),
1392self.needle.as_bytes(),
1393true,
1394 )
1395 } else {
1396searcher.next_back::<MatchOnly>(
1397self.haystack.as_bytes(),
1398self.needle.as_bytes(),
1399false,
1400 )
1401 }
1402 }
1403 }
1404 }
1405}
14061407/// The internal state of the two-way substring search algorithm.
1408#[derive(#[automatically_derived]impl crate::clone::Clone for TwoWaySearcher {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_struct_fields_finish(f,
"TwoWaySearcher crit_pos crit_pos_back period byteset position end memory memory_back",
&[&self.crit_pos, &self.crit_pos_back, &self.period,
&self.byteset, &self.position, &self.end, &self.memory,
&&self.memory_back])
}
}Debug)]
1409struct TwoWaySearcher {
1410// constants
1411/// critical factorization index
1412crit_pos: usize,
1413/// critical factorization index for reversed needle
1414crit_pos_back: usize,
1415 period: usize,
1416/// `byteset` is an extension (not part of the two way algorithm);
1417 /// it's a 64-bit "fingerprint" where each set bit `j` corresponds
1418 /// to a (byte & 63) == j present in the needle.
1419byteset: u64,
14201421// variables
1422position: usize,
1423 end: usize,
1424/// index into needle before which we have already matched
1425memory: usize,
1426/// index into needle after which we have already matched
1427memory_back: usize,
1428}
14291430/*
1431 This is the Two-Way search algorithm, which was introduced in the paper:
1432 Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.
14331434 Here's some background information.
14351436 A *word* is a string of symbols. The *length* of a word should be a familiar
1437 notion, and here we denote it for any word x by |x|.
1438 (We also allow for the possibility of the *empty word*, a word of length zero).
14391440 If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
1441 *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
1442 For example, both 1 and 2 are periods for the string "aa". As another example,
1443 the only period of the string "abcd" is 4.
14441445 We denote by period(x) the *smallest* period of x (provided that x is non-empty).
1446 This is always well-defined since every non-empty word x has at least one period,
1447 |x|. We sometimes call this *the period* of x.
14481449 If u, v and x are words such that x = uv, where uv is the concatenation of u and
1450 v, then we say that (u, v) is a *factorization* of x.
14511452 Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
1453 that both of the following hold
14541455 - either w is a suffix of u or u is a suffix of w
1456 - either w is a prefix of v or v is a prefix of w
14571458 then w is said to be a *repetition* for the factorization (u, v).
14591460 Just to unpack this, there are four possibilities here. Let w = "abc". Then we
1461 might have:
14621463 - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
1464 - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
1465 - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
1466 - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")
14671468 Note that the word vu is a repetition for any factorization (u,v) of x = uv,
1469 so every factorization has at least one repetition.
14701471 If x is a string and (u, v) is a factorization for x, then a *local period* for
1472 (u, v) is an integer r such that there is some word w such that |w| = r and w is
1473 a repetition for (u, v).
14741475 We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
1476 call this *the local period* of (u, v). Provided that x = uv is non-empty, this
1477 is well-defined (because each non-empty word has at least one factorization, as
1478 noted above).
14791480 It can be proven that the following is an equivalent definition of a local period
1481 for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
1482 all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
1483 defined. (i.e., i > 0 and i + r < |x|).
14841485 Using the above reformulation, it is easy to prove that
14861487 1 <= local_period(u, v) <= period(uv)
14881489 A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
1490 *critical factorization*.
14911492 The algorithm hinges on the following theorem, which is stated without proof:
14931494 **Critical Factorization Theorem** Any word x has at least one critical
1495 factorization (u, v) such that |u| < period(x).
14961497 The purpose of maximal_suffix is to find such a critical factorization.
14981499 If the period is short, compute another factorization x = u' v' to use
1500 for reverse search, chosen instead so that |v'| < period(x).
15011502*/
1503impl TwoWaySearcher {
1504fn new(needle: &[u8], end: usize) -> TwoWaySearcher {
1505let (crit_pos_false, period_false) = TwoWaySearcher::maximal_suffix(needle, false);
1506let (crit_pos_true, period_true) = TwoWaySearcher::maximal_suffix(needle, true);
15071508let (crit_pos, period) = if crit_pos_false > crit_pos_true {
1509 (crit_pos_false, period_false)
1510 } else {
1511 (crit_pos_true, period_true)
1512 };
15131514// A particularly readable explanation of what's going on here can be found
1515 // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
1516 // see the code for "Algorithm CP" on p. 323.
1517 //
1518 // What's going on is we have some critical factorization (u, v) of the
1519 // needle, and we want to determine whether u is a suffix of
1520 // &v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
1521 // "Algorithm CP2", which is optimized for when the period of the needle
1522 // is large.
1523if needle[..crit_pos] == needle[period..period + crit_pos] {
1524// short period case -- the period is exact
1525 // compute a separate critical factorization for the reversed needle
1526 // x = u' v' where |v'| < period(x).
1527 //
1528 // This is sped up by the period being known already.
1529 // Note that a case like x = "acba" may be factored exactly forwards
1530 // (crit_pos = 1, period = 3) while being factored with approximate
1531 // period in reverse (crit_pos = 2, period = 2). We use the given
1532 // reverse factorization but keep the exact period.
1533let crit_pos_back = needle.len()
1534 - cmp::max(
1535TwoWaySearcher::reverse_maximal_suffix(needle, period, false),
1536TwoWaySearcher::reverse_maximal_suffix(needle, period, true),
1537 );
15381539TwoWaySearcher {
1540crit_pos,
1541crit_pos_back,
1542period,
1543 byteset: Self::byteset_create(&needle[..period]),
15441545 position: 0,
1546end,
1547 memory: 0,
1548 memory_back: needle.len(),
1549 }
1550 } else {
1551// long period case -- we have an approximation to the actual period,
1552 // and don't use memorization.
1553 //
1554 // Approximate the period by lower bound max(|u|, |v|) + 1.
1555 // The critical factorization is efficient to use for both forward and
1556 // reverse search.
15571558TwoWaySearcher {
1559crit_pos,
1560 crit_pos_back: crit_pos,
1561 period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
1562 byteset: Self::byteset_create(needle),
15631564 position: 0,
1565end,
1566 memory: usize::MAX, // Dummy value to signify that the period is long
1567memory_back: usize::MAX,
1568 }
1569 }
1570 }
15711572#[inline]
1573fn byteset_create(bytes: &[u8]) -> u64 {
1574bytes.iter().fold(0, |a, &b| (1 << (b & 0x3f)) | a)
1575 }
15761577#[inline]
1578fn byteset_contains(&self, byte: u8) -> bool {
1579 (self.byteset >> ((byte & 0x3f) as usize)) & 1 != 0
1580}
15811582// One of the main ideas of Two-Way is that we factorize the needle into
1583 // two halves, (u, v), and begin trying to find v in the haystack by scanning
1584 // left to right. If v matches, we try to match u by scanning right to left.
1585 // How far we can jump when we encounter a mismatch is all based on the fact
1586 // that (u, v) is a critical factorization for the needle.
1587#[inline]
1588fn next<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> S::Output
1589where
1590S: TwoWayStrategy,
1591 {
1592// `next()` uses `self.position` as its cursor
1593let old_pos = self.position;
1594let needle_last = needle.len() - 1;
1595'search: loop {
1596// Check that we have room to search in
1597 // position + needle_last can not overflow if we assume slices
1598 // are bounded by isize's range.
1599let tail_byte = match haystack.get(self.position + needle_last) {
1600Some(&b) => b,
1601None => {
1602self.position = haystack.len();
1603return S::rejecting(old_pos, self.position);
1604 }
1605 };
16061607if S::use_early_reject() && old_pos != self.position {
1608return S::rejecting(old_pos, self.position);
1609 }
16101611// Quickly skip by large portions unrelated to our substring
1612if !self.byteset_contains(tail_byte) {
1613self.position += needle.len();
1614if !long_period {
1615self.memory = 0;
1616 }
1617continue 'search;
1618 }
16191620// See if the right part of the needle matches
1621let start =
1622if long_period { self.crit_pos } else { cmp::max(self.crit_pos, self.memory) };
1623for i in start..needle.len() {
1624// SAFETY: on every iteration of `'search`, the `haystack.get(self.position + needle_last)`
1625 // check returned `Some`, so `self.position + needle_last < haystack.len()`.
1626 // Since `i < needle.len()` implies `i <= needle_last`, we have
1627 // `self.position + i < haystack.len()`.
1628 // Every path that mutates `self.position` below either returns or re-enters `'search`,
1629 // which re-runs the check before reaching the loop again.
1630if needle[i] != unsafe { *haystack.get_unchecked(self.position + i) } {
1631self.position += i - self.crit_pos + 1;
1632if !long_period {
1633self.memory = 0;
1634 }
1635continue 'search;
1636 }
1637 }
16381639// See if the left part of the needle matches
1640let start = if long_period { 0 } else { self.memory };
1641for i in (start..self.crit_pos).rev() {
1642// SAFETY: on every iteration of `'search`, the `haystack.get(self.position + needle_last)`
1643 // check returned `Some`, so `self.position + needle_last < haystack.len()`.
1644 // Since `i < self.crit_pos <= needle.len()`, we have `i <= needle_last`, and thus
1645 // `self.position + i <= self.position + needle_last < haystack.len()`.
1646 // Every path that mutates `self.position` below either returns or re-enters `'search`,
1647 // which re-runs the check before reaching the loop again.
1648if needle[i] != unsafe { *haystack.get_unchecked(self.position + i) } {
1649self.position += self.period;
1650if !long_period {
1651self.memory = needle.len() - self.period;
1652 }
1653continue 'search;
1654 }
1655 }
16561657// We have found a match!
1658let match_pos = self.position;
16591660// Note: add self.period instead of needle.len() to have overlapping matches
1661self.position += needle.len();
1662if !long_period {
1663self.memory = 0; // set to needle.len() - self.period for overlapping matches
1664}
16651666return S::matching(match_pos, match_pos + needle.len());
1667 }
1668 }
16691670// Follows the ideas in `next()`.
1671 //
1672 // The definitions are symmetrical, with period(x) = period(reverse(x))
1673 // and local_period(u, v) = local_period(reverse(v), reverse(u)), so if (u, v)
1674 // is a critical factorization, so is (reverse(v), reverse(u)).
1675 //
1676 // For the reverse case we have computed a critical factorization x = u' v'
1677 // (field `crit_pos_back`). We need |u| < period(x) for the forward case and
1678 // thus |v'| < period(x) for the reverse.
1679 //
1680 // To search in reverse through the haystack, we search forward through
1681 // a reversed haystack with a reversed needle, matching first u' and then v'.
1682#[inline]
1683fn next_back<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> S::Output
1684where
1685S: TwoWayStrategy,
1686 {
1687// `next_back()` uses `self.end` as its cursor -- so that `next()` and `next_back()`
1688 // are independent.
1689let old_end = self.end;
1690'search: loop {
1691// Check that we have room to search in
1692 // end - needle.len() will wrap around when there is no more room,
1693 // but due to slice length limits it can never wrap all the way back
1694 // into the length of haystack.
1695let front_byte = match haystack.get(self.end.wrapping_sub(needle.len())) {
1696Some(&b) => b,
1697None => {
1698self.end = 0;
1699return S::rejecting(0, old_end);
1700 }
1701 };
17021703if S::use_early_reject() && old_end != self.end {
1704return S::rejecting(self.end, old_end);
1705 }
17061707// Quickly skip by large portions unrelated to our substring
1708if !self.byteset_contains(front_byte) {
1709self.end -= needle.len();
1710if !long_period {
1711self.memory_back = needle.len();
1712 }
1713continue 'search;
1714 }
17151716// See if the left part of the needle matches
1717let crit = if long_period {
1718self.crit_pos_back
1719 } else {
1720 cmp::min(self.crit_pos_back, self.memory_back)
1721 };
1722for i in (0..crit).rev() {
1723// SAFETY: On every iteration of `'search`, `haystack.get(self.end.wrapping_sub(needle.len()))`
1724 // returned `Some`, so `self.end >= needle.len()` and `self.end - needle.len() < haystack.len()`.
1725 // Since `self.end <= haystack.len()` and `i < needle.len()`, we have
1726 // `self.end - needle.len() + i < self.end <= haystack.len()`, so
1727 // `haystack.get_unchecked(self.end - needle.len() + i)` is safe.
1728 // - The path that mutates `self.end` either re-enters `'search`, which re-runs the checks
1729 // before reaching this loop again, or returns on match, so the invariant holds.
1730if needle[i] != unsafe { *haystack.get_unchecked(self.end - needle.len() + i) } {
1731self.end -= self.crit_pos_back - i;
1732if !long_period {
1733self.memory_back = needle.len();
1734 }
1735continue 'search;
1736 }
1737 }
17381739// See if the right part of the needle matches
1740let needle_end = if long_period { needle.len() } else { self.memory_back };
1741for i in self.crit_pos_back..needle_end {
1742// SAFETY: The same `self.end - needle.len() + i < haystack.len()` argument as the
1743 // left-part loop applies: the `haystack.get(self.end.wrapping_sub(needle.len()))`
1744 // check at the top of `'search` established the bound for this iteration, and
1745 // every mutation of `self.end` is followed by `continue 'search` (which re-runs
1746 // the check) or a `return` (which exits before any further unsafe access).
1747if needle[i] != unsafe { *haystack.get_unchecked(self.end - needle.len() + i) } {
1748self.end -= self.period;
1749if !long_period {
1750self.memory_back = self.period;
1751 }
1752continue 'search;
1753 }
1754 }
17551756// We have found a match!
1757let match_pos = self.end - needle.len();
1758// Note: sub self.period instead of needle.len() to have overlapping matches
1759self.end -= needle.len();
1760if !long_period {
1761self.memory_back = needle.len();
1762 }
17631764return S::matching(match_pos, match_pos + needle.len());
1765 }
1766 }
17671768// Compute the maximal suffix of `arr`.
1769 //
1770 // The maximal suffix is a possible critical factorization (u, v) of `arr`.
1771 //
1772 // Returns (`i`, `p`) where `i` is the starting index of v and `p` is the
1773 // period of v.
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).
1780#[inline]
1781fn maximal_suffix(arr: &[u8], order_greater: bool) -> (usize, usize) {
1782let mut left = 0; // Corresponds to i in the paper
1783let mut right = 1; // Corresponds to j in the paper
1784let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1785 // to match 0-based indexing.
1786let mut period = 1; // Corresponds to p in the paper
17871788while let Some(&a) = arr.get(right + offset) {
1789// `left` will be inbounds when `right` is.
1790let b = arr[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 }
1811 }
1812 (left, period)
1813 }
18141815// Compute the maximal suffix of the reverse of `arr`.
1816 //
1817 // The maximal suffix is a possible critical factorization (u', v') of `arr`.
1818 //
1819 // Returns `i` where `i` is the starting index of v', from the back;
1820 // returns immediately when a period of `known_period` is reached.
1821 //
1822 // `order_greater` determines if lexical order is `<` or `>`. Both
1823 // orders must be computed -- the ordering with the largest `i` gives
1824 // a critical factorization.
1825 //
1826 // For long period cases, the resulting period is not exact (it is too short).
1827fn reverse_maximal_suffix(arr: &[u8], known_period: usize, order_greater: bool) -> usize {
1828let mut left = 0; // Corresponds to i in the paper
1829let mut right = 1; // Corresponds to j in the paper
1830let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1831 // to match 0-based indexing.
1832let mut period = 1; // Corresponds to p in the paper
1833let n = arr.len();
18341835while right + offset < n {
1836let a = arr[n - (1 + right + offset)];
1837let b = arr[n - (1 + left + offset)];
1838if (a < b && !order_greater) || (a > b && order_greater) {
1839// Suffix is smaller, period is entire prefix so far.
1840right += offset + 1;
1841 offset = 0;
1842 period = right - left;
1843 } else if a == b {
1844// Advance through repetition of the current period.
1845if offset + 1 == period {
1846 right += offset + 1;
1847 offset = 0;
1848 } else {
1849 offset += 1;
1850 }
1851 } else {
1852// Suffix is larger, start over from current location.
1853left = right;
1854 right += 1;
1855 offset = 0;
1856 period = 1;
1857 }
1858if period == known_period {
1859break;
1860 }
1861 }
1862if true {
if !(period <= known_period) {
crate::panicking::panic("assertion failed: period <= known_period")
};
};debug_assert!(period <= known_period);
1863left1864 }
1865}
18661867// TwoWayStrategy allows the algorithm to either skip non-matches as quickly
1868// as possible, or to work in a mode where it emits Rejects relatively quickly.
1869trait TwoWayStrategy {
1870type Output;
1871fn use_early_reject() -> bool;
1872fn rejecting(a: usize, b: usize) -> Self::Output;
1873fn matching(a: usize, b: usize) -> Self::Output;
1874}
18751876/// Skip to match intervals as quickly as possible
1877enum MatchOnly {}
18781879impl TwoWayStrategyfor MatchOnly {
1880type Output = Option<(usize, usize)>;
18811882#[inline]
1883fn use_early_reject() -> bool {
1884false
1885}
1886#[inline]
1887fn rejecting(_a: usize, _b: usize) -> Self::Output {
1888None1889 }
1890#[inline]
1891fn matching(a: usize, b: usize) -> Self::Output {
1892Some((a, b))
1893 }
1894}
18951896/// Emit Rejects regularly
1897enum RejectAndMatch {}
18981899impl TwoWayStrategyfor RejectAndMatch {
1900type Output = SearchStep;
19011902#[inline]
1903fn use_early_reject() -> bool {
1904true
1905}
1906#[inline]
1907fn rejecting(a: usize, b: usize) -> Self::Output {
1908 SearchStep::Reject(a, b)
1909 }
1910#[inline]
1911fn matching(a: usize, b: usize) -> Self::Output {
1912 SearchStep::Match(a, b)
1913 }
1914}
19151916/// SIMD search for short needles based on
1917/// Wojciech Muła's "SIMD-friendly algorithms for substring searching"[0]
1918///
1919/// It skips ahead by the vector width on each iteration (rather than the needle length as two-way
1920/// does) by probing the first and last byte of the needle for the whole vector width
1921/// and only doing full needle comparisons when the vectorized probe indicated potential matches.
1922///
1923/// Since the x86_64 baseline only offers SSE2 we only use u8x16 here.
1924/// If we ever ship std with for x86-64-v3 or adapt this for other platforms then wider vectors
1925/// should be evaluated.
1926///
1927/// Similarly, on LoongArch the 128-bit LSX vector extension is the baseline,
1928/// so we also use `u8x16` there. Wider vector widths may be considered
1929/// for future LoongArch extensions (e.g., LASX).
1930///
1931/// For haystacks smaller than vector-size + needle length it falls back to
1932/// a naive O(n*m) search so this implementation should not be called on larger needles.
1933///
1934/// [0]: http://0x80.pl/articles/simd-strfind.html#sse-avx2
1935#[cfg(any(
1936 all(target_arch = "x86_64", target_feature = "sse2"),
1937 all(target_arch = "loongarch64", target_feature = "lsx"),
1938 all(target_arch = "aarch64", target_feature = "neon")
1939))]
1940#[inline]
1941fn simd_contains(needle: &str, haystack: &str) -> Option<bool> {
1942let needle = needle.as_bytes();
1943let haystack = haystack.as_bytes();
19441945if true {
if !(needle.len() > 1) {
crate::panicking::panic("assertion failed: needle.len() > 1")
};
};debug_assert!(needle.len() > 1);
19461947use crate::ops::BitAnd;
1948use crate::simd::cmp::SimdPartialEq;
1949use crate::simd::{mask8x16as Mask, u8x16as Block};
19501951let first_probe = needle[0];
1952let last_byte_offset = needle.len() - 1;
19531954// the offset used for the 2nd vector
1955let second_probe_offset = if needle.len() == 2 {
1956// never bail out on len=2 needles because the probes will fully cover them and have
1957 // no degenerate cases.
19581
1959} else {
1960// try a few bytes in case first and last byte of the needle are the same
1961let Some(second_probe_offset) =
1962 (needle.len().saturating_sub(4)..needle.len()).rfind(|&idx| needle[idx] != first_probe)
1963else {
1964// fall back to other search methods if we can't find any different bytes
1965 // since we could otherwise hit some degenerate cases
1966return None;
1967 };
1968second_probe_offset1969 };
19701971// do a naive search if the haystack is too small to fit
1972if haystack.len() < Block::LEN + last_byte_offset {
1973return Some(haystack.windows(needle.len()).any(|c| c == needle));
1974 }
19751976let first_probe: Block = Block::splat(first_probe);
1977let second_probe: Block = Block::splat(needle[second_probe_offset]);
1978// first byte are already checked by the outer loop. to verify a match only the
1979 // remainder has to be compared.
1980let trimmed_needle = &needle[1..];
19811982// this #[cold] is load-bearing, benchmark before removing it...
1983let check_mask = #[cold]
1984|idx, mask: u16, skip: bool| -> bool {
1985if skip {
1986return false;
1987 }
19881989// and so is this. optimizations are weird.
1990let mut mask = mask;
19911992while mask != 0 {
1993let trailing = mask.trailing_zeros();
1994let offset = idx + trailing as usize + 1;
1995// SAFETY: mask is between 0 and 15 trailing zeroes, we skip one additional byte that was already compared
1996 // and then take trimmed_needle.len() bytes. This is within the bounds defined by the outer loop
1997unsafe {
1998let sub = haystack.get_unchecked(offset..).get_unchecked(..trimmed_needle.len());
1999if small_slice_eq(sub, trimmed_needle) {
2000return true;
2001 }
2002 }
2003 mask &= !(1 << trailing);
2004 }
2005false
2006};
20072008let test_chunk = |idx| -> u16 {
2009// SAFETY: this requires at least LANES bytes being readable at idx
2010 // that is ensured by the loop ranges (see comments below)
2011let a: Block = unsafe { haystack.as_ptr().add(idx).cast::<Block>().read_unaligned() };
2012// SAFETY: this requires LANES + block_offset bytes being readable at idx
2013let b: Block = unsafe {
2014haystack.as_ptr().add(idx).add(second_probe_offset).cast::<Block>().read_unaligned()
2015 };
2016let eq_first: Mask = a.simd_eq(first_probe);
2017let eq_last: Mask = b.simd_eq(second_probe);
2018let both = eq_first.bitand(eq_last);
2019both.to_bitmask() as u162020 };
20212022let mut i = 0;
2023let mut result = false;
2024// The loop condition must ensure that there's enough headroom to read LANE bytes,
2025 // and not only at the current index but also at the index shifted by block_offset
2026const UNROLL: usize = 4;
2027while i + last_byte_offset + UNROLL * Block::LEN < haystack.len() && !result {
2028let mut masks = [0u16; UNROLL];
2029for j in 0..UNROLL {
2030 masks[j] = test_chunk(i + j * Block::LEN);
2031 }
2032for j in 0..UNROLL {
2033let mask = masks[j];
2034if mask != 0 {
2035 result |= check_mask(i + j * Block::LEN, mask, result);
2036 }
2037 }
2038 i += UNROLL * Block::LEN;
2039 }
2040while i + last_byte_offset + Block::LEN < haystack.len() && !result {
2041let mask = test_chunk(i);
2042if mask != 0 {
2043 result |= check_mask(i, mask, result);
2044 }
2045 i += Block::LEN;
2046 }
20472048// Process the tail that didn't fit into LANES-sized steps.
2049 // This simply repeats the same procedure but as right-aligned chunk instead
2050 // of a left-aligned one. The last byte must be exactly flush with the string end so
2051 // we don't miss a single byte or read out of bounds.
2052let i = haystack.len() - last_byte_offset - Block::LEN;
2053let mask = test_chunk(i);
2054if mask != 0 {
2055result |= check_mask(i, mask, result);
2056 }
20572058Some(result)
2059}
20602061/// Compares short slices for equality.
2062///
2063/// It avoids a call to libc's memcmp which is faster on long slices
2064/// due to SIMD optimizations but it incurs a function call overhead.
2065///
2066/// # Safety
2067///
2068/// Both slices must have the same length.
2069#[cfg(any(
2070 all(target_arch = "x86_64", target_feature = "sse2"),
2071 all(target_arch = "loongarch64", target_feature = "lsx"),
2072 all(target_arch = "aarch64", target_feature = "neon")
2073))]
2074#[inline]
2075unsafe fn small_slice_eq(x: &[u8], y: &[u8]) -> bool {
2076if 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());
2077// This function is adapted from
2078 // https://github.com/BurntSushi/memchr/blob/8037d11b4357b0f07be2bb66dc2659d9cf28ad32/src/memmem/util.rs#L32
20792080 // If we don't have enough bytes to do 4-byte at a time loads, then
2081 // fall back to the naive slow version.
2082 //
2083 // Potential alternative: We could do a copy_nonoverlapping combined with a mask instead
2084 // of a loop. Benchmark it.
2085if x.len() < 4 {
2086for (&b1, &b2) in x.iter().zip(y) {
2087if b1 != b2 {
2088return false;
2089 }
2090 }
2091return true;
2092 }
2093// When we have 4 or more bytes to compare, then proceed in chunks of 4 at
2094 // a time using unaligned loads.
2095 //
2096 // Also, why do 4 byte loads instead of, say, 8 byte loads? The reason is
2097 // that this particular version of memcmp is likely to be called with tiny
2098 // needles. That means that if we do 8 byte loads, then a higher proportion
2099 // of memcmp calls will use the slower variant above. With that said, this
2100 // is a hypothesis and is only loosely supported by benchmarks. There's
2101 // likely some improvement that could be made here. The main thing here
2102 // though is to optimize for latency, not throughput.
21032104 // SAFETY: Via the conditional above, we know that both `px` and `py`
2105 // have the same length, so `px < pxend` implies that `py < pyend`.
2106 // Thus, dereferencing both `px` and `py` in the loop below is safe.
2107 //
2108 // Moreover, we set `pxend` and `pyend` to be 4 bytes before the actual
2109 // end of `px` and `py`. Thus, the final dereference outside of the
2110 // loop is guaranteed to be valid. (The final comparison will overlap with
2111 // the last comparison done in the loop for lengths that aren't multiples
2112 // of four.)
2113 //
2114 // Finally, we needn't worry about alignment here, since we do unaligned
2115 // loads.
2116unsafe {
2117let (mut px, mut py) = (x.as_ptr(), y.as_ptr());
2118let (pxend, pyend) = (px.add(x.len() - 4), py.add(y.len() - 4));
2119while px < pxend {
2120let vx = (px as *const u32).read_unaligned();
2121let vy = (py as *const u32).read_unaligned();
2122if vx != vy {
2123return false;
2124 }
2125 px = px.add(4);
2126 py = py.add(4);
2127 }
2128let vx = (pxendas *const u32).read_unaligned();
2129let vy = (pyendas *const u32).read_unaligned();
2130vx == vy2131 }
2132}