#![allow(unsafe_op_in_unsafe_fn)]
use core::arch::x86_64::*;
#[target_feature(enable = "avx2,popcnt")]
#[inline]
pub(crate) unsafe fn hamming_popcnt(a: &[u64], b: &[u64]) -> u32 {
debug_assert_eq!(a.len(), b.len());
let mut h: u64 = 0;
for w in 0..a.len() {
h += _popcnt64((a[w] ^ b[w]) as i64) as u64;
}
h as u32
}
#[target_feature(enable = "avx2,popcnt")]
#[inline]
pub(crate) unsafe fn hamming_shuffle(a: &[u64], b: &[u64]) -> u32 {
debug_assert_eq!(a.len(), b.len());
let nb = a.len() * 8;
let pa = a.as_ptr() as *const u8;
let pb = b.as_ptr() as *const u8;
let nibble_lut = _mm256_setr_epi8(
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3,
3, 4,
);
let mask_lo = _mm256_set1_epi8(0x0F);
let mut acc = _mm256_setzero_si256();
let mut i = 0usize;
while i + 32 <= nb {
let av = _mm256_loadu_si256(pa.add(i) as *const __m256i);
let bv = _mm256_loadu_si256(pb.add(i) as *const __m256i);
let x = _mm256_xor_si256(av, bv);
let lo = _mm256_and_si256(x, mask_lo);
let hi = _mm256_and_si256(_mm256_srli_epi16(x, 4), mask_lo);
let pop_lo = _mm256_shuffle_epi8(nibble_lut, lo);
let pop_hi = _mm256_shuffle_epi8(nibble_lut, hi);
let bytes = _mm256_add_epi8(pop_lo, pop_hi);
let sums = _mm256_sad_epu8(bytes, _mm256_setzero_si256());
acc = _mm256_add_epi64(acc, sums);
i += 32;
}
let mut lanes = [0u64; 4];
_mm256_storeu_si256(lanes.as_mut_ptr() as *mut __m256i, acc);
let mut h = lanes[0] + lanes[1] + lanes[2] + lanes[3];
while i < nb {
h += _popcnt64((*pa.add(i) ^ *pb.add(i)) as i64) as u64;
i += 1;
}
h as u32
}