louise
The Louise language: compiler, runtime, std, tooling
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runÉchoué#94 · main · 15 min 28 s
0Étoiles
0Forks
40Issues
| 1 | //! Substring search (`string.find`, `string.contains`): memchr's |
| 2 | //! "generic SIMD" two-byte filter, with the algorithm instantiated per |
| 3 | //! target — SSE2 vectors on x86-64 (in the baseline, so no runtime |
| 4 | //! detection), SWAR over a `u64` elsewhere. No nightly features; both |
| 5 | //! backends and every target share the one dispatch (the interpreter is |
| 6 | //! the native backend's oracle). |
| 7 | //! |
| 8 | //! Dispatched by needle length (memchr's law: no single substring |
| 9 | //! algorithm wins everywhere): |
| 10 | //! |
| 11 | //! | needle | search | |
| 12 | //! |-----------|--------| |
| 13 | //! | 0 bytes | `Some(0)` | |
| 14 | //! | 1 byte | memchr | |
| 15 | //! | 2–4 bytes | first/last-byte pair filter, one vector a step, survivors confirmed | |
| 16 | //! | 5+ bytes | the same pair filter, two vectors a step | |
| 17 | //! |
| 18 | //! The pair filter compares a vector of candidate first bytes with a |
| 19 | //! vector of last bytes `len - 1` ahead and ANDs them; survivors are rare |
| 20 | //! and confirmed whole. |
| 21 | |
| 22 | /// The byte index of `needle`'s first occurrence in `haystack`, or |
| 23 | /// `None`; the empty needle is found at 0. |
| 24 | /// |
| 25 | /// Both arguments are valid UTF-8, so a byte match of `needle` starts on |
| 26 | /// a character boundary. |
| 27 | pub fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> { |
| 28 | #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] |
| 29 | { |
| 30 | sse2::find(haystack, needle) |
| 31 | } |
| 32 | #[cfg(not(all(target_arch = "x86_64", target_feature = "sse2")))] |
| 33 | { |
| 34 | swar::find(haystack, needle) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | /// SWAR: a `u64` plays the part of an 8-byte vector (eight candidate |
| 39 | /// positions a step, sixteen or thirty-two with unrolling). Portable, |
| 40 | /// safe, and what the no-SSE2 targets (and the aarch64 type-check) build; |
| 41 | /// compiled where it is used (the tests exercise it on x86-64 too). |
| 42 | #[cfg(any(test, not(all(target_arch = "x86_64", target_feature = "sse2"))))] |
| 43 | mod swar { |
| 44 | /// The low and high bits of every byte lane. |
| 45 | const LO: u64 = 0x0101_0101_0101_0101; |
| 46 | const HI: u64 = 0x8080_8080_8080_8080; |
| 47 | const WORD: usize = size_of::<u64>(); |
| 48 | |
| 49 | /// The high bit of each byte lane of `w` whose byte equals `b` |
| 50 | /// (`haszero(w ^ broadcast(b))`, exact: no false lanes). |
| 51 | fn eq_mask(w: u64, b: u8) -> u64 { |
| 52 | let x = w ^ (LO * u64::from(b)); |
| 53 | x.wrapping_sub(LO) & !x & HI |
| 54 | } |
| 55 | |
| 56 | /// Eight bytes of `h` at `i` as a little-endian word, so byte `i + k` |
| 57 | /// is lane `k` and a mask's lowest set bit is the first match, |
| 58 | /// whatever the host's endianness. `i + WORD` must not exceed |
| 59 | /// `h.len()`. |
| 60 | fn word_at(h: &[u8], i: usize) -> u64 { |
| 61 | u64::from_le_bytes(h[i..i + WORD].try_into().expect("louise: SWAR word")) |
| 62 | } |
| 63 | |
| 64 | /// The lane index of a mask's lowest set bit. |
| 65 | fn first_lane(mask: u64) -> usize { |
| 66 | (mask.trailing_zeros() / 8) as usize |
| 67 | } |
| 68 | |
| 69 | /// The first index of `b` in `h` (memchr): four words a step, then |
| 70 | /// one, then a short scalar tail. |
| 71 | fn find_byte(h: &[u8], b: u8) -> Option<usize> { |
| 72 | let mut i = 0; |
| 73 | while i + 4 * WORD <= h.len() { |
| 74 | let masks = [ |
| 75 | eq_mask(word_at(h, i), b), |
| 76 | eq_mask(word_at(h, i + WORD), b), |
| 77 | eq_mask(word_at(h, i + 2 * WORD), b), |
| 78 | eq_mask(word_at(h, i + 3 * WORD), b), |
| 79 | ]; |
| 80 | if masks.iter().any(|&m| m != 0) { |
| 81 | for (u, &m) in masks.iter().enumerate() { |
| 82 | if m != 0 { |
| 83 | return Some(i + u * WORD + first_lane(m)); |
| 84 | } |
| 85 | } |
| 86 | unreachable!("louise: a mask was set"); |
| 87 | } |
| 88 | i += 4 * WORD; |
| 89 | } |
| 90 | while i + WORD <= h.len() { |
| 91 | let m = eq_mask(word_at(h, i), b); |
| 92 | if m != 0 { |
| 93 | return Some(i + first_lane(m)); |
| 94 | } |
| 95 | i += WORD; |
| 96 | } |
| 97 | h[i..].iter().position(|&x| x == b).map(|k| i + k) |
| 98 | } |
| 99 | |
| 100 | /// The first index of `needle` in `h`, filtered on its first and last |
| 101 | /// byte: a word of candidate first bytes ANDed with a word of last |
| 102 | /// bytes `len - 1` ahead leaves few survivors, each confirmed whole. |
| 103 | /// `UNROLL` words a step; `h` is at least `needle`'s length, so a |
| 104 | /// mask's lanes never pass `h.len() - len`. |
| 105 | fn find_pair<const UNROLL: usize>(h: &[u8], needle: &[u8]) -> Option<usize> { |
| 106 | let len = needle.len(); |
| 107 | let (first, last) = (needle[0], needle[len - 1]); |
| 108 | let d = len - 1; |
| 109 | let last_start = h.len() - len; |
| 110 | let mut i = 0; |
| 111 | while i + d + UNROLL * WORD <= h.len() { |
| 112 | let mut any = 0; |
| 113 | let mut masks = [0u64; UNROLL]; |
| 114 | for (u, m) in masks.iter_mut().enumerate() { |
| 115 | *m = eq_mask(word_at(h, i + u * WORD), first) |
| 116 | & eq_mask(word_at(h, i + u * WORD + d), last); |
| 117 | any |= *m; |
| 118 | } |
| 119 | if any != 0 { |
| 120 | for (u, &m) in masks.iter().enumerate() { |
| 121 | let mut m = m; |
| 122 | while m != 0 { |
| 123 | let at = i + u * WORD + first_lane(m); |
| 124 | m &= m - 1; |
| 125 | if h[at..at + len] == *needle { |
| 126 | return Some(at); |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | i += UNROLL * WORD; |
| 132 | } |
| 133 | // One word at a time until the tail is shorter than a word. |
| 134 | while i + d + WORD <= h.len() { |
| 135 | let mut m = eq_mask(word_at(h, i), first) & eq_mask(word_at(h, i + d), last); |
| 136 | while m != 0 { |
| 137 | let at = i + first_lane(m); |
| 138 | m &= m - 1; |
| 139 | if h[at..at + len] == *needle { |
| 140 | return Some(at); |
| 141 | } |
| 142 | } |
| 143 | i += WORD; |
| 144 | } |
| 145 | // The tail: under `WORD + d` candidates, checked scalar. |
| 146 | let mut at = i; |
| 147 | while at <= last_start { |
| 148 | if h[at] == first && h[at + d] == last && h[at..at + len] == *needle { |
| 149 | return Some(at); |
| 150 | } |
| 151 | at += 1; |
| 152 | } |
| 153 | None |
| 154 | } |
| 155 | |
| 156 | pub fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> { |
| 157 | match needle.len() { |
| 158 | 0 => Some(0), |
| 159 | 1 => find_byte(haystack, needle[0]), |
| 160 | 2..=4 if needle.len() <= haystack.len() => find_pair::<1>(haystack, needle), |
| 161 | _ if needle.len() <= haystack.len() => find_pair::<2>(haystack, needle), |
| 162 | _ => None, |
| 163 | } |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | /// SSE2 (in x86-64's baseline: no runtime detection): 16-byte vectors, |
| 168 | /// sixteen candidate positions a step, thirty-two unrolled. The loads |
| 169 | /// are unaligned; every one is in bounds by its loop's condition. |
| 170 | #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] |
| 171 | mod sse2 { |
| 172 | use std::arch::x86_64::{ |
| 173 | __m128i, _mm_and_si128, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8, _mm_set1_epi8, |
| 174 | }; |
| 175 | |
| 176 | const VECTOR: usize = 16; |
| 177 | |
| 178 | /// Sixteen bytes of `h` at `i`. |
| 179 | /// |
| 180 | /// # Safety |
| 181 | /// `i + VECTOR` must not exceed `h.len()`. |
| 182 | #[target_feature(enable = "sse2")] |
| 183 | unsafe fn vector_at(h: &[u8], i: usize) -> __m128i { |
| 184 | // SAFETY: forwarded caller guarantee. |
| 185 | unsafe { _mm_loadu_si128(h.as_ptr().add(i).cast()) } |
| 186 | } |
| 187 | |
| 188 | /// The lanes of `v` equal to `b`, as a bitmask (bit `k` is lane `k`, |
| 189 | /// so its lowest set bit is the first match). |
| 190 | /// |
| 191 | /// # Safety |
| 192 | /// As `vector_at`'s. |
| 193 | #[target_feature(enable = "sse2")] |
| 194 | unsafe fn eq_mask(v: __m128i, b: __m128i) -> u32 { |
| 195 | _mm_movemask_epi8(_mm_cmpeq_epi8(v, b)) as u32 |
| 196 | } |
| 197 | |
| 198 | /// The first index of `b` in `h` (memchr): two vectors a step, then |
| 199 | /// one, then a short scalar tail. |
| 200 | #[target_feature(enable = "sse2")] |
| 201 | fn find_byte(h: &[u8], b: u8) -> Option<usize> { |
| 202 | let needle = _mm_set1_epi8(b as i8); |
| 203 | let mut i = 0; |
| 204 | while i + 2 * VECTOR <= h.len() { |
| 205 | // SAFETY: the loop keeps both loads in bounds. |
| 206 | let (m0, m1) = unsafe { |
| 207 | ( |
| 208 | eq_mask(vector_at(h, i), needle), |
| 209 | eq_mask(vector_at(h, i + VECTOR), needle), |
| 210 | ) |
| 211 | }; |
| 212 | if m0 | m1 != 0 { |
| 213 | if m0 != 0 { |
| 214 | return Some(i + m0.trailing_zeros() as usize); |
| 215 | } |
| 216 | return Some(i + VECTOR + m1.trailing_zeros() as usize); |
| 217 | } |
| 218 | i += 2 * VECTOR; |
| 219 | } |
| 220 | while i + VECTOR <= h.len() { |
| 221 | // SAFETY: the loop keeps the load in bounds. |
| 222 | let m = unsafe { eq_mask(vector_at(h, i), needle) }; |
| 223 | if m != 0 { |
| 224 | return Some(i + m.trailing_zeros() as usize); |
| 225 | } |
| 226 | i += VECTOR; |
| 227 | } |
| 228 | h[i..].iter().position(|&x| x == b).map(|k| i + k) |
| 229 | } |
| 230 | |
| 231 | /// The first index of `needle` in `h`, filtered on its first and last |
| 232 | /// byte: a vector of candidate first bytes ANDed with a vector of |
| 233 | /// last bytes `len - 1` ahead leaves few survivors, each confirmed |
| 234 | /// whole. `UNROLL` vectors a step; `h` is at least `needle`'s length, |
| 235 | /// so a mask's bits never pass `h.len() - len`. |
| 236 | #[target_feature(enable = "sse2")] |
| 237 | fn find_pair<const UNROLL: usize>(h: &[u8], needle: &[u8]) -> Option<usize> { |
| 238 | let len = needle.len(); |
| 239 | let (first, last) = ( |
| 240 | _mm_set1_epi8(needle[0] as i8), |
| 241 | _mm_set1_epi8(needle[len - 1] as i8), |
| 242 | ); |
| 243 | let d = len - 1; |
| 244 | let last_start = h.len() - len; |
| 245 | let mut i = 0; |
| 246 | while i + d + UNROLL * VECTOR <= h.len() { |
| 247 | let mut any = 0; |
| 248 | let mut masks = [0u32; UNROLL]; |
| 249 | // SAFETY: the loop keeps every load in bounds. |
| 250 | unsafe { |
| 251 | for (u, m) in masks.iter_mut().enumerate() { |
| 252 | *m = _mm_movemask_epi8(_mm_and_si128( |
| 253 | _mm_cmpeq_epi8(vector_at(h, i + u * VECTOR), first), |
| 254 | _mm_cmpeq_epi8(vector_at(h, i + u * VECTOR + d), last), |
| 255 | )) as u32; |
| 256 | any |= *m; |
| 257 | } |
| 258 | } |
| 259 | if any != 0 { |
| 260 | for (u, &m) in masks.iter().enumerate() { |
| 261 | let mut m = m; |
| 262 | while m != 0 { |
| 263 | let at = i + u * VECTOR + m.trailing_zeros() as usize; |
| 264 | m &= m - 1; |
| 265 | if h[at..at + len] == *needle { |
| 266 | return Some(at); |
| 267 | } |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | i += UNROLL * VECTOR; |
| 272 | } |
| 273 | // One vector at a time until the tail is shorter than a vector. |
| 274 | while i + d + VECTOR <= h.len() { |
| 275 | // SAFETY: the loop keeps both loads in bounds. |
| 276 | let mut m = unsafe { |
| 277 | _mm_movemask_epi8(_mm_and_si128( |
| 278 | _mm_cmpeq_epi8(vector_at(h, i), first), |
| 279 | _mm_cmpeq_epi8(vector_at(h, i + d), last), |
| 280 | )) as u32 |
| 281 | }; |
| 282 | while m != 0 { |
| 283 | let at = i + m.trailing_zeros() as usize; |
| 284 | m &= m - 1; |
| 285 | if h[at..at + len] == *needle { |
| 286 | return Some(at); |
| 287 | } |
| 288 | } |
| 289 | i += VECTOR; |
| 290 | } |
| 291 | // The tail: under `VECTOR + d` candidates, checked scalar. |
| 292 | let mut at = i; |
| 293 | while at <= last_start { |
| 294 | if h[at] == needle[0] && h[at + d] == needle[len - 1] && h[at..at + len] == *needle { |
| 295 | return Some(at); |
| 296 | } |
| 297 | at += 1; |
| 298 | } |
| 299 | None |
| 300 | } |
| 301 | |
| 302 | pub fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> { |
| 303 | // SAFETY: this module is compiled only when sse2 is statically |
| 304 | // enabled (x86-64's baseline), which is what the kernels require. |
| 305 | unsafe { |
| 306 | match needle.len() { |
| 307 | 0 => Some(0), |
| 308 | 1 => find_byte(haystack, needle[0]), |
| 309 | 2..=4 if needle.len() <= haystack.len() => find_pair::<1>(haystack, needle), |
| 310 | _ if needle.len() <= haystack.len() => find_pair::<2>(haystack, needle), |
| 311 | _ => None, |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | #[cfg(test)] |
| 318 | mod tests { |
| 319 | use super::{find, swar}; |
| 320 | |
| 321 | /// Every instantiation of the algorithm compiled for this target. |
| 322 | fn finds(h: &[u8], n: &[u8]) -> Vec<Option<usize>> { |
| 323 | let mut all = vec![find(h, n), swar::find(h, n)]; |
| 324 | #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] |
| 325 | all.push(super::sse2::find(h, n)); |
| 326 | all |
| 327 | } |
| 328 | |
| 329 | /// The scan `find` must agree with. |
| 330 | fn naive(h: &[u8], n: &[u8]) -> Option<usize> { |
| 331 | if n.is_empty() { |
| 332 | return Some(0); |
| 333 | } |
| 334 | (0..=h.len().checked_sub(n.len())?).find(|&i| h[i] == n[0] && &h[i..i + n.len()] == n) |
| 335 | } |
| 336 | |
| 337 | /// Every instantiation agrees with the naive scan. |
| 338 | #[track_caller] |
| 339 | fn check(h: &[u8], n: &[u8], case: &str) { |
| 340 | let want = naive(h, n); |
| 341 | for got in finds(h, n) { |
| 342 | assert_eq!(got, want, "{case}: needle {n:?}"); |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | /// Directed cases: the dispatch boundaries (needle 0/1/2/4/5/16/64 |
| 347 | /// bytes), matches at the edges, overlaps, and pair-filter false |
| 348 | /// friends (first and last byte match, the middle does not). |
| 349 | #[test] |
| 350 | fn find_matches_a_naive_scan_on_directed_cases() { |
| 351 | let long: Vec<u8> = (0..1000u32).map(|i| b"aab baca "[i as usize % 9]).collect(); |
| 352 | let mut cases: Vec<(Vec<u8>, Vec<u8>)> = vec![ |
| 353 | (b"".into(), b"".into()), |
| 354 | (b"".into(), b"a".into()), |
| 355 | (b"a".into(), b"a".into()), |
| 356 | (b"a".into(), b"b".into()), |
| 357 | (b"abc".into(), b"".into()), |
| 358 | (b"abc".into(), b"c".into()), |
| 359 | (b"abc".into(), b"d".into()), |
| 360 | (b"aaaa".into(), b"aa".into()), // overlapping: the first wins |
| 361 | (b"abaaa".into(), b"aaa".into()), // a false start at 1 |
| 362 | (b"ab".into(), b"abc".into()), // longer than the haystack |
| 363 | (b"hello world".into(), b"o w".into()), |
| 364 | (b"hello world".into(), b"world!".into()), |
| 365 | // Pair-filter false friends: `a...a` passes the filter, the |
| 366 | // middle differs. |
| 367 | (b"axxb ayyc azzc".into(), b"abbc".into()), |
| 368 | (b"a___b a___c a___d".into(), b"a___e".into()), |
| 369 | (b"needle at the very end: mark".into(), b"mark".into()), |
| 370 | // Multibyte UTF-8: matches stay on character boundaries. |
| 371 | ("héllo, wörld".as_bytes().into(), "wörld".as_bytes().into()), |
| 372 | ("é🦀é🦀é".as_bytes().into(), "🦀é".as_bytes().into()), |
| 373 | ]; |
| 374 | // The dispatch boundaries, each found, missed and at the end. |
| 375 | for n in [1usize, 2, 3, 4, 5, 15, 16, 17, 63, 64, 65] { |
| 376 | let needle = vec![b'q'; n]; // 'q' never occurs in `long` |
| 377 | cases.push((long.clone(), needle.clone())); |
| 378 | let mut hit = long.clone(); |
| 379 | let at = hit.len() - n - 3; // near the end, past the tail start |
| 380 | hit[at..at + n].copy_from_slice(&needle); |
| 381 | cases.push((hit, needle.clone())); |
| 382 | let mut head = long.clone(); |
| 383 | head[..n].copy_from_slice(&needle); // at 0 |
| 384 | cases.push((head, needle)); |
| 385 | } |
| 386 | for (h, n) in &cases { |
| 387 | check(h, n, "directed"); |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | /// Pseudo-random inputs (a SplitMix64, no dependencies): small |
| 392 | /// alphabets so matches are dense, haystacks and needles across the |
| 393 | /// dispatch boundaries. |
| 394 | #[test] |
| 395 | fn find_matches_a_naive_scan_on_random_inputs() { |
| 396 | let mut state = 0x9E37_79B9_7F4A_7C15u64; |
| 397 | let mut next = move || { |
| 398 | state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); |
| 399 | let mut z = state; |
| 400 | z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); |
| 401 | z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); |
| 402 | z ^ (z >> 31) |
| 403 | }; |
| 404 | for case in 0..2000 { |
| 405 | let alphabet: &[u8] = match case % 4 { |
| 406 | 0 => b"a", |
| 407 | 1 => b"ab", |
| 408 | 2 => b"aab b", |
| 409 | _ => "aab bcé🦀".as_bytes(), // multibyte bytes, searched raw |
| 410 | }; |
| 411 | let draw = |next: &mut dyn FnMut() -> u64, max: usize| -> Vec<u8> { |
| 412 | let len = (next() as usize) % (max + 1); |
| 413 | (0..len) |
| 414 | .map(|_| alphabet[(next() as usize) % alphabet.len()]) |
| 415 | .collect() |
| 416 | }; |
| 417 | let h = draw(&mut next, 300); |
| 418 | // Half the needles are cut from the haystack (a sure hit, |
| 419 | // raw bytes: possibly mid-character, which both searches see |
| 420 | // alike), half are drawn fresh. |
| 421 | let n = if case % 2 == 0 && !h.is_empty() { |
| 422 | let at = (next() as usize) % h.len(); |
| 423 | let len = ((next() as usize) % 70).min(h.len() - at); |
| 424 | h[at..at + len].to_vec() |
| 425 | } else { |
| 426 | draw(&mut next, 70) |
| 427 | }; |
| 428 | check(&h, &n, &format!("case {case}")); |
| 429 | } |
| 430 | } |
| 431 | } |