diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ff5740..0f71a76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,18 +76,19 @@ - `contains`, `find`, and `rfind` choose their search backend by haystack and needle length, using thresholds measured on x86_64 and aarch64 with `benches/search_thresholds.rs`. A needle at least as long as the haystack - is answered by one comparison. `contains` uses the standard library's SIMD - search for 2- to 32-byte needles once the haystack holds a 16-byte block - plus the needle. `find` uses `str::find` when - `16 + 3 * needle <= haystack < 64`, and `rfind` uses `str::rfind` when - `haystack >= 24 + 2 * needle`; every other search uses a one-shot `memmem`. - On an i7-11700K the backend `find` picked was 16% slower than the faster - one on geometric mean and up to 4.3x slower in the worst case; it is now - within 0.5% and 1.3x (`rfind`: 11% and 3.7x before, under 1% and 1.5x - after). The `ubuntu-latest` and `ubuntu-24.04-arm` runners stay within 4% - and 1.8x. A 16-byte needle in a 32-byte haystack fell from 43 ns to 18 ns - for both. The `Search thresholds` workflow reruns the measurement on both - targets when `src/search.rs` changes. + is answered by one comparison. Needles of 2 to 32 bytes in haystacks under + 256 bytes use the screened search that `split_str` uses, which needs no + setup: `find` and `rfind` always, and `contains` where the standard + library's SIMD search cannot run, that is, before the haystack holds a + 16-byte block plus the needle. Longer haystacks use a one-shot `memmem` for + `find` and `str::rfind` for `rfind` (from `24 + 2 * needle` bytes). On an + i7-11700K, across the benchmark's inputs, `find` now takes 0.64 and + `rfind` 0.59 of the time of the faster of `str` and `memmem` on geometric + mean. A 16-byte needle in a 64-byte haystack takes 9 ns with `find` and + 8 ns with `rfind`, against 46 ns and 54 ns with the best fixed backend. + Haystacks of 16 bytes with 2-byte needles are 1 to 2 ns slower, as they + never fill a screening block. The `Search thresholds` workflow reruns the + measurement on both targets when `src/search.rs` changes. ### Added diff --git a/README.md b/README.md index ae7a4ed..bc34819 100644 --- a/README.md +++ b/README.md @@ -128,14 +128,14 @@ value.push_str("@group-a"); Equality, prefix, and suffix checks compare up to 64 bytes with overlapping fixed-size loads instead of calling `memcmp`, and use `memcmp` beyond that. Substring search picks its backend by haystack and needle length, with -thresholds measured on x86_64 and aarch64: `contains` uses the standard -library's SIMD search for 2- to 32-byte needles once the text spans a -16-byte block plus the needle. `find` uses std only for haystacks under 64 -bytes that are at least `16 + 3 * needle` long, and `rfind` uses std once -the haystack is at least `24 + 2 * needle` long; otherwise both use -`memchr::memmem`. Single-byte needles use `memchr`, and a needle at least as -long as the text is answered by one comparison. Use `CheetahFinder` to -search for one needle repeatedly. +thresholds measured on x86_64 and aarch64. Needles of 2 to 32 bytes in text +under 256 bytes use a screened search with no setup: 16 positions at a time +are checked against the needle's first and last bytes, and only positions +that pass compare the middle. `contains` keeps the standard library's SIMD +search once the text spans a 16-byte block plus the needle. Longer text uses +`memchr::memmem` for `find` and `str::rfind` for `rfind`. Single-byte +needles use `memchr`, and a needle at least as long as the text is answered +by one comparison. Use `CheetahFinder` to search for one needle repeatedly. Iterator capabilities are explicit: diff --git a/src/cheetah_string/pattern.rs b/src/cheetah_string/pattern.rs index a044438..b41780b 100644 --- a/src/cheetah_string/pattern.rs +++ b/src/cheetah_string/pattern.rs @@ -1,3 +1,4 @@ +use crate::search::{find_short, ShortSearch, SHORT_NEEDLE_MAX}; use alloc::string::String; use core::str; @@ -135,27 +136,12 @@ enum SplitStrInner<'a, 'p> { Short(ShortSplit<'a, 'p>), } -/// Separators of 2 up to this many bytes are found by [`find_short`], which -/// needs no setup, instead of the Two-Way searcher that `str::split` builds on -/// every call. The middle of a candidate is checked with `compare::bytes_eq`, -/// which handles up to 64 bytes without a `memcmp` call. -const SHORT_SEPARATOR_MAX: usize = 32; - -/// Candidate positions screened together by [`find_short`]. -const SCREEN_BLOCK: usize = 16; - -/// Positions that pass the screen but not the full comparison, tolerated in -/// one search before the split hands the rest of the text to `str::split`. -/// Ordinary text rarely has any; text built to defeat the screen pays for at -/// most this many, once per split. -const SHORT_SEPARATOR_FALSE_CANDIDATES: usize = 4; - impl<'a, 'p> SplitStr<'a, 'p> { #[inline] pub(super) fn new(value: &'a str, pattern: &'p str) -> Self { let inner = match single_char_pattern(pattern) { Some(ch) => SplitStrInner::Char(value.split(ch)), - None if (2..=SHORT_SEPARATOR_MAX).contains(&pattern.len()) => { + None if (2..=SHORT_NEEDLE_MAX).contains(&pattern.len()) => { SplitStrInner::Short(ShortSplit { rest: Some(value), separator: pattern, @@ -168,7 +154,7 @@ impl<'a, 'p> SplitStr<'a, 'p> { } } -/// Forward split by a separator of 2 to [`SHORT_SEPARATOR_MAX`] bytes that +/// Forward split by a separator of 2 to [`SHORT_NEEDLE_MAX`] bytes that /// yields the same pieces as `str::split`: matches are leftmost and do not /// overlap. A match of valid UTF-8 inside valid UTF-8 starts and ends on /// character boundaries, so the slices never split a character. @@ -179,74 +165,6 @@ struct ShortSplit<'a, 'p> { separator: &'p str, } -/// The outcome of [`find_short`]. -enum ShortSearch { - /// The first match starts here. - Found(usize), - /// The text holds no match. - Missing, - /// More than [`SHORT_SEPARATOR_FALSE_CANDIDATES`] positions passed the - /// screen without matching, the last at this position; a Two-Way searcher - /// suits this text better. Nothing before the position matches, and the - /// position holds the needle's first byte, so it is a character boundary. - TooManyFalseCandidates(usize), -} - -/// Returns the first position of `needle`, of 2 to [`SHORT_SEPARATOR_MAX`] -/// bytes, in `haystack`. -/// -/// Positions are screened [`SCREEN_BLOCK`] at a time on the needle's first and -/// last bytes, in a fixed-size loop the compiler turns into vector compares, -/// and only positions that pass compare the middle. Text that merely repeats -/// the separator's first byte, or its leading bytes, produces no candidates. -#[inline] -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]); - // The last position where a whole separator still fits. - 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; - // Every position of a block, plus `span`, stays inside the text while - // `at + SCREEN_BLOCK <= last + 1`. - while at + SCREEN_BLOCK <= last + 1 { - let heads: &[u8; SCREEN_BLOCK] = bytes[at..at + SCREEN_BLOCK] - .try_into() - .expect("a block of heads"); - let tails: &[u8; SCREEN_BLOCK] = bytes[at + span..at + 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_byte)) << i; - } - 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_SEPARATOR_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 single_char_pattern(pattern: &str) -> Option { let mut chars = pattern.chars(); diff --git a/src/cheetah_string/query.rs b/src/cheetah_string/query.rs index 086e9ec..4cd65dc 100644 --- a/src/cheetah_string/query.rs +++ b/src/cheetah_string/query.rs @@ -94,9 +94,9 @@ impl CheetahString { /// Returns `true` if the string contains the given pattern. /// /// Needles of 2 to 32 bytes on text that spans a 16-byte block plus the - /// needle use the standard library's SIMD search, and a needle at least as - /// long as the text is answered by one comparison; other cases use - /// `memchr`/`memmem`. + /// needle use the standard library's SIMD search, and on shorter text a + /// screened search with no setup. A needle at least as long as the text is + /// answered by one comparison; other cases use `memchr`/`memmem`. /// /// # Examples /// @@ -136,9 +136,9 @@ impl CheetahString { /// Returns the byte index of the first occurrence of the pattern, or `None` if not found. /// - /// Text under 64 bytes that is at least `16 + 3 * needle` bytes long uses - /// `str::find`; other text uses `memchr::memmem`, and a needle at least as - /// long as the text is answered by one comparison. Use + /// Needles of 2 to 32 bytes in text under 256 bytes use a screened search + /// with no setup; other text uses `memchr::memmem`, and a needle at least + /// as long as the text is answered by one comparison. Use /// [`CheetahString::find_char`] for a `char` pattern and /// [`crate::CheetahFinder`] to search for the same needle repeatedly. /// @@ -159,9 +159,11 @@ impl CheetahString { /// Returns the byte index of the last occurrence of the pattern, or `None` if not found. /// - /// Text at least `24 + 2 * needle` bytes long uses `str::rfind`; shorter - /// text uses `memchr::memmem`, and a needle at least as long as the text is - /// answered by one comparison. + /// Needles of 2 to 32 bytes in text under 256 bytes use a screened search + /// with no setup, scanning from the end. Other text at least + /// `24 + 2 * needle` bytes long uses `str::rfind` and shorter text + /// `memchr::memmem`; a needle at least as long as the text is answered by + /// one comparison. /// /// # Examples /// diff --git a/src/lib.rs b/src/lib.rs index 04b782c..f38a6ce 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -38,12 +38,13 @@ //! words, also without a `memcmp` call. //! //! Substring search picks its backend by haystack and needle length, with -//! thresholds measured on x86_64 and aarch64: short needles on text that -//! spans a 16-byte block plus the needle use the standard library's SIMD -//! `contains`; `find()` uses `str::find` only for text under 64 bytes that is -//! at least `16 + 3 * needle` long, and `rfind()` uses `str::rfind` once the -//! text is at least `24 + 2 * needle` long; other searches use -//! `memchr::memmem`. A needle at least as long as the text is answered by one +//! thresholds measured on x86_64 and aarch64. Needles of 2 to 32 bytes in +//! text under 256 bytes use a screened search that needs no setup: it checks +//! 16 positions at a time against the needle's first and last bytes and +//! compares the middle only where both match. `contains` keeps the standard +//! library's SIMD search once the text spans a 16-byte block plus the needle. +//! Longer text uses `memchr::memmem` for `find()` and `str::rfind` for +//! `rfind()`. A needle at least as long as the text is answered by one //! comparison. Use [`CheetahFinder`] to search for one needle repeatedly. //! //! # Retired experimental features diff --git a/src/search.rs b/src/search.rs index 0e4b1c7..9e83852 100644 --- a/src/search.rs +++ b/src/search.rs @@ -9,54 +9,174 @@ // haystack, so one comparison answers it. std does the same for `contains`, // while `memmem` would still hash the single candidate position. // +// Needles of 2 to 32 bytes on haystacks shorter than 256 bytes use the +// screened search below, which needs no setup: it beat one-shot `memmem` +// (Rabin-Karp below 64 bytes) and std's Two-Way searchers there. From 256 +// bytes the SIMD scans of `memmem` and std win. +// // `str::contains` has a SIMD fast path for needles of 2..=32 bytes once the -// haystack holds one 16-byte block plus the needle, and it beat a one-shot -// `memmem::find` at almost every such length. Below that size std falls back -// to a byte-window scan, and above 32-byte needles it builds a Two-Way -// searcher, so memmem stays the better choice there. +// haystack holds one 16-byte block plus the needle, and it beat the screen +// there, so `contains` keeps it and screens only shorter haystacks. Above +// 32-byte needles std builds a Two-Way searcher, so memmem stays the better +// choice there. // // std only has that fast path on these targets; elsewhere it always builds a -// Two-Way searcher, so memmem remains the better default. +// Two-Way searcher, so `contains` screens up to 256 bytes like `find`. 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_MAX_NEEDLE: usize = 32; const STD_CONTAINS_BLOCK: usize = 16; -// One-shot `memmem::find` and `memmem::rfind` use Rabin-Karp below 64 bytes, -// whose cost grows with the number of candidate positions, while `str::find` -// and `str::rfind` build a Two-Way searcher whose setup grows with the needle. -// std therefore wins only when the haystack is long relative to the needle: -// -// - `find` uses std when `16 + 3 * needle <= haystack < 64`. From 64 bytes -// memmem's SIMD prefilter won at every needle length on the i7 and on -// aarch64. The `ubuntu-latest` runner favoured std up to 128 bytes for 4 to -// 16-byte needles, but moving the cutoff there cost more elsewhere. -// - `rfind` uses std when `haystack >= 24 + 2 * needle`. `memmem::rfind` has -// no prefilter, so std stays ahead on long haystacks. -// -// On every machine these rules stayed within 4% of the faster strategy on -// geometric mean and within 1.8x in the worst case. The fixed cutoffs they -// replace, std for `find` from 24 to 127 bytes and for `rfind` from 24 bytes, -// were 9-17% slower on geometric mean and up to 4.3x slower with 8 to -// 32-byte needles. -const STD_FIND_BASE: usize = 16; -const STD_FIND_PER_NEEDLE_BYTE: usize = 3; -const MEMMEM_FIND_MIN_HAYSTACK: usize = 64; +// `memmem::rfind` has no prefilter, so outside the screen `rfind` uses +// `str::rfind` once `haystack >= 24 + 2 * needle`: a one-shot `memmem::rfind` +// uses Rabin-Karp below 64 bytes, whose cost grows with the candidate +// positions, while std's setup grows with the needle. const STD_RFIND_BASE: usize = 24; const STD_RFIND_PER_NEEDLE_BYTE: usize = 2; #[inline] -fn std_find_is_faster(haystack: usize, needle: usize) -> bool { - haystack < MEMMEM_FIND_MIN_HAYSTACK - && haystack >= STD_FIND_BASE.saturating_add(needle.saturating_mul(STD_FIND_PER_NEEDLE_BYTE)) +fn std_rfind_is_faster(haystack: usize, needle: usize) -> bool { + haystack >= STD_RFIND_BASE.saturating_add(needle.saturating_mul(STD_RFIND_PER_NEEDLE_BYTE)) +} + +/// Needles of 2 up to this many bytes are found by [`find_short`] and +/// [`rfind_short`] in short haystacks, and by `split_str` at any length. The +/// middle of a candidate is checked with `compare::bytes_eq`, which handles up +/// to 64 bytes without a `memcmp` call. +pub(crate) const SHORT_NEEDLE_MAX: usize = 32; + +/// Candidate positions screened together by [`find_short`]. +const SCREEN_BLOCK: usize = 16; + +/// `find`, `rfind`, and `contains` without std's SIMD fast path screen only +/// haystacks shorter than this. +const SCREENED_MAX_HAYSTACK: usize = 256; + +/// Positions that pass the screen but not the full comparison, tolerated in +/// one search before the caller hands the rest of the text to a Two-Way +/// searcher. Ordinary text rarely has any; text built to defeat the screen pays +/// for at most this many. +const SHORT_NEEDLE_FALSE_CANDIDATES: usize = 4; + +/// The outcome of [`find_short`]. +pub(crate) enum ShortSearch { + /// The first match starts here. + Found(usize), + /// The text holds no match. + Missing, + /// More than [`SHORT_NEEDLE_FALSE_CANDIDATES`] positions passed the + /// screen without matching, the last at this position; a Two-Way searcher + /// suits this text better. Nothing before the position matches, and the + /// position holds the needle's first byte, so it is a character boundary. + TooManyFalseCandidates(usize), } +/// Returns the first position of `needle`, of 2 to [`SHORT_NEEDLE_MAX`] +/// bytes, in `haystack`. +/// +/// Positions are screened [`SCREEN_BLOCK`] at a time on the needle's first and +/// last bytes, in a fixed-size loop the compiler turns into vector compares, +/// and only positions that pass compare the middle. Text that merely repeats +/// the separator's first byte, or its leading bytes, produces no candidates. #[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) 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]); + // The last position where a whole separator still fits. + 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; + // Every position of a block, plus `span`, stays inside the text while + // `at + SCREEN_BLOCK <= last + 1`. + while at + SCREEN_BLOCK <= last + 1 { + let heads: &[u8; SCREEN_BLOCK] = bytes[at..at + SCREEN_BLOCK] + .try_into() + .expect("a block of heads"); + let tails: &[u8; SCREEN_BLOCK] = bytes[at + span..at + 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_byte)) << i; + } + 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, + } +} +/// Returns the last position of `needle`, of 2 to [`SHORT_NEEDLE_MAX`] bytes, +/// in `haystack`: [`find_short`] scanning from the end. +/// +/// `TooManyFalseCandidates(position)` means no match starts at or after the +/// position, which holds the needle's first byte. +#[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; + + // Positions below `end` are still unscanned. + let mut end = last + 1; + while end >= SCREEN_BLOCK { + let start = end - SCREEN_BLOCK; + let heads: &[u8; SCREEN_BLOCK] = bytes[start..end].try_into().expect("a block of heads"); + let tails: &[u8; SCREEN_BLOCK] = bytes[start + span..end + span] + .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_byte)) << i; + } + 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, + } } /// Answers a search whose needle is at least as long as the haystack: only @@ -73,27 +193,27 @@ pub(crate) fn contains_str(haystack: &str, needle: &str) -> bool { 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 <= STD_CONTAINS_MAX_NEEDLE + && n <= SHORT_NEEDLE_MAX && haystack.len() >= STD_CONTAINS_BLOCK + n - 1 => { std_contains(haystack, needle) } - _ => memchr::memmem::find(haystack.as_bytes(), needle.as_bytes()).is_some(), + // Everything else is one call, so the arms above compile as they did + // before the screen: inlined into a caller's loop, a second + // out-of-line arm cost the std arm about 7 instructions per call. + _ => contains_without_std_simd(haystack, needle), } } -// The std paths stay out of line: inlined, their searcher state enlarged the -// stack frame of the short memchr/memmem paths by about 2 ns per call. +// The std paths and the screened searches stay out of line, each as one call +// that returns the final answer: inlined, or followed by more work in the +// caller, their state enlarged the stack frame of every other arm, by 2 to +// 6 ns per call. #[inline(never)] fn std_contains(haystack: &str, needle: &str) -> bool { haystack.contains(needle) } -#[inline(never)] -fn std_find(haystack: &str, needle: &str) -> Option { - haystack.find(needle) -} - #[inline(never)] fn std_rfind(haystack: &str, needle: &str) -> Option { haystack.rfind(needle) @@ -105,7 +225,9 @@ pub(crate) fn find_str(haystack: &str, needle: &str) -> Option { 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 std_find_is_faster(haystack.len(), n) => std_find(haystack, needle), + n if n <= SHORT_NEEDLE_MAX && haystack.len() < SCREENED_MAX_HAYSTACK => { + find_screened(haystack, needle) + } _ => memchr::memmem::find(haystack.as_bytes(), needle.as_bytes()), } } @@ -116,11 +238,67 @@ pub(crate) fn rfind_str(haystack: &str, needle: &str) -> Option { 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()), } } +// After too many false candidates the screened searches hand the text they +// have not ruled out to a Two-Way searcher. A false candidate holds the +// needle's first byte, which begins a character, so it is a character +// boundary. + +/// `contains` for the inputs std's SIMD fast path does not take: the screen +/// for short needles in short haystacks, `memmem` for the rest. +#[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, + // Through the std wrapper, so `str::contains` keeps one call site + // and stays inlined into it. + 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 { + 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 { + match rfind_short(haystack, needle) { + ShortSearch::Found(at) => Some(at), + ShortSearch::Missing => None, + ShortSearch::TooManyFalseCandidates(before) => { + // No match starts at or after `before`, so any match ends by + // `before + needle.len() - 1`. The text is cut at the first + // character boundary from there; the up to three extra bytes + // cannot hold a match start, as those positions were ruled out. + let mut end = before + needle.len() - 1; + while !haystack.is_char_boundary(end) { + end += 1; + } + std_rfind(&haystack[..end], needle) + } + } +} + /// Reusable substring finder for repeated searches with the same needle. pub struct CheetahFinder<'a> { needle: &'a str, diff --git a/tests/transform_search.rs b/tests/transform_search.rs index 42ec037..a54d28b 100644 --- a/tests/transform_search.rs +++ b/tests/transform_search.rs @@ -244,6 +244,97 @@ fn ordering_matches_str_across_storage_kinds() { assert_eq!(keys, unique); } +fn assert_search_matches_str(text: &str, needle: &str) { + let value = CheetahString::from(text); + assert_eq!( + value.find(needle), + text.find(needle), + "find {text:?} {needle:?}" + ); + assert_eq!( + value.rfind(needle), + text.rfind(needle), + "rfind {text:?} {needle:?}" + ); + assert_eq!( + value.contains(needle), + text.contains(needle), + "contains {text:?} {needle:?}" + ); +} + +#[test] +fn search_matches_str_at_every_offset() { + // Needles at every offset land on both sides of each 16-position block + // boundary of the forward and reverse screens, in their scalar tails, and + // on both sides of the 256-byte screening limit. + let lengths: Vec = (0..=70) + .chain([100, 127, 128, 129, 200, 255, 256, 257, 300]) + .collect(); + for needle in [ + "::", + "a_b", + "<-->", + "\u{e9}\u{e9}", + "exactly-thirty-two-bytes-long!!!", + ] { + for &len in &lengths { + let base: String = "xy".chars().cycle().take(len).collect(); + assert_search_matches_str(&base, needle); + for at in 0..=len.saturating_sub(needle.len()) { + if at + needle.len() > len { + continue; + } + let mut text = base.clone(); + text.replace_range(at..at + needle.len(), needle); + assert_search_matches_str(&text, needle); + assert_search_matches_str(&format!("{text}{needle}"), needle); + } + } + } +} + +#[test] +fn search_hand_off_matches_str() { + // More than four positions pass the first/last-byte screen without + // matching, so `find`, `rfind`, and `contains` hand the rest of the text + // to a Two-Way searcher; real matches sit before and after that region. + let cases = [ + ("aXb".repeat(30), "a_b"), + (format!("a_b{}", "aXb".repeat(30)), "a_b"), + (format!("{}a_b", "aXb".repeat(30)), "a_b"), + ( + format!("{}a_b{}", "aXb".repeat(10), "aXb".repeat(10)), + "a_b", + ), + // Multi-byte needles, whose first byte is a UTF-8 lead byte; the + // reverse hand-off cuts the text at a character boundary. + ("\u{e9}X\u{e9}".repeat(20), "\u{e9}_\u{e9}"), + ( + format!("\u{e9}_\u{e9}{}", "\u{e9}X\u{e9}".repeat(20)), + "\u{e9}_\u{e9}", + ), + ( + format!("{}\u{e9}_\u{e9}", "\u{e9}X\u{e9}".repeat(20)), + "\u{e9}_\u{e9}", + ), + ( + format!("\u{1f980}zy\u{1f980}{}", "\u{1f980}xy\u{1f980}".repeat(12)), + "\u{1f980}zy\u{1f980}", + ), + ( + format!("{}\u{1f980}zy\u{1f980}", "\u{1f980}xy\u{1f980}".repeat(12)), + "\u{1f980}zy\u{1f980}", + ), + // The last match ends exactly where the reverse hand-off cuts the + // text: "aab" at 20 overlaps the fifth false candidate, "abb" at 21. + (format!("{}aabb{}", "x".repeat(20), "aXb".repeat(4)), "aab"), + ]; + for (text, needle) in &cases { + assert_search_matches_str(text, needle); + } +} + #[test] fn split_str_hand_off_matches_str_split() { // Every piece is preceded by more than four positions that pass the