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
25 changes: 13 additions & 12 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
88 changes: 3 additions & 85 deletions src/cheetah_string/pattern.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::search::{find_short, ShortSearch, SHORT_NEEDLE_MAX};
use alloc::string::String;
use core::str;

Expand Down Expand Up @@ -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,
Expand All @@ -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.
Expand All @@ -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<char> {
let mut chars = pattern.chars();
Expand Down
20 changes: 11 additions & 9 deletions src/cheetah_string/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
///
Expand Down Expand Up @@ -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.
///
Expand All @@ -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
///
Expand Down
13 changes: 7 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading