use super::lazy::Searcher;
use super::seq_store::{
PRIME4BYTES, PRIME5BYTES, PRIME6BYTES, REP_NUM, count, read_le32, read_le64, read32,
};
use crate::cpu::prefetch_l1;
pub(crate) const ROW_HASH_CACHE_SIZE: usize = 8;
const ROW_HASH_CACHE_MASK: u32 = ROW_HASH_CACHE_SIZE as u32 - 1;
pub(crate) const ROW_HASH_TAG_BITS: u32 = 8;
const ROW_HASH_MAX_ENTRIES: usize = 64;
struct MatchBuffer([core::mem::MaybeUninit<u32>; ROW_HASH_MAX_ENTRIES]);
impl MatchBuffer {
#[inline(always)]
fn new() -> Self {
MatchBuffer([core::mem::MaybeUninit::uninit(); ROW_HASH_MAX_ENTRIES])
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn set(&mut self, i: usize, v: u32) {
debug_assert!(i < ROW_HASH_MAX_ENTRIES);
unsafe { self.0.get_unchecked_mut(i).write(v) };
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn first(&self, len: usize) -> &[u32] {
debug_assert!(len <= ROW_HASH_MAX_ENTRIES);
unsafe { core::slice::from_raw_parts(self.0.as_ptr().cast::<u32>(), len) }
}
}
#[allow(unsafe_code)]
#[inline(always)]
pub(crate) unsafe fn hash_salted<const MLS: u32>(p: *const u8, h_bits: u32, salt: u64) -> u32 {
debug_assert!(h_bits <= 32 && h_bits > 0);
unsafe {
match MLS {
5 => {
((((read_le64(p) << (64 - 40)).wrapping_mul(PRIME5BYTES)) ^ salt) >> (64 - h_bits))
as u32
}
6 => {
((((read_le64(p) << (64 - 48)).wrapping_mul(PRIME6BYTES)) ^ salt) >> (64 - h_bits))
as u32
}
_ => ((read_le32(p).wrapping_mul(PRIME4BYTES)) ^ salt as u32) >> (32 - h_bits),
}
}
}
#[inline(always)]
fn next_index(head: u32, row_mask: u32) -> u32 {
let next = head.wrapping_sub(1) & row_mask;
next + if next == 0 { row_mask } else { 0 } }
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn count_short(p_in: *const u8, p_match: *const u8, p_in_limit: *const u8) -> usize {
unsafe {
if (p_in_limit as usize).saturating_sub(p_in as usize) >= 16 {
let d0 = read_le64(p_match) ^ read_le64(p_in);
let d1 = read_le64(p_match.add(8)) ^ read_le64(p_in.add(8));
if d0 | d1 != 0 {
let (m, base) = if d0 != 0 { (d0, 0) } else { (d1, 8) };
return base + ((m | 1 << 63).trailing_zeros() >> 3) as usize;
}
return 16 + count(p_in.add(16), p_match.add(16), p_in_limit);
}
count(p_in, p_match, p_in_limit)
}
}
#[inline(always)]
fn row_prefetch<const ROW_LOG: u32>(hash_table: *const u32, tag_table: *const u8, rel_row: u32) {
let rel_row = rel_row as usize;
prefetch_l1(hash_table.wrapping_add(rel_row).cast());
if ROW_LOG >= 5 {
prefetch_l1(hash_table.wrapping_add(rel_row + 16).cast());
}
prefetch_l1(tag_table.wrapping_add(rel_row));
if ROW_LOG == 6 {
prefetch_l1(tag_table.wrapping_add(rel_row + 32));
}
}
#[allow(unsafe_code)]
#[inline(always)]
pub(super) unsafe fn fill_hash_cache<const MLS: u32, const ROW_LOG: u32>(
s: &mut Searcher,
idx: u32,
ilimit: *const u8,
) {
let p = s.pos(idx) as usize;
let max_elems_to_prefetch = if p > ilimit as usize {
0
} else {
ilimit as usize - p + 1
};
let lim = idx + ROW_HASH_CACHE_SIZE.min(max_elems_to_prefetch) as u32;
for i in idx..lim {
let p = s.pos(i);
s.chk(p, 8);
let hash =
unsafe { hash_salted::<MLS>(p, s.row_hash_log + ROW_HASH_TAG_BITS, s.hash_salt) };
let row = (hash >> ROW_HASH_TAG_BITS) << ROW_LOG;
row_prefetch::<ROW_LOG>(s.hash_table, s.tag_table, row);
s.hash_cache[(i & ROW_HASH_CACHE_MASK) as usize] = hash;
}
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn next_cached_hash<const MLS: u32, const ROW_LOG: u32>(s: &mut Searcher, idx: u32) -> u32 {
let p = s.pos(idx).wrapping_add(ROW_HASH_CACHE_SIZE);
s.chk(p, 8);
let new_hash =
unsafe { hash_salted::<MLS>(p, s.row_hash_log + ROW_HASH_TAG_BITS, s.hash_salt) };
let row = (new_hash >> ROW_HASH_TAG_BITS) << ROW_LOG;
row_prefetch::<ROW_LOG>(s.hash_table, s.tag_table, row);
let slot = &mut s.hash_cache[(idx & ROW_HASH_CACHE_MASK) as usize];
let hash = *slot;
*slot = new_hash;
hash
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn update_internal_impl<const MLS: u32, const ROW_LOG: u32>(
s: &mut Searcher,
start: u32,
end: u32,
) {
let row_mask = (1u32 << ROW_LOG) - 1;
if start >= end {
return;
}
unsafe {
let mut hash = next_cached_hash::<MLS, ROW_LOG>(s, start);
let mut rel_row = ((hash >> ROW_HASH_TAG_BITS) << ROW_LOG) as usize;
let mut head = u32::from(*s.tag_table.add(rel_row));
let mut idx = start;
loop {
debug_assert_eq!(
hash,
hash_salted::<MLS>(s.pos(idx), s.row_hash_log + ROW_HASH_TAG_BITS, s.hash_salt)
);
let tag_row = s.tag_table.add(rel_row);
let pos = next_index(head, row_mask);
let next = idx + 1;
if next == end {
*tag_row = pos as u8;
*tag_row.add(pos as usize) = hash as u8;
*s.hash_table.add(rel_row + pos as usize) = idx;
break;
}
let next_hash = next_cached_hash::<MLS, ROW_LOG>(s, next);
let next_row = ((next_hash >> ROW_HASH_TAG_BITS) << ROW_LOG) as usize;
let next_head = u32::from(*s.tag_table.add(next_row));
*tag_row = pos as u8;
*tag_row.add(pos as usize) = hash as u8;
*s.hash_table.add(rel_row + pos as usize) = idx;
head = if next_row == rel_row { pos } else { next_head };
debug_assert_eq!(u32::from(*s.tag_table.add(next_row)), head);
hash = next_hash;
rel_row = next_row;
idx = next;
}
}
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn update_internal<const MLS: u32, const ROW_LOG: u32>(s: &mut Searcher, ip: *const u8) {
const SKIP_THRESHOLD: u32 = 384;
const MAX_MATCH_START_POSITIONS_TO_UPDATE: u32 = 96;
const MAX_MATCH_END_POSITIONS_TO_UPDATE: u32 = 32;
let mut idx = s.next_to_update;
let target = s.idx(ip);
debug_assert!(target >= idx);
unsafe {
if target - idx > SKIP_THRESHOLD {
let bound = idx + MAX_MATCH_START_POSITIONS_TO_UPDATE;
update_internal_impl::<MLS, ROW_LOG>(s, idx, bound);
idx = target - MAX_MATCH_END_POSITIONS_TO_UPDATE;
fill_hash_cache::<MLS, ROW_LOG>(s, idx, ip.wrapping_add(1));
}
update_internal_impl::<MLS, ROW_LOG>(s, idx, target);
}
s.next_to_update = target;
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn match_mask<const ROW_LOG: u32>(tag_row: *const u8, tag: u8, head: u32) -> u64 {
let matches = !1
& unsafe {
#[cfg(all(target_arch = "x86_64", not(feature = "portable")))]
{
match_bits_sse2::<ROW_LOG>(tag_row, tag)
}
#[cfg(not(all(target_arch = "x86_64", not(feature = "portable"))))]
{
match_bits_swar::<ROW_LOG>(tag_row, tag)
}
};
match ROW_LOG {
4 => u64::from((matches as u16).rotate_right(head)),
5 => u64::from((matches as u32).rotate_right(head)),
_ => matches.rotate_right(head),
}
}
#[cfg(target_arch = "x86_64")]
#[allow(unsafe_code, unused_unsafe)]
#[inline(always)]
unsafe fn match_bits_sse2<const ROW_LOG: u32>(tag_row: *const u8, tag: u8) -> u64 {
use core::arch::x86_64::{
__m128i, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8, _mm_set1_epi8,
};
let nb_chunks = 1usize << (ROW_LOG - 4);
let mut matches = 0u64;
unsafe {
let comparison_mask = _mm_set1_epi8(tag as i8);
for i in 0..nb_chunks {
let chunk = _mm_loadu_si128(tag_row.add(16 * i).cast::<__m128i>());
let equal_mask = _mm_cmpeq_epi8(chunk, comparison_mask);
matches |= u64::from(_mm_movemask_epi8(equal_mask) as u16) << (16 * i);
}
}
matches
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn match_bits_swar<const ROW_LOG: u32>(tag_row: *const u8, tag: u8) -> u64 {
const X01: u64 = u64::MAX / 0xFF;
const X80: u64 = X01 << 7;
const EXTRACT_MAGIC: u64 = (u64::MAX / 0x7F) >> 8;
let splat_char = u64::from(tag).wrapping_mul(X01);
let mut matches = 0u64;
let mut i = (1usize << ROW_LOG) - 8;
loop {
let mut chunk = unsafe { read_le64(tag_row.add(i)) } ^ splat_char;
chunk = (((chunk | X80).wrapping_sub(X01)) | chunk) & X80;
matches <<= 8;
matches |= chunk.wrapping_mul(EXTRACT_MAGIC) >> 56;
if i == 0 {
break;
}
i -= 8;
}
!matches
}
#[allow(unsafe_code)]
#[inline(always)]
pub(super) unsafe fn row_find_best_match<
const MLS: u32,
const ROW_LOG: u32,
const EXT: bool,
const DMS: bool,
>(
s: &mut Searcher,
ip: *const u8,
ilimit: *const u8,
offset_ptr: &mut u32,
) -> usize {
let row_entries = 1u32 << ROW_LOG;
let row_mask = row_entries - 1;
let curr = s.idx(ip);
let low_limit = s.lowest_match_index(curr);
let capped_search_log = s.search_log.min(ROW_LOG);
let mut nb_attempts = 1u32 << capped_search_log;
let mut ml = 4 - 1;
unsafe {
let (dms_tag, dms_rel_row) = if DMS {
s.chk(ip, 8);
let d = s.dms;
let dms_hash = hash_salted::<MLS>(ip, d.row_hash_log + ROW_HASH_TAG_BITS, 0);
let dms_rel_row = (dms_hash >> ROW_HASH_TAG_BITS) << ROW_LOG;
row_prefetch::<ROW_LOG>(d.hash_table, d.tag_table, dms_rel_row);
(dms_hash as u8, dms_rel_row as usize)
} else {
(0, 0)
};
let hash = if !s.lazy_skipping {
update_internal::<MLS, ROW_LOG>(s, ip);
next_cached_hash::<MLS, ROW_LOG>(s, curr)
} else {
s.chk(ip, 8);
let h = hash_salted::<MLS>(ip, s.row_hash_log + ROW_HASH_TAG_BITS, s.hash_salt);
s.next_to_update = curr;
h
};
s.hash_salt_entropy = s.hash_salt_entropy.wrapping_add(hash);
let rel_row = ((hash >> ROW_HASH_TAG_BITS) << ROW_LOG) as usize;
let tag = hash as u8;
let row = s.hash_table.add(rel_row);
let tag_row = s.tag_table.add(rel_row);
let head = u32::from(*tag_row) & row_mask;
let mut match_buffer = MatchBuffer::new();
let mut num_matches = 0;
let mut matches = match_mask::<ROW_LOG>(tag_row, tag, head);
while matches > 0 && nb_attempts > 0 {
let match_pos = (head as usize + matches.trailing_zeros() as usize) & row_mask as usize;
debug_assert!(match_pos != 0);
let match_index = *row.add(match_pos);
if match_index < low_limit {
break;
}
if EXT {
prefetch_l1(s.ext_pos(match_index));
} else {
prefetch_l1(s.pos(match_index));
}
match_buffer.set(num_matches, match_index);
num_matches += 1;
nb_attempts -= 1;
matches &= matches - 1;
}
{
debug_assert_eq!(u32::from(*tag_row) & row_mask, head);
let pos = next_index(head, row_mask) as usize;
*tag_row = pos as u8;
*tag_row.add(pos) = tag;
*row.add(pos) = s.next_to_update;
s.next_to_update += 1;
}
for &match_index in match_buffer.first(num_matches) {
let mut current_ml = 0;
debug_assert!(match_index < curr && match_index >= low_limit);
if !EXT || match_index >= s.dict_limit {
let m = s.pos(match_index);
s.chk(m.wrapping_add(ml - 3), 4);
if read32(m.add(ml - 3)) == read32(ip.add(ml - 3)) {
current_ml = count_short(ip, m, ilimit);
}
} else {
let m = s.dict_base.wrapping_add(match_index as usize);
s.chk(m, 4);
if read32(m) == read32(ip) {
current_ml = s.count_ext(ip.add(4), m.add(4), ilimit) + 4;
}
}
if current_ml > ml {
ml = current_ml;
*offset_ptr = curr - match_index + REP_NUM;
if ip.add(current_ml) == ilimit {
break; }
}
}
if DMS {
let d = s.dms;
let dms_lowest_index = d.dict_limit;
let dms_base = s.dict_base;
let dms_index_delta = s.dict_limit - d.high_limit;
let dms_row = d.hash_table.add(dms_rel_row);
let dms_tag_row = d.tag_table.add(dms_rel_row);
let head = u32::from(*dms_tag_row) & row_mask;
let mut match_buffer = MatchBuffer::new();
let mut num_matches = 0;
let mut matches = match_mask::<ROW_LOG>(dms_tag_row, dms_tag, head);
while matches > 0 && nb_attempts > 0 {
let match_pos =
(head as usize + matches.trailing_zeros() as usize) & row_mask as usize;
debug_assert!(match_pos != 0);
let match_index = *dms_row.add(match_pos);
if match_index < dms_lowest_index {
break;
}
prefetch_l1(dms_base.wrapping_add(match_index as usize));
match_buffer.set(num_matches, match_index);
num_matches += 1;
nb_attempts -= 1;
matches &= matches - 1;
}
for &match_index in match_buffer.first(num_matches) {
let mut current_ml = 0;
debug_assert!(match_index >= dms_lowest_index);
let m = dms_base.wrapping_add(match_index as usize);
s.chk(m, 4);
if read32(m) == read32(ip) {
current_ml = s.count_ext(ip.add(4), m.add(4), ilimit) + 4;
}
if current_ml > ml {
ml = current_ml;
debug_assert!(curr > match_index + dms_index_delta);
*offset_ptr = curr - (match_index + dms_index_delta) + REP_NUM;
if ip.add(current_ml) == ilimit {
break;
}
}
}
}
}
ml
}
#[cfg(test)]
mod tests {
use super::*;
fn naive_bits(row: &[u8], tag: u8) -> u64 {
row.iter()
.enumerate()
.filter(|&(_, &b)| b == tag)
.fold(0, |m, (i, _)| m | 1 << i)
}
#[test]
#[allow(unsafe_code)]
fn match_masks() {
let mut s = 0x1234_5678_9abc_def1u64;
for round in 0..2000 {
let mut row = [0u8; 64];
for b in &mut row {
s ^= s << 13;
s ^= s >> 7;
s ^= s << 17;
*b = (s >> 40) as u8 % if round % 2 == 0 { 4 } else { 255 };
}
let tag = row[round % 64];
let head = (round as u32 * 7) % 64;
unsafe {
let p = row.as_ptr();
let n16 = naive_bits(&row[..16], tag);
let n32 = naive_bits(&row[..32], tag);
let n64 = naive_bits(&row, tag);
assert_eq!(match_bits_swar::<4>(p, tag) & 0xFFFF, n16);
assert_eq!(match_bits_swar::<5>(p, tag) & 0xFFFF_FFFF, n32);
assert_eq!(match_bits_swar::<6>(p, tag), n64);
#[cfg(target_arch = "x86_64")]
{
assert_eq!(match_bits_sse2::<4>(p, tag), n16);
assert_eq!(match_bits_sse2::<5>(p, tag), n32);
assert_eq!(match_bits_sse2::<6>(p, tag), n64);
}
let h = head % 16;
assert_eq!(
match_mask::<4>(p, tag, h),
u64::from((n16 as u16 & !1).rotate_right(h))
);
assert_eq!(
match_mask::<5>(p, tag, head % 32),
u64::from((n32 as u32 & !1).rotate_right(head % 32))
);
assert_eq!(match_mask::<6>(p, tag, head), (n64 & !1).rotate_right(head));
}
}
}
#[test]
fn next_index_cycles() {
let mut head = 0u8;
let mut seen = alloc::vec::Vec::new();
for _ in 0..31 {
let next = next_index(u32::from(head), 15);
assert_eq!(next_index(u32::from(head) | 0xF0, 15), next);
head = next as u8;
seen.push(next);
}
let want: alloc::vec::Vec<u32> = (1..=15).rev().cycle().take(31).collect();
assert_eq!(seen, want);
}
#[test]
#[allow(unsafe_code)]
fn count_short_matches_count() {
let step = if cfg!(miri) { 7 } else { 1 };
let a: alloc::vec::Vec<u8> = (0..48u8).map(|i| i.wrapping_mul(37)).collect();
for diff in (0..=40).step_by(step) {
let mut b = a.clone();
if diff < 40 {
b[diff] ^= 0x10;
}
for len in (0..=40).step_by(step) {
let (pi, pm) = (a.as_ptr(), b.as_ptr());
let (got, want) =
unsafe { (count_short(pi, pm, pi.add(len)), count(pi, pm, pi.add(len))) };
assert_eq!(got, want, "diff {diff}, len {len}");
assert_eq!(want, diff.min(len));
}
}
}
}