Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,11 @@ jobs:
- name: Verify 32-bit compact layout
run: cargo test --target i686-pc-windows-msvc --test layout_snapshot --all-features -- --nocapture

# std has no SIMD `contains` on 32-bit x86, so `contains` takes the
# screened search up to 256 bytes here, a path the 64-bit jobs never run.
- name: Test search without std's SIMD contains
run: cargo test --target i686-pc-windows-msvc --test transform_search --test search --all-features

dependency-audit:
runs-on: ubuntu-latest
steps:
Expand Down
6 changes: 4 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,10 @@
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
`find` and `str::rfind` for `rfind` (from `24 + 2 * needle` bytes). On
aarch64, `find` screens only up to 64 bytes for 2- and 3-byte needles and
up to 160 bytes for 4- to 15-byte needles, where NEON `memmem` was faster.
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.
Expand Down
20 changes: 12 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,14 +128,18 @@ 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. 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.
thresholds measured on x86_64 and aarch64. Needles of 2 to 32 bytes in short
text 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. `find` and `rfind` screen text under 256 bytes; on
aarch64 `find` stops sooner for needles under 16 bytes. `contains` keeps the
standard library's SIMD search once the text spans a 16-byte block plus the
needle and screens only shorter text, or text under 256 bytes on targets
without that search. Every other search uses `memchr::memmem`, except that
`rfind` uses `str::rfind` once the text is at least `24 + 2 * needle` bytes
long. 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:

Expand Down
10 changes: 6 additions & 4 deletions src/cheetah_string/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,9 @@ impl CheetahString {
///
/// 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 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`.
/// screened search with no setup. Targets without that SIMD search screen
/// text under 256 bytes. A needle at least as long as the text is answered
/// by one comparison; other cases use `memchr`/`memmem`.
///
/// # Examples
///
Expand Down Expand Up @@ -137,8 +138,9 @@ impl CheetahString {
/// Returns the byte index of the first occurrence of the pattern, or `None` if not found.
///
/// 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
/// with no setup; on aarch64 the limit is lower for needles under 16 bytes.
/// 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.
///
Expand Down
18 changes: 11 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,17 @@
//!
//! Substring search picks its backend by haystack and needle length, with
//! 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.
//! short text 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. `find()` and `rfind()` screen text under
//! 256 bytes; on aarch64 `find()` stops sooner for needles under 16 bytes.
//! `contains()` keeps the standard library's SIMD search once the text spans
//! a 16-byte block plus the needle and screens only shorter text, or text
//! under 256 bytes on targets without that search. Every other search uses
//! `memchr::memmem`, except that `rfind()` uses `str::rfind` once the text is
//! at least `24 + 2 * needle` bytes long. 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
//!
Expand Down
178 changes: 146 additions & 32 deletions src/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,25 +54,67 @@ const SCREEN_BLOCK: usize = 16;
/// haystacks shorter than this.
const SCREENED_MAX_HAYSTACK: usize = 256;

/// `find` screens haystacks shorter than this for a needle of `needle` bytes.
///
/// On aarch64 a one-shot `memmem::find` uses NEON from 64 bytes and overtook
/// the screen sooner for short needles on the `ubuntu-24.04-arm` runner: from
/// 64 bytes for 2- and 3-byte needles and from 160 bytes for 4- to 15-byte
/// needles. Longer needles, and every needle on x86_64, gained up to the
/// 256-byte limit.
#[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
}
}

/// 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`].
/// The outcome of [`find_short`] and [`rfind_short`].
pub(crate) enum ShortSearch {
/// The first match starts here.
/// The match nearest the scan's start begins here: the first match for
/// [`find_short`], the last for [`rfind_short`].
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.
/// suits this text better. Every position the scan has passed is ruled
/// out, including this one: those before it for [`find_short`], those
/// after it for [`rfind_short`]. The position holds the needle's first
/// byte, so it is a character boundary.
TooManyFalseCandidates(usize),
}

/// Returns a bit for each of the [`SCREEN_BLOCK`] positions from `start`
/// whose byte is `first` and whose byte `span` later is `last`. The fixed-size
/// loop has no branch on the data, so the compiler turns it into vector
/// compares. The caller keeps `start + span + SCREEN_BLOCK` within `bytes`.
#[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
}

/// Returns the first position of `needle`, of 2 to [`SHORT_NEEDLE_MAX`]
/// bytes, in `haystack`.
///
Expand All @@ -97,16 +139,7 @@ pub(crate) fn find_short(haystack: &str, needle: &str) -> ShortSearch {
// 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;
}
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) {
Expand Down Expand Up @@ -148,14 +181,7 @@ fn rfind_short(haystack: &str, needle: &str) -> ShortSearch {
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;
}
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;
Expand Down Expand Up @@ -198,17 +224,29 @@ pub(crate) fn contains_str(haystack: &str, needle: &str) -> bool {
{
std_contains(haystack, needle)
}
// 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.
// Everything else, the screen or `memmem`, is one out-of-line call,
// which keeps this inlined body about as small as before the screen.
_ => contains_without_std_simd(haystack, needle),
}
}

// 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.
// `str::contains` and `str::rfind` with a `&str` pattern are called only
// through these wrappers, and each wrapper is the only call site of its search
// in the crate. Keep it that way. With one call site, LLVM inlines the whole
// std search into the wrapper. A second call site anywhere in the crate makes
// it keep the search as a shared function instead, and the wrapper becomes a
// jump to it: the instruction-count gate measured 7 more instructions on every
// short `contains` when the screened hand-off called `str::contains` directly.
//
// `str::find` is called directly, only from the cold hand-offs of
// `find_screened` and `split_str`. A third wrapper for it moved core's shared
// Two-Way code to another codegen unit in default builds, which made
// `std_rfind` on long haystacks 9 to 21% slower.
//
// The wrappers and the screened searches also stay out of line, each as one
// call that returns the final answer: inlined into the dispatch, or followed
// by more work in it, 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)
Expand All @@ -225,7 +263,7 @@ pub(crate) fn find_str(haystack: &str, needle: &str) -> Option<usize> {
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() < SCREENED_MAX_HAYSTACK => {
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()),
Expand Down Expand Up @@ -261,8 +299,6 @@ fn contains_without_std_simd(haystack: &str, needle: &str) -> bool {
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),
};
}
Expand Down Expand Up @@ -349,3 +385,81 @@ impl<'a> CheetahFinder<'a> {
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;

/// On targets with std's SIMD `contains`, `contains_str` only screens
/// haystacks too short to fill a screening block. Calling the screened
/// path directly runs the blocks and the hand-off on every target, as
/// targets without that search do through `contains_str`.
#[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:?}"
);
// A match placed at every block boundary and in the tail.
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);
}
}
}
Loading