Debian Codegraph @

src/hamming.rs

raw symbols SCIP
1 //! This module provides many Hamming distance routines.
2 //!
3 //! These distance functions share the same efficient underlying SIMD-accelerated implementation:
4 //! * `hamming`
5 //! * `hamming_simd_parallel`
6 //!
7 //! These search functions share the same efficient underlying SIMD-accelerated implementation:
8 //! * `hamming_search`
9 //! * `hamming_search_simd`
10 //! * `hamming_search_simd_with_opts`
11
12 use std::*;
13
14 use super::*;
15 use super::jewel::*;
16
17 /// Returns the hamming distance between two strings by naively counting mismatches.
18 ///
19 /// The length of `a` and `b` must be the same.
20 ///
21 /// # Arguments
22 /// * `a` - first string (slice)
23 /// * `b` - second string (slice)
24 ///
25 /// # Panics
26 /// * If the length of `a` does not equal the length of `b`.
27 ///
28 /// # Example
29 /// ```
30 /// # use triple_accel::*;
31 /// # use triple_accel::hamming::*;
32 /// let dist = hamming_naive(b"abc", b"abd");
33 ///
34 /// assert!(dist == 1);
35 /// ```
36 pub fn hamming_naive(a: &[u8], b: &[u8]) -> u32 {
37 let len = a.len();
38 assert!(len == b.len());
39
40 let mut res = 0u32;
41
42 for i in 0..len {
43 res += (a[i] != b[i]) as u32;
44 }
45
46 res
47 }
48
49 /// Returns an iterator over best `Match`s by naively searching through the text `haystack`
50 /// for the pattern `needle`.
51 ///
52 /// This is done by naively counting mismatches at every position in `haystack`.
53 /// Only the matches with the lowest Hamming distance are returned.
54 /// Each returned `Match` requires at least half or more bytes of the `needle` to match
55 /// somewhere in the `haystack`.
56 /// The length of `needle` must be less than or equal to the length of `haystack`.
57 ///
58 /// # Arguments
59 /// * `needle` - pattern string (slice)
60 /// * `haystack` - text string (slice)
61 ///
62 /// # Example
63 /// ```
64 /// # use triple_accel::*;
65 /// # use triple_accel::hamming::*;
66 /// let matches: Vec<Match> = hamming_search_naive(b"abc", b" abd").collect();
67 ///
68 /// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
69 /// ```
70 pub fn hamming_search_naive<'a>(needle: &'a [u8], haystack: &'a [u8]) -> Box<dyn Iterator<Item = Match> + 'a> {
71 hamming_search_naive_with_opts(needle, haystack, ((needle.len() as u32) >> 1) + ((needle.len() as u32) & 1), SearchType::Best)
72 }
73
74 /// Returns an iterator over `Match`s by naively searching through the text `haystack`
75 /// for the pattern `needle`, with extra options.
76 ///
77 /// Only matches with less than `k` mismatches are returned.
78 /// This is done by naively counting mismatches at every position in `haystack`.
79 /// The length of `needle` must be less than or equal to the length of `haystack`.
80 ///
81 /// # Arguments
82 /// * `needle` - pattern string (slice)
83 /// * `haystack` - text string (slice)
84 /// * `k` - number of mismatches allowed
85 /// * `search_type` - whether to only return the "best" matches with the lowest Hamming distance, or
86 /// all matches
87 ///
88 /// # Example
89 /// ```
90 /// # use triple_accel::*;
91 /// # use triple_accel::hamming::*;
92 /// let matches: Vec<Match> = hamming_search_naive_with_opts(b"abc", b" abd", 1, SearchType::All).collect();
93 ///
94 /// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
95 /// ```
96 pub fn hamming_search_naive_with_opts<'a>(needle: &'a [u8], haystack: &'a [u8], k: u32, search_type: SearchType) -> Box<dyn Iterator<Item = Match> + 'a> {
97 let needle_len = needle.len();
98 let haystack_len = haystack.len();
99
100 if needle_len > haystack_len {
101 return Box::new(iter::empty());
102 }
103
104 let len = haystack_len + 1 - needle_len;
105 let mut curr_k = k;
106 let mut i = 0;
107
108 let res = iter::from_fn(move || {
109 'outer: while i < len {
110 let mut final_res = 0u32;
111
112 for j in 0..needle_len {
113 final_res += (needle[j] != haystack[i + j]) as u32;
114
115 // early stop
116 if final_res > curr_k {
117 i += 1;
118 continue 'outer;
119 }
120 }
121
122 match search_type {
123 SearchType::Best => curr_k = final_res,
124 _ => ()
125 }
126
127 i += 1;
128
129 return Some((Match{start: i - 1, end: i + needle_len - 1, k: final_res}, curr_k));
130 }
131
132 None
133 });
134
135 if search_type == SearchType::Best {
136 let mut res_vec = Vec::with_capacity(haystack_len / needle_len);
137 res.for_each(|m| {
138 res_vec.push(m.0);
139 curr_k = m.1;
140 });
141
142 return Box::new(res_vec.into_iter().filter(move |m| m.k == curr_k));
143 }
144
145 Box::new(res.map(|m| m.0))
146 }
147
148 /// Returns the hamming distance between two strings by efficiently counting mismatches in chunks of 64 bits.
149 ///
150 /// The length of `a` and `b` must be the same.
151 /// Both `a` and `b` must be aligned and padded so they can be directly casted to chunks of `u64`.
152 /// Use `alloc_str` to create aligned and padded strings.
153 /// This should be faster than `hamming_naive` and maybe even `hamming_words_128`. This should be slower
154 /// than `hamming_simd_parallel/movemask`.
155 ///
156 /// # Arguments
157 /// * `a` - first string (slice)
158 /// * `b` - second string (slice)
159 ///
160 /// # Panics
161 /// * If the length of `a` does not equal the length of `b`.
162 ///
163 /// # Example
164 /// ```
165 /// # use triple_accel::*;
166 /// # use triple_accel::hamming::*;
167 /// let mut a = alloc_str(3);
168 /// let mut b = alloc_str(3);
169 /// fill_str(&mut a, b"abc");
170 /// fill_str(&mut b, b"abd");
171 ///
172 /// let dist = hamming_words_64(&a, &b);
173 ///
174 /// assert!(dist == 1);
175 /// ```
176 pub fn hamming_words_64(a: &[u8], b: &[u8]) -> u32 {
177 assert!(a.len() == b.len());
178
179 unsafe {
180 let mut res = 0u32;
181 // the pointer address better be aligned for u64
182 // may not be in little endian
183 let a_ptr = a.as_ptr() as *const u64;
184 let b_ptr = b.as_ptr() as *const u64;
185 let words_len = (a.len() >> 3) as isize;
186
187 for i in 0..words_len {
188 // change to little endian omitted because it is not necessary in this case
189 let mut r = (*a_ptr.offset(i)) ^ (*b_ptr.offset(i));
190 // reduce or by "folding" one half of each byte onto the other multiple times
191 r |= r >> 4;
192 // ...00001111
193 r &= 0x0f0f0f0f0f0f0f0fu64;
194 r |= r >> 2;
195 // ...00110011
196 r &= 0x3333333333333333u64;
197 r |= r >> 1;
198 // ...01010101
199 r &= 0x5555555555555555u64;
200 res += r.count_ones();
201 }
202
203 let words_rem = a.len() & 7;
204
205 if words_rem > 0 {
206 let mut r = (*a_ptr.offset(words_len)) ^ (*b_ptr.offset(words_len));
207 r |= r >> 4;
208 r &= 0x0f0f0f0f0f0f0f0fu64;
209 r |= r >> 2;
210 r &= 0x3333333333333333u64;
211 r |= r >> 1;
212 r &= 0x5555555555555555u64;
213 // make sure to mask out bits outside the string lengths
214 res += (r & ((1u64 << ((words_rem as u64) << 3u64)) - 1u64)).count_ones();
215 }
216
217 res
218 }
219 }
220
221 /// Returns the hamming distance between two strings by counting mismatches in chunks of 128 bits.
222 ///
223 /// The length of `a` and `b` must be the same.
224 /// Both `a` and `b` must be aligned and padded so they can be directly casted to chunks of `u128`.
225 /// Use `alloc_str` to create aligned and padded strings.
226 /// This may be slower than `hamming_words_64` in practice, probably since Rust `u128` is not as
227 /// optimized. This should be slower than `hamming_simd_parallel/movemask`.
228 ///
229 /// # Arguments
230 /// * `a` - first string (slice)
231 /// * `b` - second string (slice)
232 ///
233 /// # Panics
234 /// * If the length of `a` does not equal the length of `b`.
235 ///
236 /// # Example
237 /// ```
238 /// # use triple_accel::*;
239 /// # use triple_accel::hamming::*;
240 /// let mut a = alloc_str(3);
241 /// let mut b = alloc_str(3);
242 /// fill_str(&mut a, b"abc");
243 /// fill_str(&mut b, b"abd");
244 ///
245 /// let dist = hamming_words_128(&a, &b);
246 ///
247 /// assert!(dist == 1);
248 /// ```
249 pub fn hamming_words_128(a: &[u8], b: &[u8]) -> u32 {
250 assert!(a.len() == b.len());
251
252 unsafe {
253 let mut res = 0u32;
254 // the pointer address better be aligned for u128
255 // may not be in little endian
256 let a_ptr = a.as_ptr() as *const u128;
257 let b_ptr = b.as_ptr() as *const u128;
258 let words_len = (a.len() >> 4) as isize;
259
260 for i in 0..words_len {
261 // change to little endian omitted because it is not necessary in this case
262 let mut r = (*a_ptr.offset(i)) ^ (*b_ptr.offset(i));
263 // reduce or by "folding" one half of each byte onto the other multiple times
264 r |= r >> 4;
265 // ...00001111
266 r &= 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0fu128;
267 r |= r >> 2;
268 // ...00110011
269 r &= 0x33333333333333333333333333333333u128;
270 r |= r >> 1;
271 // ...01010101
272 r &= 0x55555555555555555555555555555555u128;
273 res += r.count_ones();
274 }
275
276 let words_rem = a.len() & 15;
277
278 if words_rem > 0 {
279 let mut r = (*a_ptr.offset(words_len)) ^ (*b_ptr.offset(words_len));
280 r |= r >> 4;
281 r &= 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0fu128;
282 r |= r >> 2;
283 r &= 0x33333333333333333333333333333333u128;
284 r |= r >> 1;
285 r &= 0x55555555555555555555555555555555u128;
286 // make sure to mask out bits outside the string lengths
287 res += (r & ((1u128 << ((words_rem as u128) << 3u128)) - 1u128)).count_ones();
288 }
289
290 res
291 }
292 }
293
294 /// Returns the hamming distance between two strings by counting mismatches using SIMD vectors to
295 /// increment multiple counters in parallel.
296 ///
297 /// The length of `a` and `b` must be the same.
298 /// There are no constraints on how `a` and `b` are aligned and padded.
299 /// This will automatically fall back to `hamming_naive`, if AVX2 and SSE4.1 are not supported.
300 /// This should be faster than both `hamming_word_64/128` and `hamming_simd_movemask`.
301 ///
302 /// # Arguments
303 /// * `a` - first string (slice)
304 /// * `b` - second string (slice)
305 ///
306 /// # Panics
307 /// * If the length of `a` does not equal the length of `b`.
308 ///
309 /// # Example
310 /// ```
311 /// # use triple_accel::*;
312 /// # use triple_accel::hamming::*;
313 /// let dist = hamming_simd_parallel(b"abc", b"abd");
314 ///
315 /// assert!(dist == 1);
316 /// ```
317 pub fn hamming_simd_parallel(a: &[u8], b: &[u8]) -> u32 {
318 assert!(a.len() == b.len());
319
320 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
321 {
322 if cfg!(feature = "jewel-avx") && is_x86_feature_detected!("avx2") {
323 return unsafe {Avx::count_mismatches(a.as_ptr(), b.as_ptr(), a.len())};
324 }else if cfg!(feature = "jewel-sse") && is_x86_feature_detected!("sse4.1") {
325 return unsafe {Sse::count_mismatches(a.as_ptr(), b.as_ptr(), a.len())};
326 }
327 }
328
329 hamming_naive(a, b)
330 }
331
332 /// Returns the hamming distance between two strings by counting mismatches using the SIMD movemask intrinsic.
333 ///
334 /// The length of `a` and `b` must be the same.
335 /// There are no constraints on how `a` and `b` are aligned and padded.
336 /// This will automatically fall back to `hamming_naive`, if AVX2 and SSE4.1 are not supported.
337 /// This should be faster than `hamming_word_64/128`, but slower than `hamming_simd_parallel`.
338 ///
339 /// # Arguments
340 /// * `a` - first string (slice)
341 /// * `b` - second string (slice)
342 ///
343 /// # Panics
344 /// * If the length of `a` does not equal the length of `b`.
345 ///
346 /// # Example
347 /// ```
348 /// # use triple_accel::*;
349 /// # use triple_accel::hamming::*;
350 /// let dist = hamming_simd_movemask(b"abc", b"abd");
351 ///
352 /// assert!(dist == 1);
353 /// ```
354 pub fn hamming_simd_movemask(a: &[u8], b: &[u8]) -> u32 {
355 assert!(a.len() == b.len());
356
357 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
358 {
359 if cfg!(feature = "jewel-avx") && is_x86_feature_detected!("avx2") {
360 return unsafe {Avx::mm_count_mismatches(a.as_ptr(), b.as_ptr(), a.len())};
361 }else if cfg!(feature = "jewel-sse") && is_x86_feature_detected!("sse4.1") {
362 return unsafe {Sse::mm_count_mismatches(a.as_ptr(), b.as_ptr(), a.len())};
363 }
364 }
365
366 hamming_naive(a, b)
367 }
368
369 /// Returns the hamming distance between two strings using the best method.
370 ///
371 /// The length of `a` and `b` must be the same.
372 /// This will automatically fall back to a scalar alternative if AVX2 and
373 /// SSE4.1 are not supported.
374 /// Internally, this calls `hamming_simd_parallel`.
375 ///
376 /// # Arguments
377 /// * `a` - first string (slice)
378 /// * `b` - second string (slice)
379 ///
380 /// # Panics
381 /// * If the length of `a` does not equal the length of `b`.
382 ///
383 /// # Example
384 /// ```
385 /// # use triple_accel::*;
386 /// let dist = hamming(b"abc", b"abd");
387 ///
388 /// assert!(dist == 1);
389 /// ```
390 pub fn hamming(a: &[u8], b: &[u8]) -> u32 {
391 hamming_simd_parallel(a, b)
392 }
393
394 /// Returns an iterator over best `Match`s by searching through the text `haystack`
395 /// for the pattern `needle` using SIMD.
396 ///
397 /// This is done by counting mismatches at every position in `haystack`.
398 /// This will automatically fall back to `hamming_search_naive_with_opts` if AVX2 and SSE4.1
399 /// are not supported.
400 /// Null bytes/characters are not supported.
401 /// The length of `needle` must be less than or equal to the length of `haystack`.
402 /// Each returned `Match` requires at least half or more bytes of the `needle` to match
403 /// somwhere in the `haystack`.
404 /// Only the matches with the lowest Hamming distance are returned.
405 /// This should be faster than `hamming_search_naive`.
406 ///
407 /// # Arguments
408 /// * `needle` - pattern string (slice)
409 /// * `haystack` - text string (slice)
410 ///
411 /// # Panics
412 /// * When there are zero/null bytes in the `haystack` string.
413 ///
414 /// # Example
415 /// ```
416 /// # use triple_accel::*;
417 /// # use triple_accel::hamming::*;
418 /// let matches: Vec<Match> = hamming_search_simd(b"abc", b" abd").collect();
419 ///
420 /// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
421 /// ```
422 pub fn hamming_search_simd<'a>(needle: &'a [u8], haystack: &'a [u8]) -> Box<dyn Iterator<Item = Match> + 'a> {
423 hamming_search_simd_with_opts(needle, haystack, ((needle.len() as u32) >> 1) + ((needle.len() as u32) & 1), SearchType::Best)
424 }
425
426 /// Returns an iterator over `Match`s by searching through the text `haystack` for the
427 /// pattern `needle` using SIMD, with extra options.
428 ///
429 /// This is done by using SIMD to count mismatches at every position in `haystack`.
430 /// This will automatically fall back to `hamming_search_naive_with_opts` if AVX2 and SSE4.1
431 /// are not supported.
432 /// Null bytes/characters are not supported.
433 /// The length of `needle` must be less than or equal to the length of `haystack`.
434 /// This should be faster than `hamming_search_naive_with_opts`.
435 ///
436 /// # Arguments
437 /// * `needle` - pattern string (slice)
438 /// * `haystack` - text string (slice)
439 /// * `k` - number of mismatches allowed
440 /// * `search_type` - whether to only return the "best" matches with the lowest Hamming distance, or
441 /// all matches
442 ///
443 /// # Panics
444 /// * When there are zero/null bytes in the `haystack` string.
445 ///
446 /// # Example
447 /// ```
448 /// # use triple_accel::*;
449 /// # use triple_accel::hamming::*;
450 /// let matches: Vec<Match> = hamming_search_simd_with_opts(b"abc", b" abd", 1, SearchType::All).collect();
451 ///
452 /// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
453 /// ```
454 pub fn hamming_search_simd_with_opts<'a>(needle: &'a [u8], haystack: &'a [u8], k: u32, search_type: SearchType) -> Box<dyn Iterator<Item = Match> + 'a> {
455 if needle.len() > haystack.len() {
456 return Box::new(iter::empty());
457 }
458
459 if needle.len() == 0 {
460 return Box::new(iter::empty());
461 }
462
463 check_no_null_bytes(haystack);
464
465 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
466 {
467 if cfg!(feature = "jewel-avx") && is_x86_feature_detected!("avx2") {
468 return unsafe {hamming_search_simd_core_avx(needle, haystack, k, search_type)};
469 }else if cfg!(feature = "jewel-sse") && is_x86_feature_detected!("sse4.1") {
470 return unsafe {hamming_search_simd_core_sse(needle, haystack, k, search_type)};
471 }
472 }
473
474 hamming_search_naive_with_opts(needle, haystack, k, search_type)
475 }
476
477 macro_rules! create_hamming_search_simd_core {
478 ($name:ident, $jewel:ty, $target:literal) => {
479 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
480 #[target_feature(enable = $target)]
481 unsafe fn $name<'a>(needle: &'a [u8], haystack: &'a [u8], k: u32, search_type: SearchType) -> Box<dyn Iterator<Item = Match> + 'a> {
482 #[cfg(feature = "debug")]
483 {
484 println!("Debug: Hamming search Jewel vector type {} for target {}.", stringify!($jewel), stringify!($target));
485 }
486
487 let needle_len = needle.len();
488 let haystack_len = haystack.len();
489 let needle_vector = <$jewel>::loadu(needle.as_ptr(), needle_len);
490 // calculate len using the unused bytes in the needle Jewel vector, for speed
491 // there may be leftover positions in haystack that need to be calculated using a
492 // scalar search afterwards
493 // there should be no null bytes in the strings
494 let len = if needle_vector.upper_bound() > haystack_len {0} else {haystack_len + 1 - needle_vector.upper_bound()};
495 let real_len = haystack_len + 1 - needle_len;
496 let haystack_ptr = haystack.as_ptr();
497 let mut curr_k = k;
498 let mut i = 0;
499
500 let res = iter::from_fn(move || {
501 while i < len {
502 let final_res = <$jewel>::vector_count_mismatches(&needle_vector, haystack_ptr.offset(i as isize), needle_len);
503 i += 1;
504
505 if final_res <= curr_k {
506 match search_type {
507 SearchType::Best => curr_k = final_res,
508 _ => ()
509 }
510
511 return Some((Match{start: i - 1, end: i + needle_len - 1, k: final_res}, curr_k));
512 }
513 }
514
515 // scalar search
516 'outer: while i < real_len {
517 let mut final_res = 0u32;
518
519 for j in 0..needle_len {
520 final_res += (*needle.get_unchecked(j) != *haystack.get_unchecked(i + j)) as u32;
521
522 if final_res > curr_k {
523 i += 1;
524 continue 'outer;
525 }
526 }
527
528 match search_type {
529 SearchType::Best => curr_k = final_res,
530 _ => ()
531 }
532
533 i += 1;
534
535 return Some((Match{start: i - 1, end: i + needle_len - 1, k: final_res}, curr_k));
536 }
537
538 None
539 });
540
541 if search_type == SearchType::Best {
542 let mut res_vec = Vec::with_capacity(haystack_len / needle_len);
543 res.for_each(|m| {
544 res_vec.push(m.0);
545 curr_k = m.1;
546 });
547
548 return Box::new(res_vec.into_iter().filter(move |m| m.k == curr_k));
549 }
550
551 Box::new(res.map(|m| m.0))
552 }
553 };
554 }
555
556 // generate different versions for different intrinsics
557 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
558 create_hamming_search_simd_core!(hamming_search_simd_core_avx, Avx, "avx2");
559 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
560 create_hamming_search_simd_core!(hamming_search_simd_core_sse, Sse, "sse4.1");
561
562 /// Returns an iterator over best `Match`s by searching through the text `haystack`
563 /// for the pattern `needle` using SIMD.
564 ///
565 /// This will automatically fall back to a scalar alternative if AVX2 and SSE4.1
566 /// are not supported.
567 /// Null bytes/characters are not supported.
568 /// The length of `needle` must be less than or equal to the length of `haystack`.
569 /// Each returned `Match` requires at least half or more bytes of the `needle` to match
570 /// somewhere in the `haystack`.
571 /// Only the matches with the lowest Hamming distance are returned.
572 /// Internally, this calls `hamming_search_simd`.
573 ///
574 /// # Arguments
575 /// * `needle` - pattern string (slice)
576 /// * `haystack` - text string (slice)
577 ///
578 /// # Panics
579 /// * When there are zero/null bytes in the `haystack` string.
580 ///
581 /// # Example
582 /// ```
583 /// # use triple_accel::*;
584 /// let matches: Vec<Match> = hamming_search(b"abc", b" abd").collect();
585 ///
586 /// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
587 /// ```
588 pub fn hamming_search<'a>(needle: &'a [u8], haystack: &'a [u8]) -> Box<dyn Iterator<Item = Match> + 'a> {
589 hamming_search_simd(needle, haystack)
590 }
591