1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! This module provides many Hamming distance routines.
//!
//! These distance functions share the same efficient underlying SIMD-accelerated implementation:
//! * `hamming`
//! * `hamming_simd_parallel`
//!
//! These search functions share the same efficient underlying SIMD-accelerated implementation:
//! * `hamming_search`
//! * `hamming_search_simd`
//! * `hamming_search_simd_with_opts`

use std::*;

use super::*;
use super::jewel::*;

/// Returns the hamming distance between two strings by naively counting mismatches.
///
/// The length of `a` and `b` must be the same.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
///
/// # Panics
/// * If the length of `a` does not equal the length of `b`.
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::hamming::*;
/// let dist = hamming_naive(b"abc", b"abd");
///
/// assert!(dist == 1);
/// ```
pub fn hamming_naive(a: &[u8], b: &[u8]) -> u32 {
    let len = a.len();
    assert!(len == b.len());

    let mut res = 0u32;

    for i in 0..len {
        res += (a[i] != b[i]) as u32;
    }

    res
}

/// Returns an iterator over best `Match`s by naively searching through the text `haystack`
/// for the pattern `needle`.
///
/// This is done by naively counting mismatches at every position in `haystack`.
/// Only the matches with the lowest Hamming distance are returned.
/// Each returned `Match` requires at least half or more bytes of the `needle` to match
/// somewhere in the `haystack`.
/// The length of `needle` must be less than or equal to the length of `haystack`.
///
/// # Arguments
/// * `needle` - pattern string (slice)
/// * `haystack` - text string (slice)
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::hamming::*;
/// let matches: Vec<Match> = hamming_search_naive(b"abc", b"  abd").collect();
///
/// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
/// ```
pub fn hamming_search_naive<'a>(needle: &'a [u8], haystack: &'a [u8]) -> Box<dyn Iterator<Item = Match> + 'a> {
    hamming_search_naive_with_opts(needle, haystack, ((needle.len() as u32) >> 1) + ((needle.len() as u32) & 1), SearchType::Best)
}

/// Returns an iterator over `Match`s by naively searching through the text `haystack`
/// for the pattern `needle`, with extra options.
///
/// Only matches with less than `k` mismatches are returned.
/// This is done by naively counting mismatches at every position in `haystack`.
/// The length of `needle` must be less than or equal to the length of `haystack`.
///
/// # Arguments
/// * `needle` - pattern string (slice)
/// * `haystack` - text string (slice)
/// * `k` - number of mismatches allowed
/// * `search_type` - whether to only return the "best" matches with the lowest Hamming distance, or
/// all matches
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::hamming::*;
/// let matches: Vec<Match> = hamming_search_naive_with_opts(b"abc", b"  abd", 1, SearchType::All).collect();
///
/// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
/// ```
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> {
    let needle_len = needle.len();
    let haystack_len = haystack.len();

    if needle_len > haystack_len {
        return Box::new(iter::empty());
    }

    let len = haystack_len + 1 - needle_len;
    let mut curr_k = k;
    let mut i = 0;

    let res = iter::from_fn(move || {
        'outer: while i < len {
            let mut final_res = 0u32;

            for j in 0..needle_len {
                final_res += (needle[j] != haystack[i + j]) as u32;

                // early stop
                if final_res > curr_k {
                    i += 1;
                    continue 'outer;
                }
            }

            match search_type {
                SearchType::Best => curr_k = final_res,
                _ => ()
            }

            i += 1;

            return Some((Match{start: i - 1, end: i + needle_len - 1, k: final_res}, curr_k));
        }

        None
    });

    if search_type == SearchType::Best {
        let mut res_vec = Vec::with_capacity(haystack_len / needle_len);
        res.for_each(|m| {
            res_vec.push(m.0);
            curr_k = m.1;
        });

        return Box::new(res_vec.into_iter().filter(move |m| m.k == curr_k));
    }

    Box::new(res.map(|m| m.0))
}

