Skip to main content

cheetah_string/
search.rs

1// Thresholds measured with `benches/search_thresholds.rs` on x86_64 (an
2// i7-11700K and the `ubuntu-latest` runner) and aarch64 (the
3// `ubuntu-24.04-arm` runner): needles of 2 to 32 bytes made of common or rare
4// haystack bytes, haystacks of 8 B to 4 KiB, hits and misses. The
5// `Search thresholds` workflow reruns it on both targets when this file
6// changes.
7//
8// A needle at least as long as the haystack can only match the whole
9// haystack, so one comparison answers it. std does the same for `contains`,
10// while `memmem` would still hash the single candidate position.
11//
12// Needles of 2 to 32 bytes on haystacks shorter than 256 bytes use the
13// screened search below, which needs no setup: it beat one-shot `memmem`
14// (Rabin-Karp below 64 bytes) and std's Two-Way searchers there. From 256
15// bytes the SIMD scans of `memmem` and std win.
16//
17// `str::contains` has a SIMD fast path for needles of 2..=32 bytes once the
18// haystack holds one 16-byte block plus the needle, and it beat the screen
19// there, so `contains` keeps it and screens only shorter haystacks. Above
20// 32-byte needles std builds a Two-Way searcher, so memmem stays the better
21// choice there.
22//
23// std only has that fast path on these targets; elsewhere it always builds a
24// Two-Way searcher, so `contains` screens up to 256 bytes like `find`.
25const 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
32// `memmem::rfind` has no prefilter, so outside the screen `rfind` uses
33// `str::rfind` once `haystack >= 24 + 2 * needle`: a one-shot `memmem::rfind`
34// uses Rabin-Karp below 64 bytes, whose cost grows with the candidate
35// positions, while std's setup grows with the needle.
36const 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
44/// Needles of 2 up to this many bytes are found by [`find_short`] and
45/// [`rfind_short`] in short haystacks, and by `split_str` at any length. The
46/// middle of a candidate is checked with `compare::bytes_eq`, which handles up
47/// to 64 bytes without a `memcmp` call.
48pub(crate) const SHORT_NEEDLE_MAX: usize = 32;
49
50/// Candidate positions screened together by [`find_short`].
51const SCREEN_BLOCK: usize = 16;
52
53/// `find`, `rfind`, and `contains` without std's SIMD fast path screen only
54/// haystacks shorter than this.
55const SCREENED_MAX_HAYSTACK: usize = 256;
56
57/// `find` screens haystacks shorter than this for a needle of `needle` bytes.
58///
59/// On aarch64 a one-shot `memmem::find` uses NEON from 64 bytes and overtook
60/// the screen sooner for short needles on the `ubuntu-24.04-arm` runner: from
61/// 64 bytes for 2- and 3-byte needles and from 160 bytes for 4- to 15-byte
62/// needles. Longer needles, and every needle on x86_64, gained up to the
63/// 256-byte limit.
64#[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
77/// Positions that pass the screen but not the full comparison, tolerated in
78/// one search before the caller hands the rest of the text to a Two-Way
79/// searcher. Ordinary text rarely has any; text built to defeat the screen pays
80/// for at most this many.
81const SHORT_NEEDLE_FALSE_CANDIDATES: usize = 4;
82
83/// The outcome of [`find_short`] and [`rfind_short`].
84pub(crate) enum ShortSearch {
85    /// The match nearest the scan's start begins here: the first match for
86    /// [`find_short`], the last for [`rfind_short`].
87    Found(usize),
88    /// The text holds no match.
89    Missing,
90    /// More than [`SHORT_NEEDLE_FALSE_CANDIDATES`] positions passed the
91    /// screen without matching, the last at this position; a Two-Way searcher
92    /// suits this text better. Every position the scan has passed is ruled
93    /// out, including this one: those before it for [`find_short`], those
94    /// after it for [`rfind_short`]. The position holds the needle's first
95    /// byte, so it is a character boundary.
96    TooManyFalseCandidates(usize),
97}
98
99/// Returns a bit for each of the [`SCREEN_BLOCK`] positions from `start`
100/// whose byte is `first` and whose byte `span` later is `last`. The fixed-size
101/// loop has no branch on the data, so the compiler turns it into vector
102/// compares. The caller keeps `start + span + SCREEN_BLOCK` within `bytes`.
103#[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/// Returns the first position of `needle`, of 2 to [`SHORT_NEEDLE_MAX`]
119/// bytes, in `haystack`.
120///
121/// Positions are screened [`SCREEN_BLOCK`] at a time on the needle's first and
122/// last bytes, in a fixed-size loop the compiler turns into vector compares,
123/// and only positions that pass compare the middle. Text that merely repeats
124/// the separator's first byte, or its leading bytes, produces no candidates.
125#[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    // The last position where a whole separator still fits.
132    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    // Every position of a block, plus `span`, stays inside the text while
140    // `at + SCREEN_BLOCK <= last + 1`.
141    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/// Returns the last position of `needle`, of 2 to [`SHORT_NEEDLE_MAX`] bytes,
164/// in `haystack`: [`find_short`] scanning from the end.
165///
166/// `TooManyFalseCandidates(position)` means no match starts at or after the
167/// position, which holds the needle's first byte.
168#[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    // Positions below `end` are still unscanned.
181    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/// Answers a search whose needle is at least as long as the haystack: only
209/// an identical haystack contains it, at offset 0.
210#[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        // Everything else, the screen or `memmem`, is one out-of-line call,
228        // which keeps this inlined body about as small as before the screen.
229        _ => contains_without_std_simd(haystack, needle),
230    }
231}
232
233// `str::contains` and `str::rfind` with a `&str` pattern are called only
234// through these wrappers, and each wrapper is the only call site of its search
235// in the crate. Keep it that way. With one call site, LLVM inlines the whole
236// std search into the wrapper. A second call site anywhere in the crate makes
237// it keep the search as a shared function instead, and the wrapper becomes a
238// jump to it: the instruction-count gate measured 7 more instructions on every
239// short `contains` when the screened hand-off called `str::contains` directly.
240//
241// `str::find` is called directly, only from the cold hand-offs of
242// `find_screened` and `split_str`. A third wrapper for it moved core's shared
243// Two-Way code to another codegen unit in default builds, which made
244// `std_rfind` on long haystacks 9 to 21% slower.
245//
246// The wrappers and the screened searches also stay out of line, each as one
247// call that returns the final answer: inlined into the dispatch, or followed
248// by more work in it, their state enlarged the stack frame of every other arm
249// by 2 to 6 ns per call.
250#[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// After too many false candidates the screened searches hand the text they
288// have not ruled out to a Two-Way searcher. A false candidate holds the
289// needle's first byte, which begins a character, so it is a character
290// boundary.
291
292/// `contains` for the inputs std's SIMD fast path does not take: the screen
293/// for short needles in short haystacks, `memmem` for the rest.
294#[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            // No match starts at or after `before`, so any match ends by
326            // `before + needle.len() - 1`. The text is cut at the first
327            // character boundary from there; the up to three extra bytes
328            // cannot hold a match start, as those positions were ruled out.
329            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
338/// Reusable substring finder for repeated searches with the same needle.
339pub struct CheetahFinder<'a> {
340    needle: &'a str,
341    finder: Option<memchr::memmem::Finder<'a>>,
342}
343
344impl<'a> CheetahFinder<'a> {
345    /// Creates a reusable finder for `needle`.
346    #[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    /// Returns the needle used by this finder.
353    #[inline]
354    pub fn needle(&self) -> &'a str {
355        self.needle
356    }
357
358    /// Finds the first occurrence of the needle in `haystack`.
359    #[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    /// Returns whether the needle occurs in `haystack`.
380    #[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    /// On targets with std's SIMD `contains`, `contains_str` only screens
396    /// haystacks too short to fill a screening block. Calling the screened
397    /// path directly runs the blocks and the hand-off on every target, as
398    /// targets without that search do through `contains_str`.
399    #[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                // A match placed at every block boundary and in the tail.
427                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}