| @@ -220,6 +220,148 @@ pub fn parse_float(s: &str) -> Result<f64, String> { |
| 220 | 220 | s.parse::<f64>().map_err(|_| format!("not a float: {s:?}")) |
| 221 | 221 | } |
| 222 | 222 | |
| 223 | +// ---- substring search (string.find, string.contains) -------------------------- |
| 224 | +// |
| 225 | +// memchr's "generic SIMD" substring search as SWAR: no nightly features and |
| 226 | +// no architecture intrinsics, so every target and both backends run the one |
| 227 | +// kernel (the interpreter is the native backend's oracle). A machine word |
| 228 | +// plays the part of a vector: eight candidate positions per step, sixteen |
| 229 | +// or thirty-two with unrolling. |
| 230 | + |
| 231 | +/// SWAR over a `u64`: the low and high bits of every byte lane. |
| 232 | +const SWAR_LO: u64 = 0x0101_0101_0101_0101; |
| 233 | +const SWAR_HI: u64 = 0x8080_8080_8080_8080; |
| 234 | +const WORD: usize = size_of::<u64>(); |
| 235 | + |
| 236 | +/// The high bit of each byte lane of `w` whose byte equals `b` |
| 237 | +/// (`haszero(w ^ broadcast(b))`, exact: no false lanes). |
| 238 | +fn eq_mask(w: u64, b: u8) -> u64 { |
| 239 | + let x = w ^ (SWAR_LO * u64::from(b)); |
| 240 | + x.wrapping_sub(SWAR_LO) & !x & SWAR_HI |
| 241 | +} |
| 242 | + |
| 243 | +/// Eight bytes of `h` at `i` as a little-endian word, so byte `i + k` is |
| 244 | +/// lane `k` and a mask's lowest set bit is the first match, whatever the |
| 245 | +/// host's endianness. `i + WORD` must not exceed `h.len()`. |
| 246 | +fn word_at(h: &[u8], i: usize) -> u64 { |
| 247 | + u64::from_le_bytes(h[i..i + WORD].try_into().expect("louise: SWAR word")) |
| 248 | +} |
| 249 | + |
| 250 | +/// The lane index of a mask's lowest set bit. |
| 251 | +fn first_lane(mask: u64) -> usize { |
| 252 | + (mask.trailing_zeros() / 8) as usize |
| 253 | +} |
| 254 | + |
| 255 | +/// The first index of `b` in `h` (memchr, SWAR): four words per step, |
| 256 | +/// then one, then a short scalar tail. |
| 257 | +fn find_byte(h: &[u8], b: u8) -> Option<usize> { |
| 258 | + let mut i = 0; |
| 259 | + while i + 4 * WORD <= h.len() { |
| 260 | + let masks = [ |
| 261 | + eq_mask(word_at(h, i), b), |
| 262 | + eq_mask(word_at(h, i + WORD), b), |
| 263 | + eq_mask(word_at(h, i + 2 * WORD), b), |
| 264 | + eq_mask(word_at(h, i + 3 * WORD), b), |
| 265 | + ]; |
| 266 | + if masks.iter().any(|&m| m != 0) { |
| 267 | + for (u, &m) in masks.iter().enumerate() { |
| 268 | + if m != 0 { |
| 269 | + return Some(i + u * WORD + first_lane(m)); |
| 270 | + } |
| 271 | + } |
| 272 | + unreachable!("louise: a mask was set"); |
| 273 | + } |
| 274 | + i += 4 * WORD; |
| 275 | + } |
| 276 | + while i + WORD <= h.len() { |
| 277 | + let m = eq_mask(word_at(h, i), b); |
| 278 | + if m != 0 { |
| 279 | + return Some(i + first_lane(m)); |
| 280 | + } |
| 281 | + i += WORD; |
| 282 | + } |
| 283 | + h[i..].iter().position(|&x| x == b).map(|k| i + k) |
| 284 | +} |
| 285 | + |
| 286 | +/// The first index of `needle` in `h`, filtered on its first and last |
| 287 | +/// byte (memchr's packed pair): a word of candidate first bytes ANDed |
| 288 | +/// with a word of last bytes `len - 1` ahead leaves few survivors, each |
| 289 | +/// confirmed whole. `UNROLL` words per step; `h` is at least `needle`'s |
| 290 | +/// length, so `i + k` over a mask never passes `h.len() - len`. |
| 291 | +fn find_pair<const UNROLL: usize>(h: &[u8], needle: &[u8]) -> Option<usize> { |
| 292 | + let len = needle.len(); |
| 293 | + let (first, last) = (needle[0], needle[len - 1]); |
| 294 | + let d = len - 1; |
| 295 | + let last_start = h.len() - len; |
| 296 | + let mut i = 0; |
| 297 | + while i + d + UNROLL * WORD <= h.len() { |
| 298 | + let mut any = 0; |
| 299 | + let mut masks = [0u64; UNROLL]; |
| 300 | + for (u, m) in masks.iter_mut().enumerate() { |
| 301 | + *m = eq_mask(word_at(h, i + u * WORD), first) |
| 302 | + & eq_mask(word_at(h, i + u * WORD + d), last); |
| 303 | + any |= *m; |
| 304 | + } |
| 305 | + if any != 0 { |
| 306 | + for (u, &m) in masks.iter().enumerate() { |
| 307 | + let mut m = m; |
| 308 | + while m != 0 { |
| 309 | + let at = i + u * WORD + first_lane(m); |
| 310 | + m &= m - 1; |
| 311 | + if h[at..at + len] == *needle { |
| 312 | + return Some(at); |
| 313 | + } |
| 314 | + } |
| 315 | + } |
| 316 | + } |
| 317 | + i += UNROLL * WORD; |
| 318 | + } |
| 319 | + // One word at a time until the tail is shorter than a word. |
| 320 | + while i + d + WORD <= h.len() { |
| 321 | + let mut m = eq_mask(word_at(h, i), first) & eq_mask(word_at(h, i + d), last); |
| 322 | + while m != 0 { |
| 323 | + let at = i + first_lane(m); |
| 324 | + m &= m - 1; |
| 325 | + if h[at..at + len] == *needle { |
| 326 | + return Some(at); |
| 327 | + } |
| 328 | + } |
| 329 | + i += WORD; |
| 330 | + } |
| 331 | + // The tail: under `WORD + d` candidates, checked scalar. |
| 332 | + let mut at = i; |
| 333 | + while at <= last_start { |
| 334 | + if h[at] == first && h[at + d] == last && h[at..at + len] == *needle { |
| 335 | + return Some(at); |
| 336 | + } |
| 337 | + at += 1; |
| 338 | + } |
| 339 | + None |
| 340 | +} |
| 341 | + |
| 342 | +/// The byte index of `needle`'s first occurrence in `haystack` |
| 343 | +/// (`string.find`), or `None`; the empty needle is found at 0. |
| 344 | +/// |
| 345 | +/// Both arguments are valid UTF-8, so a byte match of `needle` starts on |
| 346 | +/// a character boundary. Dispatched by needle length (memchr's law: no |
| 347 | +/// single substring algorithm wins everywhere): |
| 348 | +/// |
| 349 | +/// | needle | search | |
| 350 | +/// |-----------|--------| |
| 351 | +/// | 0 bytes | `Some(0)` | |
| 352 | +/// | 1 byte | SWAR memchr, 32 bytes a step | |
| 353 | +/// | 2–4 bytes | first/last-byte pair filter, 8 bytes a step, survivors confirmed | |
| 354 | +/// | 5+ bytes | the same pair filter, 16 bytes a step | |
| 355 | +pub fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> { |
| 356 | + match needle.len() { |
| 357 | + 0 => Some(0), |
| 358 | + 1 => find_byte(haystack, needle[0]), |
| 359 | + 2..=4 if needle.len() <= haystack.len() => find_pair::<1>(haystack, needle), |
| 360 | + _ if needle.len() <= haystack.len() => find_pair::<2>(haystack, needle), |
| 361 | + _ => None, |
| 362 | + } |
| 363 | +} |
| 364 | + |
| 223 | 365 | /// The HTML replacement of a metacharacter, if `b` is one (`& < > " '`). |
| 224 | 366 | fn html_replacement(b: u8) -> Option<&'static [u8]> { |
| 225 | 367 | match b { |
| @@ -899,6 +1041,105 @@ mod tests { |
| 899 | 1041 | assert_eq!(split("", ","), [""]); |
| 900 | 1042 | } |
| 901 | 1043 | |
| 1044 | + /// `find` against a naive scan, on directed cases: the dispatch |
| 1045 | + /// boundaries (needle 0/1/2/4/5/16/64 bytes), matches at the edges, |
| 1046 | + /// overlaps, and pair-filter false friends (first and last byte |
| 1047 | + /// match, the middle does not). |
| 1048 | + #[test] |
| 1049 | + fn find_matches_a_naive_scan_on_directed_cases() { |
| 1050 | + fn naive(h: &[u8], n: &[u8]) -> Option<usize> { |
| 1051 | + if n.is_empty() { |
| 1052 | + return Some(0); |
| 1053 | + } |
| 1054 | + (0..=h.len().checked_sub(n.len())?).find(|&i| h[i] == n[0] && &h[i..i + n.len()] == n) |
| 1055 | + } |
| 1056 | + let long: Vec<u8> = (0..1000u32).map(|i| b"aab baca "[i as usize % 9]).collect(); |
| 1057 | + let mut cases: Vec<(Vec<u8>, Vec<u8>)> = vec![ |
| 1058 | + (b"".into(), b"".into()), |
| 1059 | + (b"".into(), b"a".into()), |
| 1060 | + (b"a".into(), b"a".into()), |
| 1061 | + (b"a".into(), b"b".into()), |
| 1062 | + (b"abc".into(), b"".into()), |
| 1063 | + (b"abc".into(), b"c".into()), |
| 1064 | + (b"abc".into(), b"d".into()), |
| 1065 | + (b"aaaa".into(), b"aa".into()), // overlapping: the first wins |
| 1066 | + (b"abaaa".into(), b"aaa".into()), // false start at 1 |
| 1067 | + (b"ab".into(), b"abc".into()), // longer than the haystack |
| 1068 | + (b"hello world".into(), b"o w".into()), |
| 1069 | + (b"hello world".into(), b"world!".into()), |
| 1070 | + // Pair-filter false friends: `a...a` passes the filter, the |
| 1071 | + // middle differs. |
| 1072 | + (b"axxb ayyc azzc".into(), b"abbc".into()), |
| 1073 | + (b"a___b a___c a___d".into(), b"a___e".into()), |
| 1074 | + (b"needle at the very end: mark".into(), b"mark".into()), |
| 1075 | + // Multibyte UTF-8: matches stay on character boundaries. |
| 1076 | + ("héllo, wörld".as_bytes().into(), "wörld".as_bytes().into()), |
| 1077 | + ("é🦀é🦀é".as_bytes().into(), "🦀é".as_bytes().into()), |
| 1078 | + ]; |
| 1079 | + // The dispatch boundaries, each found, missed and at the end. |
| 1080 | + for n in [1usize, 2, 3, 4, 5, 15, 16, 17, 63, 64, 65] { |
| 1081 | + let needle = vec![b'q'; n]; // 'q' never occurs in `long` |
| 1082 | + cases.push((long.clone(), needle.clone())); |
| 1083 | + let mut hit = long.clone(); |
| 1084 | + let at = hit.len() - n - 3; // near the end, past the tail start |
| 1085 | + hit[at..at + n].copy_from_slice(&needle); |
| 1086 | + cases.push((hit, needle.clone())); |
| 1087 | + let mut head = long.clone(); |
| 1088 | + head[..n].copy_from_slice(&needle); // at 0 |
| 1089 | + cases.push((head, needle)); |
| 1090 | + } |
| 1091 | + for (h, n) in &cases { |
| 1092 | + assert_eq!(find(h, n), naive(h, n), "needle {n:?}"); |
| 1093 | + } |
| 1094 | + } |
| 1095 | + |
| 1096 | + /// `find` against a naive scan on pseudo-random inputs (a SplitMix64, |
| 1097 | + /// no dependencies): small alphabets so matches are dense, haystacks |
| 1098 | + /// and needles across the dispatch boundaries. |
| 1099 | + #[test] |
| 1100 | + fn find_matches_a_naive_scan_on_random_inputs() { |
| 1101 | + fn naive(h: &[u8], n: &[u8]) -> Option<usize> { |
| 1102 | + if n.is_empty() { |
| 1103 | + return Some(0); |
| 1104 | + } |
| 1105 | + (0..=h.len().checked_sub(n.len())?).find(|&i| h[i] == n[0] && &h[i..i + n.len()] == n) |
| 1106 | + } |
| 1107 | + let mut state = 0x9E37_79B9_7F4A_7C15u64; |
| 1108 | + let mut next = move || { |
| 1109 | + state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); |
| 1110 | + let mut z = state; |
| 1111 | + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); |
| 1112 | + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); |
| 1113 | + z ^ (z >> 31) |
| 1114 | + }; |
| 1115 | + for case in 0..2000 { |
| 1116 | + let alphabet: &[u8] = match case % 4 { |
| 1117 | + 0 => b"a", |
| 1118 | + 1 => b"ab", |
| 1119 | + 2 => b"aab b", |
| 1120 | + _ => "aab bcé🦀".as_bytes(), // multibyte bytes, searched raw |
| 1121 | + }; |
| 1122 | + let draw = |next: &mut dyn FnMut() -> u64, max: usize| -> Vec<u8> { |
| 1123 | + let len = (next() as usize) % (max + 1); |
| 1124 | + (0..len) |
| 1125 | + .map(|_| alphabet[(next() as usize) % alphabet.len()]) |
| 1126 | + .collect() |
| 1127 | + }; |
| 1128 | + let h = draw(&mut next, 300); |
| 1129 | + // Half the needles are cut from the haystack (a sure hit, |
| 1130 | + // raw bytes: possibly mid-character, which both searches see |
| 1131 | + // alike), half are drawn fresh. |
| 1132 | + let n = if case % 2 == 0 && !h.is_empty() { |
| 1133 | + let at = (next() as usize) % h.len(); |
| 1134 | + let len = ((next() as usize) % 70).min(h.len() - at); |
| 1135 | + h[at..at + len].to_vec() |
| 1136 | + } else { |
| 1137 | + draw(&mut next, 70) |
| 1138 | + }; |
| 1139 | + assert_eq!(find(&h, &n), naive(&h, &n), "case {case}: needle {n:?}"); |
| 1140 | + } |
| 1141 | + } |
| 1142 | + |
| 902 | 1143 | #[test] |
| 903 | 1144 | fn chars_splits_on_scalar_values() { |
| 904 | 1145 | assert_eq!(chars("héllo"), ["h", "é", "l", "l", "o"]); |