/// Returns the hamming distance between two strings by efficiently counting mismatches in chunks of 64 bits.
///
/// The length of `a` and `b` must be the same.
/// Both `a` and `b` must be aligned and padded so they can be directly casted to chunks of `u64`.
/// Use `alloc_str` to create aligned and padded strings.
/// This should be faster than `hamming_naive` and maybe even `hamming_words_128`. This should be slower
/// than `hamming_simd_parallel/movemask`.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
///
/// # Panics
/// * If the length of `a` does not equal the length of `b`.
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::hamming::*;
/// let mut a = alloc_str(3);
/// let mut b = alloc_str(3);
/// fill_str(&mut a, b"abc");
/// fill_str(&mut b, b"abd");
///
/// let dist = hamming_words_64(&a, &b);
///
/// assert!(dist == 1);
/// ```
pub fn hamming_words_64(a: &[u8], b: &[u8]) -> u32 {
    assert!(a.len() == b.len());

    unsafe {
        let mut res = 0u32;
        // the pointer address better be aligned for u64
        // may not be in little endian
        let a_ptr = a.as_ptr() as *const u64;
        let b_ptr = b.as_ptr() as *const u64;
        let words_len = (a.len() >> 3) as isize;

        for i in 0..words_len {
            // change to little endian omitted because it is not necessary in this case
            let mut r = (*a_ptr.offset(i)) ^ (*b_ptr.offset(i));
            // reduce or by "folding" one half of each byte onto the other multiple times
            r |= r >> 4;
            // ...00001111
            r &= 0x0f0f0f0f0f0f0f0fu64;
            r |= r >> 2;
            // ...00110011
            r &= 0x3333333333333333u64;
            r |= r >> 1;
            // ...01010101
            r &= 0x5555555555555555u64;
            res += r.count_ones();
        }

        let words_rem = a.len() & 7;

        if words_rem > 0 {
            let mut r = (*a_ptr.offset(words_len)) ^ (*b_ptr.offset(words_len));
            r |= r >> 4;
            r &= 0x0f0f0f0f0f0f0f0fu64;
            r |= r >> 2;
            r &= 0x3333333333333333u64;
            r |= r >> 1;
            r &= 0x5555555555555555u64;
            // make sure to mask out bits outside the string lengths
            res += (r & ((1u64 << ((words_rem as u64) << 3u64)) - 1u64)).count_ones();
        }

        res
    }
}

/// Returns the hamming distance between two strings by counting mismatches in chunks of 128 bits.
///
/// The length of `a` and `b` must be the same.
/// Both `a` and `b` must be aligned and padded so they can be directly casted to chunks of `u128`.
/// Use `alloc_str` to create aligned and padded strings.
/// This may be slower than `hamming_words_64` in practice, probably since Rust `u128` is not as
/// optimized. This should be slower than `hamming_simd_parallel/movemask`.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
///
/// # Panics
/// * If the length of `a` does not equal the length of `b`.
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::hamming::*;
/// let mut a = alloc_str(3);
/// let mut b = alloc_str(3);
/// fill_str(&mut a, b"abc");
/// fill_str(&mut b, b"abd");
///
/// let dist = hamming_words_128(&a, &b);
///
/// assert!(dist == 1);
/// ```
pub fn hamming_words_128(a: &[u8], b: &[u8]) -> u32 {
    assert!(a.len() == b.len());

    unsafe {
        let mut res = 0u32;
        // the pointer address better be aligned for u128
        // may not be in little endian
        let a_ptr = a.as_ptr() as *const u128;
        let b_ptr = b.as_ptr() as *const u128;
        let words_len = (a.len() >> 4) as isize;

        for i in 0..words_len {
            // change to little endian omitted because it is not necessary in this case
            let mut r = (*a_ptr.offset(i)) ^ (*b_ptr.offset(i));
            // reduce or by "folding" one half of each byte onto the other multiple times
            r |= r >> 4;
            // ...00001111
            r &= 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0fu128;
            r |= r >> 2;
            // ...00110011
            r &= 0x33333333333333333333333333333333u128;
            r |= r >> 1;
            // ...01010101
            r &= 0x55555555555555555555555555555555u128;
            res += r.count_ones();
        }

        let words_rem = a.len() & 15;

        if words_rem > 0 {
            let mut r = (*a_ptr.offset(words_len)) ^ (*b_ptr.offset(words_len));
            r |= r >> 4;
            r &= 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0fu128;
            r |= r >> 2;
            r &= 0x33333333333333333333333333333333u128;
            r |= r >> 1;
            r &= 0x55555555555555555555555555555555u128;
            // make sure to mask out bits outside the string lengths
            res += (r & ((1u128 << ((words_rem as u128) << 3u128)) - 1u128)).count_ones();
        }

        res
    }
}

/// Returns the hamming distance between two strings by counting mismatches using SIMD vectors to
/// increment multiple counters in parallel.
///
/// The length of `a` and `b` must be the same.
/// There are no constraints on how `a` and `b` are aligned and padded.
/// This will automatically fall back to `hamming_naive`, if AVX2 and SSE4.1 are not supported.
/// This should be faster than both `hamming_word_64/128` and `hamming_simd_movemask`.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
///
/// # Panics
/// * If the length of `a` does not equal the length of `b`.
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::hamming::*;
/// let dist = hamming_simd_parallel(b"abc", b"abd");
///
/// assert!(dist == 1);
/// ```
pub fn hamming_simd_parallel(a: &[u8], b: &[u8]) -> u32 {
    assert!(a.len() == b.len());

    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        if cfg!(feature = "jewel-avx") && is_x86_feature_detected!("avx2") {
            return unsafe {Avx::count_mismatches(a.as_ptr(), b.as_ptr(), a.len())};
        }else if cfg!(feature = "jewel-sse") && is_x86_feature_detected!("sse4.1") {
            return unsafe {Sse::count_mismatches(a.as_ptr(), b.as_ptr(), a.len())};
        }
    }

    hamming_naive(a, b)
}

