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]
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::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]
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::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.len() == 0 {
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.as_bytes().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.as_bytes().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::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::TwoWay(__self_0) =>
crate::fmt::Formatter::debug_tuple_field1_finish(f, "TwoWay",
&__self_0),
}
}
}Debug)]
1072enum StrSearcherImpl {
1073 Empty(EmptyNeedle),
1074 TwoWay(TwoWaySearcher),
1075}
10761077#[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)]
1078struct EmptyNeedle {
1079 position: usize,
1080 end: usize,
1081 is_match_fw: bool,
1082 is_match_bw: bool,
1083// Needed in case of an empty haystack, see #85462
1084is_finished: bool,
1085}
10861087impl<'a, 'b> StrSearcher<'a, 'b> {
1088fn new(haystack: &'a str, needle: &'b str) -> StrSearcher<'a, 'b> {
1089if needle.is_empty() {
1090StrSearcher {
1091haystack,
1092needle,
1093 searcher: StrSearcherImpl::Empty(EmptyNeedle {
1094 position: 0,
1095 end: haystack.len(),
1096 is_match_fw: true,
1097 is_match_bw: true,
1098 is_finished: false,
1099 }),
1100 }
1101 } else {
1102StrSearcher {
1103haystack,
1104needle,
1105 searcher: StrSearcherImpl::TwoWay(TwoWaySearcher::new(
1106needle.as_bytes(),
1107haystack.len(),
1108 )),
1109 }
1110 }
1111 }
1112}
11131114unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> {
1115#[inline]
1116fn haystack(&self) -> &'a str {
1117self.haystack
1118 }
11191120#[inline]
1121fn next(&mut self) -> SearchStep {
1122match self.searcher {
1123 StrSearcherImpl::Empty(ref mut searcher) => {
1124if searcher.is_finished {
1125return SearchStep::Done;
1126 }
1127// empty needle rejects every char and matches every empty string between them
1128let is_match = searcher.is_match_fw;
1129searcher.is_match_fw = !searcher.is_match_fw;
1130let pos = searcher.position;
1131match self.haystack[pos..].chars().next() {
1132_ if is_match => SearchStep::Match(pos, pos),
1133None => {
1134searcher.is_finished = true;
1135 SearchStep::Done1136 }
1137Some(ch) => {
1138searcher.position += ch.len_utf8();
1139 SearchStep::Reject(pos, searcher.position)
1140 }
1141 }
1142 }
1143 StrSearcherImpl::TwoWay(ref mut searcher) => {
1144// TwoWaySearcher produces valid *Match* indices that split at char boundaries
1145 // as long as it does correct matching and that haystack and needle are
1146 // valid UTF-8
1147 // *Rejects* from the algorithm can fall on any indices, but we will walk them
1148 // manually to the next character boundary, so that they are utf-8 safe.
1149if searcher.position == self.haystack.len() {
1150return SearchStep::Done;
1151 }
1152let is_long = searcher.memory == usize::MAX;
1153match searcher.next::<RejectAndMatch>(
1154self.haystack.as_bytes(),
1155self.needle.as_bytes(),
1156is_long,
1157 ) {
1158 SearchStep::Reject(a, mut b) => {
1159// skip to next char boundary
1160while !self.haystack.is_char_boundary(b) {
1161 b += 1;
1162 }
1163searcher.position = cmp::max(b, searcher.position);
1164 SearchStep::Reject(a, b)
1165 }
1166 otherwise => otherwise,
1167 }
1168 }
1169 }
1170 }
11711172#[inline]
1173fn next_match(&mut self) -> Option<(usize, usize)> {
1174match self.searcher {
1175 StrSearcherImpl::Empty(..) => loop {
1176match self.next() {
1177 SearchStep::Match(a, b) => return Some((a, b)),
1178 SearchStep::Done => return None,
1179 SearchStep::Reject(..) => {}
1180 }
1181 },
1182 StrSearcherImpl::TwoWay(ref mut searcher) => {
1183let is_long = searcher.memory == usize::MAX;
1184// write out `true` and `false` cases to encourage the compiler
1185 // to specialize the two cases separately.
1186if is_long {
1187searcher.next::<MatchOnly>(
1188self.haystack.as_bytes(),
1189self.needle.as_bytes(),
1190true,
1191 )
1192 } else {
1193searcher.next::<MatchOnly>(
1194self.haystack.as_bytes(),
1195self.needle.as_bytes(),
1196false,
1197 )
1198 }
1199 }
1200 }
1201 }
1202}
12031204unsafe impl<'a, 'b> ReverseSearcher<'a> for StrSearcher<'a, 'b> {
1205#[inline]
1206fn next_back(&mut self) -> SearchStep {
1207match self.searcher {
1208 StrSearcherImpl::Empty(ref mut searcher) => {
1209if searcher.is_finished {
1210return SearchStep::Done;
1211 }
1212let is_match = searcher.is_match_bw;
1213searcher.is_match_bw = !searcher.is_match_bw;
1214let end = searcher.end;
1215match self.haystack[..end].chars().next_back() {
1216_ if is_match => SearchStep::Match(end, end),
1217None => {
1218searcher.is_finished = true;
1219 SearchStep::Done1220 }
1221Some(ch) => {
1222searcher.end -= ch.len_utf8();
1223 SearchStep::Reject(searcher.end, end)
1224 }
1225 }
1226 }
1227 StrSearcherImpl::TwoWay(ref mut searcher) => {
1228if searcher.end == 0 {
1229return SearchStep::Done;
1230 }
1231let is_long = searcher.memory == usize::MAX;
1232match searcher.next_back::<RejectAndMatch>(
1233self.haystack.as_bytes(),
1234self.needle.as_bytes(),
1235is_long,
1236 ) {
1237 SearchStep::Reject(mut a, b) => {
1238// skip to next char boundary
1239while !self.haystack.is_char_boundary(a) {
1240 a -= 1;
1241 }
1242searcher.end = cmp::min(a, searcher.end);
1243 SearchStep::Reject(a, b)
1244 }
1245 otherwise => otherwise,
1246 }
1247 }
1248 }
1249 }
12501251#[inline]
1252fn next_match_back(&mut self) -> Option<(usize, usize)> {
1253match self.searcher {
1254 StrSearcherImpl::Empty(..) => loop {
1255match self.next_back() {
1256 SearchStep::Match(a, b) => return Some((a, b)),
1257 SearchStep::Done => return None,
1258 SearchStep::Reject(..) => {}
1259 }
1260 },
1261 StrSearcherImpl::TwoWay(ref mut searcher) => {
1262let is_long = searcher.memory == usize::MAX;
1263// write out `true` and `false`, like `next_match`
1264if is_long {
1265searcher.next_back::<MatchOnly>(
1266self.haystack.as_bytes(),
1267self.needle.as_bytes(),
1268true,
1269 )
1270 } else {
1271searcher.next_back::<MatchOnly>(
1272self.haystack.as_bytes(),
1273self.needle.as_bytes(),
1274false,
1275 )
1276 }
1277 }
1278 }
1279 }
1280}
12811282/// The internal state of the two-way substring search algorithm.
1283#[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)]
1284struct TwoWaySearcher {
1285// constants
1286/// critical factorization index
1287crit_pos: usize,
1288/// critical factorization index for reversed needle
1289crit_pos_back: usize,
1290 period: usize,
1291/// `byteset` is an extension (not part of the two way algorithm);
1292 /// it's a 64-bit "fingerprint" where each set bit `j` corresponds
1293 /// to a (byte & 63) == j present in the needle.
1294byteset: u64,
12951296// variables
1297position: usize,
1298 end: usize,
1299/// index into needle before which we have already matched
1300memory: usize,
1301/// index into needle after which we have already matched
1302memory_back: usize,
1303}
13041305/*
1306 This is the Two-Way search algorithm, which was introduced in the paper:
1307 Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.
13081309 Here's some background information.
13101311 A *word* is a string of symbols. The *length* of a word should be a familiar
1312 notion, and here we denote it for any word x by |x|.
1313 (We also allow for the possibility of the *empty word*, a word of length zero).
13141315 If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
1316 *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
1317 For example, both 1 and 2 are periods for the string "aa". As another example,
1318 the only period of the string "abcd" is 4.
13191320 We denote by period(x) the *smallest* period of x (provided that x is non-empty).
1321 This is always well-defined since every non-empty word x has at least one period,
1322 |x|. We sometimes call this *the period* of x.
13231324 If u, v and x are words such that x = uv, where uv is the concatenation of u and
1325 v, then we say that (u, v) is a *factorization* of x.
13261327 Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
1328 that both of the following hold
13291330 - either w is a suffix of u or u is a suffix of w
1331 - either w is a prefix of v or v is a prefix of w
13321333 then w is said to be a *repetition* for the factorization (u, v).
13341335 Just to unpack this, there are four possibilities here. Let w = "abc". Then we
1336 might have:
13371338 - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
1339 - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
1340 - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
1341 - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")
13421343 Note that the word vu is a repetition for any factorization (u,v) of x = uv,
1344 so every factorization has at least one repetition.
13451346 If x is a string and (u, v) is a factorization for x, then a *local period* for
1347 (u, v) is an integer r such that there is some word w such that |w| = r and w is
1348 a repetition for (u, v).
13491350 We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
1351 call this *the local period* of (u, v). Provided that x = uv is non-empty, this
1352 is well-defined (because each non-empty word has at least one factorization, as
1353 noted above).
13541355 It can be proven that the following is an equivalent definition of a local period
1356 for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
1357 all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
1358 defined. (i.e., i > 0 and i + r < |x|).
13591360 Using the above reformulation, it is easy to prove that
13611362 1 <= local_period(u, v) <= period(uv)
13631364 A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
1365 *critical factorization*.
13661367 The algorithm hinges on the following theorem, which is stated without proof:
13681369 **Critical Factorization Theorem** Any word x has at least one critical
1370 factorization (u, v) such that |u| < period(x).
13711372 The purpose of maximal_suffix is to find such a critical factorization.
13731374 If the period is short, compute another factorization x = u' v' to use
1375 for reverse search, chosen instead so that |v'| < period(x).
13761377*/
1378impl TwoWaySearcher {
1379fn new(needle: &[u8], end: usize) -> TwoWaySearcher {
1380let (crit_pos_false, period_false) = TwoWaySearcher::maximal_suffix(needle, false);
1381let (crit_pos_true, period_true) = TwoWaySearcher::maximal_suffix(needle, true);
13821383let (crit_pos, period) = if crit_pos_false > crit_pos_true {
1384 (crit_pos_false, period_false)
1385 } else {
1386 (crit_pos_true, period_true)
1387 };
13881389// A particularly readable explanation of what's going on here can be found
1390 // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
1391 // see the code for "Algorithm CP" on p. 323.
1392 //
1393 // What's going on is we have some critical factorization (u, v) of the
1394 // needle, and we want to determine whether u is a suffix of
1395 // &v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
1396 // "Algorithm CP2", which is optimized for when the period of the needle
1397 // is large.
1398if needle[..crit_pos] == needle[period..period + crit_pos] {
1399// short period case -- the period is exact
1400 // compute a separate critical factorization for the reversed needle
1401 // x = u' v' where |v'| < period(x).
1402 //
1403 // This is sped up by the period being known already.
1404 // Note that a case like x = "acba" may be factored exactly forwards
1405 // (crit_pos = 1, period = 3) while being factored with approximate
1406 // period in reverse (crit_pos = 2, period = 2). We use the given
1407 // reverse factorization but keep the exact period.
1408let crit_pos_back = needle.len()
1409 - cmp::max(
1410TwoWaySearcher::reverse_maximal_suffix(needle, period, false),
1411TwoWaySearcher::reverse_maximal_suffix(needle, period, true),
1412 );
14131414TwoWaySearcher {
1415crit_pos,
1416crit_pos_back,
1417period,
1418 byteset: Self::byteset_create(&needle[..period]),
14191420 position: 0,
1421end,
1422 memory: 0,
1423 memory_back: needle.len(),
1424 }
1425 } else {
1426// long period case -- we have an approximation to the actual period,
1427 // and don't use memorization.
1428 //
1429 // Approximate the period by lower bound max(|u|, |v|) + 1.
1430 // The critical factorization is efficient to use for both forward and
1431 // reverse search.
14321433TwoWaySearcher {
1434crit_pos,
1435 crit_pos_back: crit_pos,
1436 period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
1437 byteset: Self::byteset_create(needle),
14381439 position: 0,
1440end,
1441 memory: usize::MAX, // Dummy value to signify that the period is long
1442memory_back: usize::MAX,
1443 }
1444 }
1445 }
14461447#[inline]
1448fn byteset_create(bytes: &[u8]) -> u64 {
1449bytes.iter().fold(0, |a, &b| (1 << (b & 0x3f)) | a)
1450 }
14511452#[inline]
1453fn byteset_contains(&self, byte: u8) -> bool {
1454 (self.byteset >> ((byte & 0x3f) as usize)) & 1 != 0
1455}
14561457// One of the main ideas of Two-Way is that we factorize the needle into
1458 // two halves, (u, v), and begin trying to find v in the haystack by scanning
1459 // left to right. If v matches, we try to match u by scanning right to left.
1460 // How far we can jump when we encounter a mismatch is all based on the fact
1461 // that (u, v) is a critical factorization for the needle.
1462#[inline]
1463fn next<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> S::Output
1464where
1465S: TwoWayStrategy,
1466 {
1467// `next()` uses `self.position` as its cursor
1468let old_pos = self.position;
1469let needle_last = needle.len() - 1;
1470'search: loop {
1471// Check that we have room to search in
1472 // position + needle_last can not overflow if we assume slices
1473 // are bounded by isize's range.
1474let tail_byte = match haystack.get(self.position + needle_last) {
1475Some(&b) => b,
1476None => {
1477self.position = haystack.len();
1478return S::rejecting(old_pos, self.position);
1479 }
1480 };
14811482if S::use_early_reject() && old_pos != self.position {
1483return S::rejecting(old_pos, self.position);
1484 }
14851486// Quickly skip by large portions unrelated to our substring
1487if !self.byteset_contains(tail_byte) {
1488self.position += needle.len();
1489if !long_period {
1490self.memory = 0;
1491 }
1492continue 'search;
1493 }
14941495// See if the right part of the needle matches
1496let start =
1497if long_period { self.crit_pos } else { cmp::max(self.crit_pos, self.memory) };
1498for i in start..needle.len() {
1499// SAFETY: on every iteration of `'search`, the `haystack.get(self.position + needle_last)`
1500 // check returned `Some`, so `self.position + needle_last < haystack.len()`.
1501 // Since `i < needle.len()` implies `i <= needle_last`, we have
1502 // `self.position + i < haystack.len()`.
1503 // Every path that mutates `self.position` below either returns or re-enters `'search`,
1504 // which re-runs the check before reaching the loop again.
1505if needle[i] != unsafe { *haystack.get_unchecked(self.position + i) } {
1506self.position += i - self.crit_pos + 1;
1507if !long_period {
1508self.memory = 0;
1509 }
1510continue 'search;
1511 }
1512 }
15131514// See if the left part of the needle matches
1515let start = if long_period { 0 } else { self.memory };
1516for i in (start..self.crit_pos).rev() {
1517// SAFETY: on every iteration of `'search`, the `haystack.get(self.position + needle_last)`
1518 // check returned `Some`, so `self.position + needle_last < haystack.len()`.
1519 // Since `i < self.crit_pos <= needle.len()`, we have `i <= needle_last`, and thus
1520 // `self.position + i <= self.position + needle_last < haystack.len()`.
1521 // Every path that mutates `self.position` below either returns or re-enters `'search`,
1522 // which re-runs the check before reaching the loop again.
1523if needle[i] != unsafe { *haystack.get_unchecked(self.position + i) } {
1524self.position += self.period;
1525if !long_period {
1526self.memory = needle.len() - self.period;
1527 }
1528continue 'search;
1529 }
1530 }
15311532// We have found a match!
1533let match_pos = self.position;
15341535// Note: add self.period instead of needle.len() to have overlapping matches
1536self.position += needle.len();
1537if !long_period {
1538self.memory = 0; // set to needle.len() - self.period for overlapping matches
1539}
15401541return S::matching(match_pos, match_pos + needle.len());
1542 }
1543 }
15441545// Follows the ideas in `next()`.
1546 //
1547 // The definitions are symmetrical, with period(x) = period(reverse(x))
1548 // and local_period(u, v) = local_period(reverse(v), reverse(u)), so if (u, v)
1549 // is a critical factorization, so is (reverse(v), reverse(u)).
1550 //
1551 // For the reverse case we have computed a critical factorization x = u' v'
1552 // (field `crit_pos_back`). We need |u| < period(x) for the forward case and
1553 // thus |v'| < period(x) for the reverse.
1554 //
1555 // To search in reverse through the haystack, we search forward through
1556 // a reversed haystack with a reversed needle, matching first u' and then v'.
1557#[inline]
1558fn next_back<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> S::Output
1559where
1560S: TwoWayStrategy,
1561 {
1562// `next_back()` uses `self.end` as its cursor -- so that `next()` and `next_back()`
1563 // are independent.
1564let old_end = self.end;
1565'search: loop {
1566// Check that we have room to search in
1567 // end - needle.len() will wrap around when there is no more room,
1568 // but due to slice length limits it can never wrap all the way back
1569 // into the length of haystack.
1570let front_byte = match haystack.get(self.end.wrapping_sub(needle.len())) {
1571Some(&b) => b,
1572None => {
1573self.end = 0;
1574return S::rejecting(0, old_end);
1575 }
1576 };
15771578if S::use_early_reject() && old_end != self.end {
1579return S::rejecting(self.end, old_end);
1580 }
15811582// Quickly skip by large portions unrelated to our substring
1583if !self.byteset_contains(front_byte) {
1584self.end -= needle.len();
1585if !long_period {
1586self.memory_back = needle.len();
1587 }
1588continue 'search;
1589 }
15901591// See if the left part of the needle matches
1592let crit = if long_period {
1593self.crit_pos_back
1594 } else {
1595 cmp::min(self.crit_pos_back, self.memory_back)
1596 };
1597for i in (0..crit).rev() {
1598// SAFETY: On every iteration of `'search`, `haystack.get(self.end.wrapping_sub(needle.len()))`
1599 // returned `Some`, so `self.end >= needle.len()` and `self.end - needle.len() < haystack.len()`.
1600 // Since `self.end <= haystack.len()` and `i < needle.len()`, we have
1601 // `self.end - needle.len() + i < self.end <= haystack.len()`, so
1602 // `haystack.get_unchecked(self.end - needle.len() + i)` is safe.
1603 // - The path that mutates `self.end` either re-enters `'search`, which re-runs the checks
1604 // before reaching this loop again, or returns on match, so the invariant holds.
1605if needle[i] != unsafe { *haystack.get_unchecked(self.end - needle.len() + i) } {
1606self.end -= self.crit_pos_back - i;
1607if !long_period {
1608self.memory_back = needle.len();
1609 }
1610continue 'search;
1611 }
1612 }
16131614// See if the right part of the needle matches
1615let needle_end = if long_period { needle.len() } else { self.memory_back };
1616for i in self.crit_pos_back..needle_end {
1617// SAFETY: The same `self.end - needle.len() + i < haystack.len()` argument as the
1618 // left-part loop applies: the `haystack.get(self.end.wrapping_sub(needle.len()))`
1619 // check at the top of `'search` established the bound for this iteration, and
1620 // every mutation of `self.end` is followed by `continue 'search` (which re-runs
1621 // the check) or a `return` (which exits before any further unsafe access).
1622if needle[i] != unsafe { *haystack.get_unchecked(self.end - needle.len() + i) } {
1623self.end -= self.period;
1624if !long_period {
1625self.memory_back = self.period;
1626 }
1627continue 'search;
1628 }
1629 }
16301631// We have found a match!
1632let match_pos = self.end - needle.len();
1633// Note: sub self.period instead of needle.len() to have overlapping matches
1634self.end -= needle.len();
1635if !long_period {
1636self.memory_back = needle.len();
1637 }
16381639return S::matching(match_pos, match_pos + needle.len());
1640 }
1641 }
16421643// Compute the maximal suffix of `arr`.
1644 //
1645 // The maximal suffix is a possible critical factorization (u, v) of `arr`.
1646 //
1647 // Returns (`i`, `p`) where `i` is the starting index of v and `p` is the
1648 // period of v.
1649 //
1650 // `order_greater` determines if lexical order is `<` or `>`. Both
1651 // orders must be computed -- the ordering with the largest `i` gives
1652 // a critical factorization.
1653 //
1654 // For long period cases, the resulting period is not exact (it is too short).
1655#[inline]
1656fn maximal_suffix(arr: &[u8], order_greater: bool) -> (usize, usize) {
1657let mut left = 0; // Corresponds to i in the paper
1658let mut right = 1; // Corresponds to j in the paper
1659let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1660 // to match 0-based indexing.
1661let mut period = 1; // Corresponds to p in the paper
16621663while let Some(&a) = arr.get(right + offset) {
1664// `left` will be inbounds when `right` is.
1665let b = arr[left + offset];
1666if (a < b && !order_greater) || (a > b && order_greater) {
1667// Suffix is smaller, period is entire prefix so far.
1668right += offset + 1;
1669 offset = 0;
1670 period = right - left;
1671 } else if a == b {
1672// Advance through repetition of the current period.
1673if offset + 1 == period {
1674 right += offset + 1;
1675 offset = 0;
1676 } else {
1677 offset += 1;
1678 }
1679 } else {
1680// Suffix is larger, start over from current location.
1681left = right;
1682 right += 1;
1683 offset = 0;
1684 period = 1;
1685 }
1686 }
1687 (left, period)
1688 }
16891690// Compute the maximal suffix of the reverse of `arr`.
1691 //
1692 // The maximal suffix is a possible critical factorization (u', v') of `arr`.
1693 //
1694 // Returns `i` where `i` is the starting index of v', from the back;
1695 // returns immediately when a period of `known_period` is reached.
1696 //
1697 // `order_greater` determines if lexical order is `<` or `>`. Both
1698 // orders must be computed -- the ordering with the largest `i` gives
1699 // a critical factorization.
1700 //
1701 // For long period cases, the resulting period is not exact (it is too short).
1702fn reverse_maximal_suffix(arr: &[u8], known_period: usize, order_greater: bool) -> usize {
1703let mut left = 0; // Corresponds to i in the paper
1704let mut right = 1; // Corresponds to j in the paper
1705let mut offset = 0; // Corresponds to k in the paper, but starting at 0
1706 // to match 0-based indexing.
1707let mut period = 1; // Corresponds to p in the paper
1708let n = arr.len();
17091710while right + offset < n {
1711let a = arr[n - (1 + right + offset)];
1712let b = arr[n - (1 + left + offset)];
1713if (a < b && !order_greater) || (a > b && order_greater) {
1714// Suffix is smaller, period is entire prefix so far.
1715right += offset + 1;
1716 offset = 0;
1717 period = right - left;
1718 } else if a == b {
1719// Advance through repetition of the current period.
1720if offset + 1 == period {
1721 right += offset + 1;
1722 offset = 0;
1723 } else {
1724 offset += 1;
1725 }
1726 } else {
1727// Suffix is larger, start over from current location.
1728left = right;
1729 right += 1;
1730 offset = 0;
1731 period = 1;
1732 }
1733if period == known_period {
1734break;
1735 }
1736 }
1737if true {
if !(period <= known_period) {
crate::panicking::panic("assertion failed: period <= known_period")
};
};debug_assert!(period <= known_period);
1738left1739 }
1740}
17411742// TwoWayStrategy allows the algorithm to either skip non-matches as quickly
1743// as possible, or to work in a mode where it emits Rejects relatively quickly.
1744trait TwoWayStrategy {
1745type Output;
1746fn use_early_reject() -> bool;
1747fn rejecting(a: usize, b: usize) -> Self::Output;
1748fn matching(a: usize, b: usize) -> Self::Output;
1749}
17501751/// Skip to match intervals as quickly as possible
1752enum MatchOnly {}
17531754impl TwoWayStrategyfor MatchOnly {
1755type Output = Option<(usize, usize)>;
17561757#[inline]
1758fn use_early_reject() -> bool {
1759false
1760}
1761#[inline]
1762fn rejecting(_a: usize, _b: usize) -> Self::Output {
1763None1764 }
1765#[inline]
1766fn matching(a: usize, b: usize) -> Self::Output {
1767Some((a, b))
1768 }
1769}
17701771/// Emit Rejects regularly
1772enum RejectAndMatch {}
17731774impl TwoWayStrategyfor RejectAndMatch {
1775type Output = SearchStep;
17761777#[inline]
1778fn use_early_reject() -> bool {
1779true
1780}
1781#[inline]
1782fn rejecting(a: usize, b: usize) -> Self::Output {
1783 SearchStep::Reject(a, b)
1784 }
1785#[inline]
1786fn matching(a: usize, b: usize) -> Self::Output {
1787 SearchStep::Match(a, b)
1788 }
1789}
17901791/// SIMD search for short needles based on
1792/// Wojciech Muła's "SIMD-friendly algorithms for substring searching"[0]
1793///
1794/// It skips ahead by the vector width on each iteration (rather than the needle length as two-way
1795/// does) by probing the first and last byte of the needle for the whole vector width
1796/// and only doing full needle comparisons when the vectorized probe indicated potential matches.
1797///
1798/// Since the x86_64 baseline only offers SSE2 we only use u8x16 here.
1799/// If we ever ship std with for x86-64-v3 or adapt this for other platforms then wider vectors
1800/// should be evaluated.
1801///
1802/// Similarly, on LoongArch the 128-bit LSX vector extension is the baseline,
1803/// so we also use `u8x16` there. Wider vector widths may be considered
1804/// for future LoongArch extensions (e.g., LASX).
1805///
1806/// For haystacks smaller than vector-size + needle length it falls back to
1807/// a naive O(n*m) search so this implementation should not be called on larger needles.
1808///
1809/// [0]: http://0x80.pl/articles/simd-strfind.html#sse-avx2
1810#[cfg(any(
1811 all(target_arch = "x86_64", target_feature = "sse2"),
1812 all(target_arch = "loongarch64", target_feature = "lsx"),
1813 all(target_arch = "aarch64", target_feature = "neon")
1814))]
1815#[inline]
1816fn simd_contains(needle: &str, haystack: &str) -> Option<bool> {
1817let needle = needle.as_bytes();
1818let haystack = haystack.as_bytes();
18191820if true {
if !(needle.len() > 1) {
crate::panicking::panic("assertion failed: needle.len() > 1")
};
};debug_assert!(needle.len() > 1);
18211822use crate::ops::BitAnd;
1823use crate::simd::cmp::SimdPartialEq;
1824use crate::simd::{mask8x16as Mask, u8x16as Block};
18251826let first_probe = needle[0];
1827let last_byte_offset = needle.len() - 1;
18281829// the offset used for the 2nd vector
1830let second_probe_offset = if needle.len() == 2 {
1831// never bail out on len=2 needles because the probes will fully cover them and have
1832 // no degenerate cases.
18331
1834} else {
1835// try a few bytes in case first and last byte of the needle are the same
1836let Some(second_probe_offset) =
1837 (needle.len().saturating_sub(4)..needle.len()).rfind(|&idx| needle[idx] != first_probe)
1838else {
1839// fall back to other search methods if we can't find any different bytes
1840 // since we could otherwise hit some degenerate cases
1841return None;
1842 };
1843second_probe_offset1844 };
18451846// do a naive search if the haystack is too small to fit
1847if haystack.len() < Block::LEN + last_byte_offset {
1848return Some(haystack.windows(needle.len()).any(|c| c == needle));
1849 }
18501851let first_probe: Block = Block::splat(first_probe);
1852let second_probe: Block = Block::splat(needle[second_probe_offset]);
1853// first byte are already checked by the outer loop. to verify a match only the
1854 // remainder has to be compared.
1855let trimmed_needle = &needle[1..];
18561857// this #[cold] is load-bearing, benchmark before removing it...
1858let check_mask = #[cold]
1859|idx, mask: u16, skip: bool| -> bool {
1860if skip {
1861return false;
1862 }
18631864// and so is this. optimizations are weird.
1865let mut mask = mask;
18661867while mask != 0 {
1868let trailing = mask.trailing_zeros();
1869let offset = idx + trailing as usize + 1;
1870// SAFETY: mask is between 0 and 15 trailing zeroes, we skip one additional byte that was already compared
1871 // and then take trimmed_needle.len() bytes. This is within the bounds defined by the outer loop
1872unsafe {
1873let sub = haystack.get_unchecked(offset..).get_unchecked(..trimmed_needle.len());
1874if small_slice_eq(sub, trimmed_needle) {
1875return true;
1876 }
1877 }
1878 mask &= !(1 << trailing);
1879 }
1880false
1881};
18821883let test_chunk = |idx| -> u16 {
1884// SAFETY: this requires at least LANES bytes being readable at idx
1885 // that is ensured by the loop ranges (see comments below)
1886let a: Block = unsafe { haystack.as_ptr().add(idx).cast::<Block>().read_unaligned() };
1887// SAFETY: this requires LANES + block_offset bytes being readable at idx
1888let b: Block = unsafe {
1889haystack.as_ptr().add(idx).add(second_probe_offset).cast::<Block>().read_unaligned()
1890 };
1891let eq_first: Mask = a.simd_eq(first_probe);
1892let eq_last: Mask = b.simd_eq(second_probe);
1893let both = eq_first.bitand(eq_last);
1894let mask = both.to_bitmask() as u16;
18951896mask1897 };
18981899let mut i = 0;
1900let mut result = false;
1901// The loop condition must ensure that there's enough headroom to read LANE bytes,
1902 // and not only at the current index but also at the index shifted by block_offset
1903const UNROLL: usize = 4;
1904while i + last_byte_offset + UNROLL * Block::LEN < haystack.len() && !result {
1905let mut masks = [0u16; UNROLL];
1906for j in 0..UNROLL {
1907 masks[j] = test_chunk(i + j * Block::LEN);
1908 }
1909for j in 0..UNROLL {
1910let mask = masks[j];
1911if mask != 0 {
1912 result |= check_mask(i + j * Block::LEN, mask, result);
1913 }
1914 }
1915 i += UNROLL * Block::LEN;
1916 }
1917while i + last_byte_offset + Block::LEN < haystack.len() && !result {
1918let mask = test_chunk(i);
1919if mask != 0 {
1920 result |= check_mask(i, mask, result);
1921 }
1922 i += Block::LEN;
1923 }
19241925// Process the tail that didn't fit into LANES-sized steps.
1926 // This simply repeats the same procedure but as right-aligned chunk instead
1927 // of a left-aligned one. The last byte must be exactly flush with the string end so
1928 // we don't miss a single byte or read out of bounds.
1929let i = haystack.len() - last_byte_offset - Block::LEN;
1930let mask = test_chunk(i);
1931if mask != 0 {
1932result |= check_mask(i, mask, result);
1933 }
19341935Some(result)
1936}
19371938/// Compares short slices for equality.
1939///
1940/// It avoids a call to libc's memcmp which is faster on long slices
1941/// due to SIMD optimizations but it incurs a function call overhead.
1942///
1943/// # Safety
1944///
1945/// Both slices must have the same length.
1946#[cfg(any(
1947 all(target_arch = "x86_64", target_feature = "sse2"),
1948 all(target_arch = "loongarch64", target_feature = "lsx"),
1949 all(target_arch = "aarch64", target_feature = "neon")
1950))]
1951#[inline]
1952unsafe fn small_slice_eq(x: &[u8], y: &[u8]) -> bool {
1953if 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());
1954// This function is adapted from
1955 // https://github.com/BurntSushi/memchr/blob/8037d11b4357b0f07be2bb66dc2659d9cf28ad32/src/memmem/util.rs#L32
19561957 // If we don't have enough bytes to do 4-byte at a time loads, then
1958 // fall back to the naive slow version.
1959 //
1960 // Potential alternative: We could do a copy_nonoverlapping combined with a mask instead
1961 // of a loop. Benchmark it.
1962if x.len() < 4 {
1963for (&b1, &b2) in x.iter().zip(y) {
1964if b1 != b2 {
1965return false;
1966 }
1967 }
1968return true;
1969 }
1970// When we have 4 or more bytes to compare, then proceed in chunks of 4 at
1971 // a time using unaligned loads.
1972 //
1973 // Also, why do 4 byte loads instead of, say, 8 byte loads? The reason is
1974 // that this particular version of memcmp is likely to be called with tiny
1975 // needles. That means that if we do 8 byte loads, then a higher proportion
1976 // of memcmp calls will use the slower variant above. With that said, this
1977 // is a hypothesis and is only loosely supported by benchmarks. There's
1978 // likely some improvement that could be made here. The main thing here
1979 // though is to optimize for latency, not throughput.
19801981 // SAFETY: Via the conditional above, we know that both `px` and `py`
1982 // have the same length, so `px < pxend` implies that `py < pyend`.
1983 // Thus, dereferencing both `px` and `py` in the loop below is safe.
1984 //
1985 // Moreover, we set `pxend` and `pyend` to be 4 bytes before the actual
1986 // end of `px` and `py`. Thus, the final dereference outside of the
1987 // loop is guaranteed to be valid. (The final comparison will overlap with
1988 // the last comparison done in the loop for lengths that aren't multiples
1989 // of four.)
1990 //
1991 // Finally, we needn't worry about alignment here, since we do unaligned
1992 // loads.
1993unsafe {
1994let (mut px, mut py) = (x.as_ptr(), y.as_ptr());
1995let (pxend, pyend) = (px.add(x.len() - 4), py.add(y.len() - 4));
1996while px < pxend {
1997let vx = (px as *const u32).read_unaligned();
1998let vy = (py as *const u32).read_unaligned();
1999if vx != vy {
2000return false;
2001 }
2002 px = px.add(4);
2003 py = py.add(4);
2004 }
2005let vx = (pxendas *const u32).read_unaligned();
2006let vy = (pyendas *const u32).read_unaligned();
2007vx == vy2008 }
2009}