//! Substring search (`string.find`, `string.contains`): memchr's //! "generic SIMD" two-byte filter, with the algorithm instantiated per //! target — SSE2 vectors on x86-64 (in the baseline, so no runtime //! detection), SWAR over a `u64` elsewhere. No nightly features; both //! backends and every target share the one dispatch (the interpreter is //! the native backend's oracle). //! //! Dispatched by needle length (memchr's law: no single substring //! algorithm wins everywhere): //! //! | needle | search | //! |-----------|--------| //! | 0 bytes | `Some(0)` | //! | 1 byte | memchr | //! | 2–4 bytes | first/last-byte pair filter, one vector a step, survivors confirmed | //! | 5+ bytes | the same pair filter, two vectors a step | //! //! The pair filter compares a vector of candidate first bytes with a //! vector of last bytes `len - 1` ahead and ANDs them; survivors are rare //! and confirmed whole. /// The byte index of `needle`'s first occurrence in `haystack`, or /// `None`; the empty needle is found at 0. /// /// Both arguments are valid UTF-8, so a byte match of `needle` starts on /// a character boundary. pub fn find(haystack: &[u8], needle: &[u8]) -> Option { #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] { sse2::find(haystack, needle) } #[cfg(not(all(target_arch = "x86_64", target_feature = "sse2")))] { swar::find(haystack, needle) } } /// SWAR: a `u64` plays the part of an 8-byte vector (eight candidate /// positions a step, sixteen or thirty-two with unrolling). Portable, /// safe, and what the no-SSE2 targets (and the aarch64 type-check) build; /// compiled where it is used (the tests exercise it on x86-64 too). #[cfg(any(test, not(all(target_arch = "x86_64", target_feature = "sse2"))))] mod swar { /// The low and high bits of every byte lane. const LO: u64 = 0x0101_0101_0101_0101; const HI: u64 = 0x8080_8080_8080_8080; const WORD: usize = size_of::(); /// The high bit of each byte lane of `w` whose byte equals `b` /// (`haszero(w ^ broadcast(b))`, exact: no false lanes). fn eq_mask(w: u64, b: u8) -> u64 { let x = w ^ (LO * u64::from(b)); x.wrapping_sub(LO) & !x & HI } /// Eight bytes of `h` at `i` as a little-endian word, so byte `i + k` /// is lane `k` and a mask's lowest set bit is the first match, /// whatever the host's endianness. `i + WORD` must not exceed /// `h.len()`. fn word_at(h: &[u8], i: usize) -> u64 { u64::from_le_bytes(h[i..i + WORD].try_into().expect("louise: SWAR word")) } /// The lane index of a mask's lowest set bit. fn first_lane(mask: u64) -> usize { (mask.trailing_zeros() / 8) as usize } /// The first index of `b` in `h` (memchr): four words a step, then /// one, then a short scalar tail. fn find_byte(h: &[u8], b: u8) -> Option { let mut i = 0; while i + 4 * WORD <= h.len() { let masks = [ eq_mask(word_at(h, i), b), eq_mask(word_at(h, i + WORD), b), eq_mask(word_at(h, i + 2 * WORD), b), eq_mask(word_at(h, i + 3 * WORD), b), ]; if masks.iter().any(|&m| m != 0) { for (u, &m) in masks.iter().enumerate() { if m != 0 { return Some(i + u * WORD + first_lane(m)); } } unreachable!("louise: a mask was set"); } i += 4 * WORD; } while i + WORD <= h.len() { let m = eq_mask(word_at(h, i), b); if m != 0 { return Some(i + first_lane(m)); } i += WORD; } h[i..].iter().position(|&x| x == b).map(|k| i + k) } /// The first index of `needle` in `h`, filtered on its first and last /// byte: a word of candidate first bytes ANDed with a word of last /// bytes `len - 1` ahead leaves few survivors, each confirmed whole. /// `UNROLL` words a step; `h` is at least `needle`'s length, so a /// mask's lanes never pass `h.len() - len`. fn find_pair(h: &[u8], needle: &[u8]) -> Option { let len = needle.len(); let (first, last) = (needle[0], needle[len - 1]); let d = len - 1; let last_start = h.len() - len; let mut i = 0; while i + d + UNROLL * WORD <= h.len() { let mut any = 0; let mut masks = [0u64; UNROLL]; for (u, m) in masks.iter_mut().enumerate() { *m = eq_mask(word_at(h, i + u * WORD), first) & eq_mask(word_at(h, i + u * WORD + d), last); any |= *m; } if any != 0 { for (u, &m) in masks.iter().enumerate() { let mut m = m; while m != 0 { let at = i + u * WORD + first_lane(m); m &= m - 1; if h[at..at + len] == *needle { return Some(at); } } } } i += UNROLL * WORD; } // One word at a time until the tail is shorter than a word. while i + d + WORD <= h.len() { let mut m = eq_mask(word_at(h, i), first) & eq_mask(word_at(h, i + d), last); while m != 0 { let at = i + first_lane(m); m &= m - 1; if h[at..at + len] == *needle { return Some(at); } } i += WORD; } // The tail: under `WORD + d` candidates, checked scalar. let mut at = i; while at <= last_start { if h[at] == first && h[at + d] == last && h[at..at + len] == *needle { return Some(at); } at += 1; } None } pub fn find(haystack: &[u8], needle: &[u8]) -> Option { match needle.len() { 0 => Some(0), 1 => find_byte(haystack, needle[0]), 2..=4 if needle.len() <= haystack.len() => find_pair::<1>(haystack, needle), _ if needle.len() <= haystack.len() => find_pair::<2>(haystack, needle), _ => None, } } } /// SSE2 (in x86-64's baseline: no runtime detection): 16-byte vectors, /// sixteen candidate positions a step, thirty-two unrolled. The loads /// are unaligned; every one is in bounds by its loop's condition. #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] mod sse2 { use std::arch::x86_64::{ __m128i, _mm_and_si128, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8, _mm_set1_epi8, }; const VECTOR: usize = 16; /// Sixteen bytes of `h` at `i`. /// /// # Safety /// `i + VECTOR` must not exceed `h.len()`. #[target_feature(enable = "sse2")] unsafe fn vector_at(h: &[u8], i: usize) -> __m128i { // SAFETY: forwarded caller guarantee. unsafe { _mm_loadu_si128(h.as_ptr().add(i).cast()) } } /// The lanes of `v` equal to `b`, as a bitmask (bit `k` is lane `k`, /// so its lowest set bit is the first match). /// /// # Safety /// As `vector_at`'s. #[target_feature(enable = "sse2")] unsafe fn eq_mask(v: __m128i, b: __m128i) -> u32 { _mm_movemask_epi8(_mm_cmpeq_epi8(v, b)) as u32 } /// The first index of `b` in `h` (memchr): two vectors a step, then /// one, then a short scalar tail. #[target_feature(enable = "sse2")] fn find_byte(h: &[u8], b: u8) -> Option { let needle = _mm_set1_epi8(b as i8); let mut i = 0; while i + 2 * VECTOR <= h.len() { // SAFETY: the loop keeps both loads in bounds. let (m0, m1) = unsafe { ( eq_mask(vector_at(h, i), needle), eq_mask(vector_at(h, i + VECTOR), needle), ) }; if m0 | m1 != 0 { if m0 != 0 { return Some(i + m0.trailing_zeros() as usize); } return Some(i + VECTOR + m1.trailing_zeros() as usize); } i += 2 * VECTOR; } while i + VECTOR <= h.len() { // SAFETY: the loop keeps the load in bounds. let m = unsafe { eq_mask(vector_at(h, i), needle) }; if m != 0 { return Some(i + m.trailing_zeros() as usize); } i += VECTOR; } h[i..].iter().position(|&x| x == b).map(|k| i + k) } /// The first index of `needle` in `h`, filtered on its first and last /// byte: a vector of candidate first bytes ANDed with a vector of /// last bytes `len - 1` ahead leaves few survivors, each confirmed /// whole. `UNROLL` vectors a step; `h` is at least `needle`'s length, /// so a mask's bits never pass `h.len() - len`. #[target_feature(enable = "sse2")] fn find_pair(h: &[u8], needle: &[u8]) -> Option { let len = needle.len(); let (first, last) = ( _mm_set1_epi8(needle[0] as i8), _mm_set1_epi8(needle[len - 1] as i8), ); let d = len - 1; let last_start = h.len() - len; let mut i = 0; while i + d + UNROLL * VECTOR <= h.len() { let mut any = 0; let mut masks = [0u32; UNROLL]; // SAFETY: the loop keeps every load in bounds. unsafe { for (u, m) in masks.iter_mut().enumerate() { *m = _mm_movemask_epi8(_mm_and_si128( _mm_cmpeq_epi8(vector_at(h, i + u * VECTOR), first), _mm_cmpeq_epi8(vector_at(h, i + u * VECTOR + d), last), )) as u32; any |= *m; } } if any != 0 { for (u, &m) in masks.iter().enumerate() { let mut m = m; while m != 0 { let at = i + u * VECTOR + m.trailing_zeros() as usize; m &= m - 1; if h[at..at + len] == *needle { return Some(at); } } } } i += UNROLL * VECTOR; } // One vector at a time until the tail is shorter than a vector. while i + d + VECTOR <= h.len() { // SAFETY: the loop keeps both loads in bounds. let mut m = unsafe { _mm_movemask_epi8(_mm_and_si128( _mm_cmpeq_epi8(vector_at(h, i), first), _mm_cmpeq_epi8(vector_at(h, i + d), last), )) as u32 }; while m != 0 { let at = i + m.trailing_zeros() as usize; m &= m - 1; if h[at..at + len] == *needle { return Some(at); } } i += VECTOR; } // The tail: under `VECTOR + d` candidates, checked scalar. let mut at = i; while at <= last_start { if h[at] == needle[0] && h[at + d] == needle[len - 1] && h[at..at + len] == *needle { return Some(at); } at += 1; } None } pub fn find(haystack: &[u8], needle: &[u8]) -> Option { // SAFETY: this module is compiled only when sse2 is statically // enabled (x86-64's baseline), which is what the kernels require. unsafe { match needle.len() { 0 => Some(0), 1 => find_byte(haystack, needle[0]), 2..=4 if needle.len() <= haystack.len() => find_pair::<1>(haystack, needle), _ if needle.len() <= haystack.len() => find_pair::<2>(haystack, needle), _ => None, } } } } #[cfg(test)] mod tests { use super::{find, swar}; /// Every instantiation of the algorithm compiled for this target. fn finds(h: &[u8], n: &[u8]) -> Vec> { let mut all = vec![find(h, n), swar::find(h, n)]; #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] all.push(super::sse2::find(h, n)); all } /// The scan `find` must agree with. fn naive(h: &[u8], n: &[u8]) -> Option { if n.is_empty() { return Some(0); } (0..=h.len().checked_sub(n.len())?).find(|&i| h[i] == n[0] && &h[i..i + n.len()] == n) } /// Every instantiation agrees with the naive scan. #[track_caller] fn check(h: &[u8], n: &[u8], case: &str) { let want = naive(h, n); for got in finds(h, n) { assert_eq!(got, want, "{case}: needle {n:?}"); } } /// Directed cases: the dispatch boundaries (needle 0/1/2/4/5/16/64 /// bytes), matches at the edges, overlaps, and pair-filter false /// friends (first and last byte match, the middle does not). #[test] fn find_matches_a_naive_scan_on_directed_cases() { let long: Vec = (0..1000u32).map(|i| b"aab baca "[i as usize % 9]).collect(); let mut cases: Vec<(Vec, Vec)> = vec![ (b"".into(), b"".into()), (b"".into(), b"a".into()), (b"a".into(), b"a".into()), (b"a".into(), b"b".into()), (b"abc".into(), b"".into()), (b"abc".into(), b"c".into()), (b"abc".into(), b"d".into()), (b"aaaa".into(), b"aa".into()), // overlapping: the first wins (b"abaaa".into(), b"aaa".into()), // a false start at 1 (b"ab".into(), b"abc".into()), // longer than the haystack (b"hello world".into(), b"o w".into()), (b"hello world".into(), b"world!".into()), // Pair-filter false friends: `a...a` passes the filter, the // middle differs. (b"axxb ayyc azzc".into(), b"abbc".into()), (b"a___b a___c a___d".into(), b"a___e".into()), (b"needle at the very end: mark".into(), b"mark".into()), // Multibyte UTF-8: matches stay on character boundaries. ("héllo, wörld".as_bytes().into(), "wörld".as_bytes().into()), ("é🦀é🦀é".as_bytes().into(), "🦀é".as_bytes().into()), ]; // The dispatch boundaries, each found, missed and at the end. for n in [1usize, 2, 3, 4, 5, 15, 16, 17, 63, 64, 65] { let needle = vec![b'q'; n]; // 'q' never occurs in `long` cases.push((long.clone(), needle.clone())); let mut hit = long.clone(); let at = hit.len() - n - 3; // near the end, past the tail start hit[at..at + n].copy_from_slice(&needle); cases.push((hit, needle.clone())); let mut head = long.clone(); head[..n].copy_from_slice(&needle); // at 0 cases.push((head, needle)); } for (h, n) in &cases { check(h, n, "directed"); } } /// Pseudo-random inputs (a SplitMix64, no dependencies): small /// alphabets so matches are dense, haystacks and needles across the /// dispatch boundaries. #[test] fn find_matches_a_naive_scan_on_random_inputs() { let mut state = 0x9E37_79B9_7F4A_7C15u64; let mut next = move || { state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); let mut z = state; z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); z ^ (z >> 31) }; for case in 0..2000 { let alphabet: &[u8] = match case % 4 { 0 => b"a", 1 => b"ab", 2 => b"aab b", _ => "aab bcé🦀".as_bytes(), // multibyte bytes, searched raw }; let draw = |next: &mut dyn FnMut() -> u64, max: usize| -> Vec { let len = (next() as usize) % (max + 1); (0..len) .map(|_| alphabet[(next() as usize) % alphabet.len()]) .collect() }; let h = draw(&mut next, 300); // Half the needles are cut from the haystack (a sure hit, // raw bytes: possibly mid-character, which both searches see // alike), half are drawn fresh. let n = if case % 2 == 0 && !h.is_empty() { let at = (next() as usize) % h.len(); let len = ((next() as usize) % 70).min(h.len() - at); h[at..at + len].to_vec() } else { draw(&mut next, 70) }; check(&h, &n, &format!("case {case}")); } } }