/// Returns the hamming distance between two strings by counting mismatches using the SIMD movemask intrinsic.
///
/// The length of `a` and `b` must be the same.
/// There are no constraints on how `a` and `b` are aligned and padded.
/// This will automatically fall back to `hamming_naive`, if AVX2 and SSE4.1 are not supported.
/// This should be faster than `hamming_word_64/128`, but slower than `hamming_simd_parallel`.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
///
/// # Panics
/// * If the length of `a` does not equal the length of `b`.
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::hamming::*;
/// let dist = hamming_simd_movemask(b"abc", b"abd");
///
/// assert!(dist == 1);
/// ```
pub fn hamming_simd_movemask(a: &[u8], b: &[u8]) -> u32 {
    assert!(a.len() == b.len());

    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        if cfg!(feature = "jewel-avx") && is_x86_feature_detected!("avx2") {
            return unsafe {Avx::mm_count_mismatches(a.as_ptr(), b.as_ptr(), a.len())};
        }else if cfg!(feature = "jewel-sse") && is_x86_feature_detected!("sse4.1") {
            return unsafe {Sse::mm_count_mismatches(a.as_ptr(), b.as_ptr(), a.len())};
        }
    }

    hamming_naive(a, b)
}

/// Returns the hamming distance between two strings using the best method.
///
/// The length of `a` and `b` must be the same.
/// This will automatically fall back to a scalar alternative if AVX2 and
/// SSE4.1 are not supported.
/// Internally, this calls `hamming_simd_parallel`.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
///
/// # Panics
/// * If the length of `a` does not equal the length of `b`.
///
/// # Example
/// ```
/// # use triple_accel::*;
/// let dist = hamming(b"abc", b"abd");
///
/// assert!(dist == 1);
/// ```
pub fn hamming(a: &[u8], b: &[u8]) -> u32 {
    hamming_simd_parallel(a, b)
}

/// Returns an iterator over best `Match`s by searching through the text `haystack`
/// for the pattern `needle` using SIMD.
///
/// This is done by counting mismatches at every position in `haystack`.
/// This will automatically fall back to `hamming_search_naive_with_opts` if AVX2 and SSE4.1
/// are not supported.
/// Null bytes/characters are not supported.
/// The length of `needle` must be less than or equal to the length of `haystack`.
/// Each returned `Match` requires at least half or more bytes of the `needle` to match
/// somwhere in the `haystack`.
/// Only the matches with the lowest Hamming distance are returned.
/// This should be faster than `hamming_search_naive`.
///
/// # Arguments
/// * `needle` - pattern string (slice)
/// * `haystack` - text string (slice)
///
/// # Panics
/// * When there are zero/null bytes in the `haystack` string.
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::hamming::*;
/// let matches: Vec<Match> = hamming_search_simd(b"abc", b"  abd").collect();
///
/// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
/// ```
pub fn hamming_search_simd<'a>(needle: &'a [u8], haystack: &'a [u8]) -> Box<dyn Iterator<Item = Match> + 'a> {
    hamming_search_simd_with_opts(needle, haystack, ((needle.len() as u32) >> 1) + ((needle.len() as u32) & 1), SearchType::Best)
}

/// Returns an iterator over `Match`s by searching through the text `haystack` for the
/// pattern `needle` using SIMD, with extra options.
///
/// This is done by using SIMD to count mismatches at every position in `haystack`.
/// This will automatically fall back to `hamming_search_naive_with_opts` if AVX2 and SSE4.1
/// are not supported.
/// Null bytes/characters are not supported.
/// The length of `needle` must be less than or equal to the length of `haystack`.
/// This should be faster than `hamming_search_naive_with_opts`.
///
/// # Arguments
/// * `needle` - pattern string (slice)
/// * `haystack` - text string (slice)
/// * `k` - number of mismatches allowed
/// * `search_type` - whether to only return the "best" matches with the lowest Hamming distance, or
/// all matches
///
/// # Panics
/// * When there are zero/null bytes in the `haystack` string.
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::hamming::*;
/// let matches: Vec<Match> = hamming_search_simd_with_opts(b"abc", b"  abd", 1, SearchType::All).collect();
///
/// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
/// ```
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> {
    if needle.len() > haystack.len() {
        return Box::new(iter::empty());
    }

    if needle.len() == 0 {
        return Box::new(iter::empty());
    }

    check_no_null_bytes(haystack);

    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        if cfg!(feature = "jewel-avx") && is_x86_feature_detected!("avx2") {
            return unsafe {hamming_search_simd_core_avx(needle, haystack, k, search_type)};
        }else if cfg!(feature = "jewel-sse") && is_x86_feature_detected!("sse4.1") {
            return unsafe {hamming_search_simd_core_sse(needle, haystack, k, search_type)};
        }
    }

    hamming_search_naive_with_opts(needle, haystack, k, search_type)
}

