const STD_HAS_SIMD_CONTAINS: bool = cfg!(any(
all(target_arch = "x86_64", target_feature = "sse2"),
all(target_arch = "loongarch64", target_feature = "lsx"),
all(target_arch = "aarch64", target_feature = "neon")
));
const STD_CONTAINS_BLOCK: usize = 16;
const STD_RFIND_BASE: usize = 24;
const STD_RFIND_PER_NEEDLE_BYTE: usize = 2;
#[inline]
fn std_rfind_is_faster(haystack: usize, needle: usize) -> bool {
haystack >= STD_RFIND_BASE.saturating_add(needle.saturating_mul(STD_RFIND_PER_NEEDLE_BYTE))
}
pub(crate) const SHORT_NEEDLE_MAX: usize = 32;
const SCREEN_BLOCK: usize = 16;
const SCREENED_MAX_HAYSTACK: usize = 256;
#[inline]
const fn find_screen_limit(needle: usize) -> usize {
if cfg!(target_arch = "aarch64") {
match needle {
0..=3 => 64,
4..=15 => 160,
_ => SCREENED_MAX_HAYSTACK,
}
} else {
SCREENED_MAX_HAYSTACK
}
}
const SHORT_NEEDLE_FALSE_CANDIDATES: usize = 4;
pub(crate) enum ShortSearch {
Found(usize),
Missing,
TooManyFalseCandidates(usize),
}
#[inline(always)]
fn screen_block(bytes: &[u8], start: usize, span: usize, first: u8, last: u8) -> u32 {
let heads: &[u8; SCREEN_BLOCK] = bytes[start..start + SCREEN_BLOCK]
.try_into()
.expect("a block of heads");
let tails: &[u8; SCREEN_BLOCK] = bytes[start + span..start + span + SCREEN_BLOCK]
.try_into()
.expect("a block of tails");
let mut hits = 0u32;
for i in 0..SCREEN_BLOCK {
hits |= u32::from((heads[i] == first) & (tails[i] == last)) << i;
}
hits
}
#[inline]
pub(crate) fn find_short(haystack: &str, needle: &str) -> ShortSearch {
let bytes = haystack.as_bytes();
let pattern = needle.as_bytes();
let span = pattern.len() - 1;
let (first, last_byte, middle) = (pattern[0], pattern[span], &pattern[1..span]);
let Some(last) = bytes.len().checked_sub(pattern.len()) else {
return ShortSearch::Missing;
};
let middle_matches = |at: usize| crate::compare::bytes_eq(&bytes[at + 1..at + span], middle);
let mut false_candidates = 0;
let mut at = 0;
while at + SCREEN_BLOCK <= last + 1 {
let mut hits = screen_block(bytes, at, span, first, last_byte);
while hits != 0 {
let candidate = at + hits.trailing_zeros() as usize;
if middle_matches(candidate) {
return ShortSearch::Found(candidate);
}
false_candidates += 1;
if false_candidates > SHORT_NEEDLE_FALSE_CANDIDATES {
return ShortSearch::TooManyFalseCandidates(candidate);
}
hits &= hits - 1;
}
at += SCREEN_BLOCK;
}
match (at..=last)
.find(|&i| bytes[i] == first && bytes[i + span] == last_byte && middle_matches(i))
{
Some(found) => ShortSearch::Found(found),
None => ShortSearch::Missing,
}
}
#[inline]
fn rfind_short(haystack: &str, needle: &str) -> ShortSearch {
let bytes = haystack.as_bytes();
let pattern = needle.as_bytes();
let span = pattern.len() - 1;
let (first, last_byte, middle) = (pattern[0], pattern[span], &pattern[1..span]);
let Some(last) = bytes.len().checked_sub(pattern.len()) else {
return ShortSearch::Missing;
};
let middle_matches = |at: usize| crate::compare::bytes_eq(&bytes[at + 1..at + span], middle);
let mut false_candidates = 0;
let mut end = last + 1;
while end >= SCREEN_BLOCK {
let start = end - SCREEN_BLOCK;
let mut hits = screen_block(bytes, start, span, first, last_byte);
while hits != 0 {
let offset = 31 - hits.leading_zeros() as usize;
let candidate = start + offset;
if middle_matches(candidate) {
return ShortSearch::Found(candidate);
}
false_candidates += 1;
if false_candidates > SHORT_NEEDLE_FALSE_CANDIDATES {
return ShortSearch::TooManyFalseCandidates(candidate);
}
hits &= !(1 << offset);
}
end = start;
}
match (0..end)
.rev()
.find(|&i| bytes[i] == first && bytes[i + span] == last_byte && middle_matches(i))
{
Some(found) => ShortSearch::Found(found),
None => ShortSearch::Missing,
}
}
#[inline]
fn whole_match(haystack: &str, needle: &str) -> bool {
crate::compare::bytes_eq(haystack.as_bytes(), needle.as_bytes())
}
#[inline]
pub(crate) fn contains_str(haystack: &str, needle: &str) -> bool {
match needle.len() {
0 => true,
1 => memchr::memchr(needle.as_bytes()[0], haystack.as_bytes()).is_some(),
n if n >= haystack.len() => whole_match(haystack, needle),
n if STD_HAS_SIMD_CONTAINS
&& n <= SHORT_NEEDLE_MAX
&& haystack.len() >= STD_CONTAINS_BLOCK + n - 1 =>
{
std_contains(haystack, needle)
}
_ => contains_without_std_simd(haystack, needle),
}
}
#[inline(never)]
fn std_contains(haystack: &str, needle: &str) -> bool {
haystack.contains(needle)
}
#[inline(never)]
fn std_rfind(haystack: &str, needle: &str) -> Option<usize> {
haystack.rfind(needle)
}
#[inline]
pub(crate) fn find_str(haystack: &str, needle: &str) -> Option<usize> {
match needle.len() {
0 => Some(0),
1 => memchr::memchr(needle.as_bytes()[0], haystack.as_bytes()),
n if n >= haystack.len() => whole_match(haystack, needle).then_some(0),
n if n <= SHORT_NEEDLE_MAX && haystack.len() < find_screen_limit(n) => {
find_screened(haystack, needle)
}
_ => memchr::memmem::find(haystack.as_bytes(), needle.as_bytes()),
}
}
#[inline]
pub(crate) fn rfind_str(haystack: &str, needle: &str) -> Option<usize> {
match needle.len() {
0 => Some(haystack.len()),
1 => memchr::memrchr(needle.as_bytes()[0], haystack.as_bytes()),
n if n >= haystack.len() => whole_match(haystack, needle).then_some(0),
n if n <= SHORT_NEEDLE_MAX && haystack.len() < SCREENED_MAX_HAYSTACK => {
rfind_screened(haystack, needle)
}
n if std_rfind_is_faster(haystack.len(), n) => std_rfind(haystack, needle),
_ => memchr::memmem::rfind(haystack.as_bytes(), needle.as_bytes()),
}
}
#[inline(never)]
fn contains_without_std_simd(haystack: &str, needle: &str) -> bool {
if needle.len() <= SHORT_NEEDLE_MAX
&& (STD_HAS_SIMD_CONTAINS || haystack.len() < SCREENED_MAX_HAYSTACK)
{
return match find_short(haystack, needle) {
ShortSearch::Found(_) => true,
ShortSearch::Missing => false,
ShortSearch::TooManyFalseCandidates(from) => std_contains(&haystack[from..], needle),
};
}
memchr::memmem::find(haystack.as_bytes(), needle.as_bytes()).is_some()
}
#[inline(never)]
fn find_screened(haystack: &str, needle: &str) -> Option<usize> {
match find_short(haystack, needle) {
ShortSearch::Found(at) => Some(at),
ShortSearch::Missing => None,
ShortSearch::TooManyFalseCandidates(from) => {
haystack[from..].find(needle).map(|offset| from + offset)
}
}
}
#[inline(never)]
fn rfind_screened(haystack: &str, needle: &str) -> Option<usize> {
match rfind_short(haystack, needle) {
ShortSearch::Found(at) => Some(at),
ShortSearch::Missing => None,
ShortSearch::TooManyFalseCandidates(before) => {
let mut end = before + needle.len() - 1;
while !haystack.is_char_boundary(end) {
end += 1;
}
std_rfind(&haystack[..end], needle)
}
}
}
pub struct CheetahFinder<'a> {
needle: &'a str,
finder: Option<memchr::memmem::Finder<'a>>,
}
impl<'a> CheetahFinder<'a> {
#[inline]
pub fn new(needle: &'a str) -> Self {
let finder = (needle.len() > 1).then(|| memchr::memmem::Finder::new(needle.as_bytes()));
Self { needle, finder }
}
#[inline]
pub fn needle(&self) -> &'a str {
self.needle
}
#[inline]
pub fn find_in<S>(&self, haystack: &S) -> Option<usize>
where
S: AsRef<str> + ?Sized,
{
let haystack = haystack.as_ref().as_bytes();
if self.needle.is_empty() {
return Some(0);
}
if self.needle.len() == 1 {
return memchr::memchr(self.needle.as_bytes()[0], haystack);
}
self.finder
.as_ref()
.and_then(|finder| finder.find(haystack))
}
#[inline]
pub fn is_match<S>(&self, haystack: &S) -> bool
where
S: AsRef<str> + ?Sized,
{
self.find_in(haystack).is_some()
}
}
#[cfg(test)]
mod tests {
use super::{contains_without_std_simd, find_screen_limit, SCREENED_MAX_HAYSTACK};
use alloc::format;
use alloc::string::String;
#[test]
fn screened_contains_matches_str_with_full_blocks() {
let mut texts: alloc::vec::Vec<String> = alloc::vec::Vec::new();
for len in [16usize, 17, 31, 32, 33, 47, 48, 64, 100, 128, 200, 255] {
texts.push("xy".chars().cycle().take(len).collect());
}
texts.push(format!("{}a_b", "aXb".repeat(30)));
texts.push(format!("a_b{}", "aXb".repeat(30)));
texts.push("\u{e9}X\u{e9}".repeat(20) + "\u{e9}_\u{e9}");
for text in &texts {
for needle in [
"xy",
"yx",
"yy",
"a_b",
"<-->",
"\u{e9}_\u{e9}",
"exactly-thirty-two-bytes-long!!!",
] {
if needle.len() >= text.len() || text.len() >= SCREENED_MAX_HAYSTACK {
continue;
}
assert_eq!(
contains_without_std_simd(text, needle),
text.contains(needle),
"{text:?} {needle:?}"
);
for at in [0, 15, 16, 17, 31, 32, text.len() - needle.len()] {
if at + needle.len() > text.len() || !text.is_char_boundary(at) {
continue;
}
let end = at + needle.len();
if !text.is_char_boundary(end) {
continue;
}
let mut placed = text.clone();
placed.replace_range(at..end, needle);
assert_eq!(
contains_without_std_simd(&placed, needle),
placed.contains(needle),
"{placed:?} {needle:?}"
);
}
}
}
}
#[test]
fn find_screen_limit_stays_within_the_screened_range() {
for needle in 2..=super::SHORT_NEEDLE_MAX {
let limit = find_screen_limit(needle);
assert!(limit <= SCREENED_MAX_HAYSTACK);
assert!(
limit > needle,
"a needle of {needle} bytes must be screenable"
);
}
if cfg!(target_arch = "aarch64") {
assert_eq!(find_screen_limit(2), 64);
assert_eq!(find_screen_limit(8), 160);
assert_eq!(find_screen_limit(16), SCREENED_MAX_HAYSTACK);
} else {
assert_eq!(find_screen_limit(2), SCREENED_MAX_HAYSTACK);
}
}
}