1const STD_HAS_SIMD_CONTAINS: bool = cfg!(any(
26 all(target_arch = "x86_64", target_feature = "sse2"),
27 all(target_arch = "loongarch64", target_feature = "lsx"),
28 all(target_arch = "aarch64", target_feature = "neon")
29));
30const STD_CONTAINS_BLOCK: usize = 16;
31
32const STD_RFIND_BASE: usize = 24;
37const STD_RFIND_PER_NEEDLE_BYTE: usize = 2;
38
39#[inline]
40fn std_rfind_is_faster(haystack: usize, needle: usize) -> bool {
41 haystack >= STD_RFIND_BASE.saturating_add(needle.saturating_mul(STD_RFIND_PER_NEEDLE_BYTE))
42}
43
44pub(crate) const SHORT_NEEDLE_MAX: usize = 32;
49
50const SCREEN_BLOCK: usize = 16;
52
53const SCREENED_MAX_HAYSTACK: usize = 256;
56
57#[inline]
65const fn find_screen_limit(needle: usize) -> usize {
66 if cfg!(target_arch = "aarch64") {
67 match needle {
68 0..=3 => 64,
69 4..=15 => 160,
70 _ => SCREENED_MAX_HAYSTACK,
71 }
72 } else {
73 SCREENED_MAX_HAYSTACK
74 }
75}
76
77const SHORT_NEEDLE_FALSE_CANDIDATES: usize = 4;
82
83pub(crate) enum ShortSearch {
85 Found(usize),
88 Missing,
90 TooManyFalseCandidates(usize),
97}
98
99#[inline(always)]
104fn screen_block(bytes: &[u8], start: usize, span: usize, first: u8, last: u8) -> u32 {
105 let heads: &[u8; SCREEN_BLOCK] = bytes[start..start + SCREEN_BLOCK]
106 .try_into()
107 .expect("a block of heads");
108 let tails: &[u8; SCREEN_BLOCK] = bytes[start + span..start + span + SCREEN_BLOCK]
109 .try_into()
110 .expect("a block of tails");
111 let mut hits = 0u32;
112 for i in 0..SCREEN_BLOCK {
113 hits |= u32::from((heads[i] == first) & (tails[i] == last)) << i;
114 }
115 hits
116}
117
118#[inline]
126pub(crate) fn find_short(haystack: &str, needle: &str) -> ShortSearch {
127 let bytes = haystack.as_bytes();
128 let pattern = needle.as_bytes();
129 let span = pattern.len() - 1;
130 let (first, last_byte, middle) = (pattern[0], pattern[span], &pattern[1..span]);
131 let Some(last) = bytes.len().checked_sub(pattern.len()) else {
133 return ShortSearch::Missing;
134 };
135 let middle_matches = |at: usize| crate::compare::bytes_eq(&bytes[at + 1..at + span], middle);
136 let mut false_candidates = 0;
137
138 let mut at = 0;
139 while at + SCREEN_BLOCK <= last + 1 {
142 let mut hits = screen_block(bytes, at, span, first, last_byte);
143 while hits != 0 {
144 let candidate = at + hits.trailing_zeros() as usize;
145 if middle_matches(candidate) {
146 return ShortSearch::Found(candidate);
147 }
148 false_candidates += 1;
149 if false_candidates > SHORT_NEEDLE_FALSE_CANDIDATES {
150 return ShortSearch::TooManyFalseCandidates(candidate);
151 }
152 hits &= hits - 1;
153 }
154 at += SCREEN_BLOCK;
155 }
156 match (at..=last)
157 .find(|&i| bytes[i] == first && bytes[i + span] == last_byte && middle_matches(i))
158 {
159 Some(found) => ShortSearch::Found(found),
160 None => ShortSearch::Missing,
161 }
162}
163#[inline]
169fn rfind_short(haystack: &str, needle: &str) -> ShortSearch {
170 let bytes = haystack.as_bytes();
171 let pattern = needle.as_bytes();
172 let span = pattern.len() - 1;
173 let (first, last_byte, middle) = (pattern[0], pattern[span], &pattern[1..span]);
174 let Some(last) = bytes.len().checked_sub(pattern.len()) else {
175 return ShortSearch::Missing;
176 };
177 let middle_matches = |at: usize| crate::compare::bytes_eq(&bytes[at + 1..at + span], middle);
178 let mut false_candidates = 0;
179
180 let mut end = last + 1;
182 while end >= SCREEN_BLOCK {
183 let start = end - SCREEN_BLOCK;
184 let mut hits = screen_block(bytes, start, span, first, last_byte);
185 while hits != 0 {
186 let offset = 31 - hits.leading_zeros() as usize;
187 let candidate = start + offset;
188 if middle_matches(candidate) {
189 return ShortSearch::Found(candidate);
190 }
191 false_candidates += 1;
192 if false_candidates > SHORT_NEEDLE_FALSE_CANDIDATES {
193 return ShortSearch::TooManyFalseCandidates(candidate);
194 }
195 hits &= !(1 << offset);
196 }
197 end = start;
198 }
199 match (0..end)
200 .rev()
201 .find(|&i| bytes[i] == first && bytes[i + span] == last_byte && middle_matches(i))
202 {
203 Some(found) => ShortSearch::Found(found),
204 None => ShortSearch::Missing,
205 }
206}
207
208#[inline]
211fn whole_match(haystack: &str, needle: &str) -> bool {
212 crate::compare::bytes_eq(haystack.as_bytes(), needle.as_bytes())
213}
214
215#[inline]
216pub(crate) fn contains_str(haystack: &str, needle: &str) -> bool {
217 match needle.len() {
218 0 => true,
219 1 => memchr::memchr(needle.as_bytes()[0], haystack.as_bytes()).is_some(),
220 n if n >= haystack.len() => whole_match(haystack, needle),
221 n if STD_HAS_SIMD_CONTAINS
222 && n <= SHORT_NEEDLE_MAX
223 && haystack.len() >= STD_CONTAINS_BLOCK + n - 1 =>
224 {
225 std_contains(haystack, needle)
226 }
227 _ => contains_without_std_simd(haystack, needle),
230 }
231}
232
233#[inline(never)]
251fn std_contains(haystack: &str, needle: &str) -> bool {
252 haystack.contains(needle)
253}
254
255#[inline(never)]
256fn std_rfind(haystack: &str, needle: &str) -> Option<usize> {
257 haystack.rfind(needle)
258}
259
260#[inline]
261pub(crate) fn find_str(haystack: &str, needle: &str) -> Option<usize> {
262 match needle.len() {
263 0 => Some(0),
264 1 => memchr::memchr(needle.as_bytes()[0], haystack.as_bytes()),
265 n if n >= haystack.len() => whole_match(haystack, needle).then_some(0),
266 n if n <= SHORT_NEEDLE_MAX && haystack.len() < find_screen_limit(n) => {
267 find_screened(haystack, needle)
268 }
269 _ => memchr::memmem::find(haystack.as_bytes(), needle.as_bytes()),
270 }
271}
272
273#[inline]
274pub(crate) fn rfind_str(haystack: &str, needle: &str) -> Option<usize> {
275 match needle.len() {
276 0 => Some(haystack.len()),
277 1 => memchr::memrchr(needle.as_bytes()[0], haystack.as_bytes()),
278 n if n >= haystack.len() => whole_match(haystack, needle).then_some(0),
279 n if n <= SHORT_NEEDLE_MAX && haystack.len() < SCREENED_MAX_HAYSTACK => {
280 rfind_screened(haystack, needle)
281 }
282 n if std_rfind_is_faster(haystack.len(), n) => std_rfind(haystack, needle),
283 _ => memchr::memmem::rfind(haystack.as_bytes(), needle.as_bytes()),
284 }
285}
286
287#[inline(never)]
295fn contains_without_std_simd(haystack: &str, needle: &str) -> bool {
296 if needle.len() <= SHORT_NEEDLE_MAX
297 && (STD_HAS_SIMD_CONTAINS || haystack.len() < SCREENED_MAX_HAYSTACK)
298 {
299 return match find_short(haystack, needle) {
300 ShortSearch::Found(_) => true,
301 ShortSearch::Missing => false,
302 ShortSearch::TooManyFalseCandidates(from) => std_contains(&haystack[from..], needle),
303 };
304 }
305 memchr::memmem::find(haystack.as_bytes(), needle.as_bytes()).is_some()
306}
307
308#[inline(never)]
309fn find_screened(haystack: &str, needle: &str) -> Option<usize> {
310 match find_short(haystack, needle) {
311 ShortSearch::Found(at) => Some(at),
312 ShortSearch::Missing => None,
313 ShortSearch::TooManyFalseCandidates(from) => {
314 haystack[from..].find(needle).map(|offset| from + offset)
315 }
316 }
317}
318
319#[inline(never)]
320fn rfind_screened(haystack: &str, needle: &str) -> Option<usize> {
321 match rfind_short(haystack, needle) {
322 ShortSearch::Found(at) => Some(at),
323 ShortSearch::Missing => None,
324 ShortSearch::TooManyFalseCandidates(before) => {
325 let mut end = before + needle.len() - 1;
330 while !haystack.is_char_boundary(end) {
331 end += 1;
332 }
333 std_rfind(&haystack[..end], needle)
334 }
335 }
336}
337
338pub struct CheetahFinder<'a> {
340 needle: &'a str,
341 finder: Option<memchr::memmem::Finder<'a>>,
342}
343
344impl<'a> CheetahFinder<'a> {
345 #[inline]
347 pub fn new(needle: &'a str) -> Self {
348 let finder = (needle.len() > 1).then(|| memchr::memmem::Finder::new(needle.as_bytes()));
349 Self { needle, finder }
350 }
351
352 #[inline]
354 pub fn needle(&self) -> &'a str {
355 self.needle
356 }
357
358 #[inline]
360 pub fn find_in<S>(&self, haystack: &S) -> Option<usize>
361 where
362 S: AsRef<str> + ?Sized,
363 {
364 let haystack = haystack.as_ref().as_bytes();
365
366 if self.needle.is_empty() {
367 return Some(0);
368 }
369
370 if self.needle.len() == 1 {
371 return memchr::memchr(self.needle.as_bytes()[0], haystack);
372 }
373
374 self.finder
375 .as_ref()
376 .and_then(|finder| finder.find(haystack))
377 }
378
379 #[inline]
381 pub fn is_match<S>(&self, haystack: &S) -> bool
382 where
383 S: AsRef<str> + ?Sized,
384 {
385 self.find_in(haystack).is_some()
386 }
387}
388
389#[cfg(test)]
390mod tests {
391 use super::{contains_without_std_simd, find_screen_limit, SCREENED_MAX_HAYSTACK};
392 use alloc::format;
393 use alloc::string::String;
394
395 #[test]
400 fn screened_contains_matches_str_with_full_blocks() {
401 let mut texts: alloc::vec::Vec<String> = alloc::vec::Vec::new();
402 for len in [16usize, 17, 31, 32, 33, 47, 48, 64, 100, 128, 200, 255] {
403 texts.push("xy".chars().cycle().take(len).collect());
404 }
405 texts.push(format!("{}a_b", "aXb".repeat(30)));
406 texts.push(format!("a_b{}", "aXb".repeat(30)));
407 texts.push("\u{e9}X\u{e9}".repeat(20) + "\u{e9}_\u{e9}");
408 for text in &texts {
409 for needle in [
410 "xy",
411 "yx",
412 "yy",
413 "a_b",
414 "<-->",
415 "\u{e9}_\u{e9}",
416 "exactly-thirty-two-bytes-long!!!",
417 ] {
418 if needle.len() >= text.len() || text.len() >= SCREENED_MAX_HAYSTACK {
419 continue;
420 }
421 assert_eq!(
422 contains_without_std_simd(text, needle),
423 text.contains(needle),
424 "{text:?} {needle:?}"
425 );
426 for at in [0, 15, 16, 17, 31, 32, text.len() - needle.len()] {
428 if at + needle.len() > text.len() || !text.is_char_boundary(at) {
429 continue;
430 }
431 let end = at + needle.len();
432 if !text.is_char_boundary(end) {
433 continue;
434 }
435 let mut placed = text.clone();
436 placed.replace_range(at..end, needle);
437 assert_eq!(
438 contains_without_std_simd(&placed, needle),
439 placed.contains(needle),
440 "{placed:?} {needle:?}"
441 );
442 }
443 }
444 }
445 }
446
447 #[test]
448 fn find_screen_limit_stays_within_the_screened_range() {
449 for needle in 2..=super::SHORT_NEEDLE_MAX {
450 let limit = find_screen_limit(needle);
451 assert!(limit <= SCREENED_MAX_HAYSTACK);
452 assert!(
453 limit > needle,
454 "a needle of {needle} bytes must be screenable"
455 );
456 }
457 if cfg!(target_arch = "aarch64") {
458 assert_eq!(find_screen_limit(2), 64);
459 assert_eq!(find_screen_limit(8), 160);
460 assert_eq!(find_screen_limit(16), SCREENED_MAX_HAYSTACK);
461 } else {
462 assert_eq!(find_screen_limit(2), SCREENED_MAX_HAYSTACK);
463 }
464 }
465}