macro_rules! create_hamming_search_simd_core {
    ($name:ident, $jewel:ty, $target:literal) => {
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        #[target_feature(enable = $target)]
        unsafe fn $name<'a>(needle: &'a [u8], haystack: &'a [u8], k: u32, search_type: SearchType) -> Box<dyn Iterator<Item = Match> + 'a> {
            #[cfg(feature = "debug")]
            {
                println!("Debug: Hamming search Jewel vector type {} for target {}.", stringify!($jewel), stringify!($target));
            }

            let needle_len = needle.len();
            let haystack_len = haystack.len();
            let needle_vector = <$jewel>::loadu(needle.as_ptr(), needle_len);
            // calculate len using the unused bytes in the needle Jewel vector, for speed
            // there may be leftover positions in haystack that need to be calculated using a
            // scalar search afterwards
            // there should be no null bytes in the strings
            let len = if needle_vector.upper_bound() > haystack_len {0} else {haystack_len + 1 - needle_vector.upper_bound()};
            let real_len = haystack_len + 1 - needle_len;
            let haystack_ptr = haystack.as_ptr();
            let mut curr_k = k;
            let mut i = 0;

            let res = iter::from_fn(move || {
                while i < len {
                    let final_res = <$jewel>::vector_count_mismatches(&needle_vector, haystack_ptr.offset(i as isize), needle_len);
                    i += 1;

                    if final_res <= curr_k {
                        match search_type {
                            SearchType::Best => curr_k = final_res,
                            _ => ()
                        }

                        return Some((Match{start: i - 1, end: i + needle_len - 1, k: final_res}, curr_k));
                    }
                }

                // scalar search
                'outer: while i < real_len {
                    let mut final_res = 0u32;

                    for j in 0..needle_len {
                        final_res += (*needle.get_unchecked(j) != *haystack.get_unchecked(i + j)) as u32;

                        if final_res > curr_k {
                            i += 1;
                            continue 'outer;
                        }
                    }

                    match search_type {
                        SearchType::Best => curr_k = final_res,
                        _ => ()
                    }

                    i += 1;

                    return Some((Match{start: i - 1, end: i + needle_len - 1, k: final_res}, curr_k));
                }

                None
            });

            if search_type == SearchType::Best {
                let mut res_vec = Vec::with_capacity(haystack_len / needle_len);
                res.for_each(|m| {
                    res_vec.push(m.0);
                    curr_k = m.1;
                });

                return Box::new(res_vec.into_iter().filter(move |m| m.k == curr_k));
            }

            Box::new(res.map(|m| m.0))
        }
    };
}

// generate different versions for different intrinsics
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_hamming_search_simd_core!(hamming_search_simd_core_avx, Avx, "avx2");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_hamming_search_simd_core!(hamming_search_simd_core_sse, Sse, "sse4.1");

/// Returns an iterator over best `Match`s by searching through the text `haystack`
/// for the pattern `needle` using SIMD.
///
/// This will automatically fall back to a scalar alternative if AVX2 and SSE4.1
/// are not supported.
/// Null bytes/characters are not supported.
/// The length of `needle` must be less than or equal to the length of `haystack`.
/// Each returned `Match` requires at least half or more bytes of the `needle` to match
/// somewhere in the `haystack`.
/// Only the matches with the lowest Hamming distance are returned.
/// Internally, this calls `hamming_search_simd`.
///
/// # Arguments
/// * `needle` - pattern string (slice)
/// * `haystack` - text string (slice)
///
/// # Panics
/// * When there are zero/null bytes in the `haystack` string.
///
/// # Example
/// ```
/// # use triple_accel::*;
/// let matches: Vec<Match> = hamming_search(b"abc", b"  abd").collect();
///
/// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
/// ```
pub fn hamming_search<'a>(needle: &'a [u8], haystack: &'a [u8]) -> Box<dyn Iterator<Item = Match> + 'a> {
    hamming_search_simd(needle, haystack)
}