use super::params::{
CParams, ParamSwitch, Strategy, cycle_log, resolve_row_match_finder_mode, row_match_finder_used,
};
use super::seq_store::{
REPCODE1_TO_OFFBASE, SeqStore, count, count_2segments, hash4_ptr, hash5_ptr, hash6_ptr,
hash7_ptr, hash8_ptr, offset_to_offbase, read_le64, read32,
};
use crate::cpu::prefetch_l1;
pub(crate) const WINDOW_START_INDEX: u32 = 2;
pub(crate) const HASH_READ_SIZE: usize = 8;
pub(crate) const K_SEARCH_STRENGTH: u32 = 8;
pub(crate) const CURRENT_MAX: u32 = if usize::BITS == 64 {
3500 << 20
} else {
2000 << 20
};
pub(crate) const INDEXOVERFLOW_MARGIN: u32 = 16 << 20;
pub(crate) const HASHLOG3_MAX: u32 = 17;
pub(crate) const CHUNKSIZE_MAX: u32 = u32::MAX - CURRENT_MAX;
pub(crate) const MIN_SEQ_STORE_BLOCK: usize = 2 + 3 + 1 + 1;
const INIT_BASE: usize = usize::MAX - 15;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Window {
pub(crate) next_src: usize,
pub(crate) base: usize,
pub(crate) dict_base: usize,
pub(crate) dict_limit: u32,
pub(crate) low_limit: u32,
pub(crate) nb_overflow_corrections: u32,
pub(crate) base_in_dict: bool,
pub(crate) dict_base_in_dict: bool,
}
impl Window {
pub(crate) fn new() -> Self {
Self {
next_src: INIT_BASE + WINDOW_START_INDEX as usize,
base: INIT_BASE,
dict_base: INIT_BASE,
dict_limit: WINDOW_START_INDEX,
low_limit: WINDOW_START_INDEX,
nb_overflow_corrections: 0,
base_in_dict: false,
dict_base_in_dict: false,
}
}
#[inline(always)]
pub(crate) fn index(&self, pos: usize) -> u32 {
pos.wrapping_sub(self.base) as u32
}
#[inline(always)]
pub(crate) fn pos(&self, idx: u32) -> usize {
self.base.wrapping_add(idx as usize)
}
pub(crate) fn clear(&mut self) {
let end = self.next_src.wrapping_sub(self.base) as u32;
self.low_limit = end;
self.dict_limit = end;
}
pub(crate) fn is_empty(&self) -> bool {
self.dict_limit == WINDOW_START_INDEX
&& self.low_limit == WINDOW_START_INDEX
&& self.next_src.wrapping_sub(self.base) == WINDOW_START_INDEX as usize
}
pub(crate) fn has_ext_dict(&self) -> bool {
self.low_limit < self.dict_limit
}
pub(crate) fn update(
&mut self,
src: usize,
src_size: usize,
force_non_contiguous: bool,
) -> bool {
let mut contiguous = true;
if src_size == 0 {
return contiguous;
}
if src != self.next_src || force_non_contiguous || self.base_in_dict {
let distance_from_base = self.next_src.wrapping_sub(self.base);
self.low_limit = self.dict_limit;
debug_assert!(distance_from_base == distance_from_base as u32 as usize);
self.dict_limit = distance_from_base as u32;
self.dict_base = self.base;
self.dict_base_in_dict = self.base_in_dict;
self.base_in_dict = false;
self.base = src.wrapping_sub(distance_from_base);
if self.dict_limit - self.low_limit < HASH_READ_SIZE as u32 {
self.low_limit = self.dict_limit; }
contiguous = false;
}
self.next_src = src.wrapping_add(src_size);
let src_end = src.wrapping_add(src_size);
if !self.dict_base_in_dict
&& (src_end > self.dict_base.wrapping_add(self.low_limit as usize))
& (src < self.dict_base.wrapping_add(self.dict_limit as usize))
{
let high_input_idx = src_end.wrapping_sub(self.dict_base);
let low_limit_max = if high_input_idx > self.dict_limit as usize {
self.dict_limit
} else {
high_input_idx as u32
};
self.low_limit = low_limit_max;
}
contiguous
}
pub(crate) fn need_overflow_correction(&self, src_end: usize) -> bool {
let curr = src_end.wrapping_sub(self.base) as u32;
curr > CURRENT_MAX
}
pub(crate) fn correct_overflow(&mut self, cycle_log: u32, max_dist: u32, src: usize) -> u32 {
let cycle_size = 1u32 << cycle_log;
let cycle_mask = cycle_size - 1;
let curr = src.wrapping_sub(self.base) as u32;
let current_cycle = curr & cycle_mask;
let current_cycle_correction = if current_cycle < WINDOW_START_INDEX {
cycle_size.max(WINDOW_START_INDEX)
} else {
0
};
let new_current = current_cycle + current_cycle_correction + max_dist.max(cycle_size);
let correction = curr - new_current;
debug_assert!(max_dist & max_dist.wrapping_sub(1) == 0);
debug_assert!(curr & cycle_mask == new_current & cycle_mask);
debug_assert!(curr > new_current);
debug_assert!(correction > 1 << 28);
self.base = self.base.wrapping_add(correction as usize);
self.dict_base = self.dict_base.wrapping_add(correction as usize);
if self.low_limit < correction + WINDOW_START_INDEX {
self.low_limit = WINDOW_START_INDEX;
} else {
self.low_limit -= correction;
}
if self.dict_limit < correction + WINDOW_START_INDEX {
self.dict_limit = WINDOW_START_INDEX;
} else {
self.dict_limit -= correction;
}
debug_assert!(new_current >= max_dist);
debug_assert!(new_current - max_dist >= WINDOW_START_INDEX);
debug_assert!(self.low_limit <= new_current);
debug_assert!(self.dict_limit <= new_current);
self.nb_overflow_corrections += 1;
correction
}
pub(crate) fn enforce_max_dist(
&mut self,
block_end: usize,
max_dist: u32,
loaded_dict_end: &mut u32,
dms: &mut bool,
) {
let block_end_idx = block_end.wrapping_sub(self.base) as u32;
if block_end_idx > max_dist.wrapping_add(*loaded_dict_end) {
let new_low_limit = block_end_idx - max_dist;
if self.low_limit < new_low_limit {
self.low_limit = new_low_limit;
}
if self.dict_limit < self.low_limit {
self.dict_limit = self.low_limit;
}
*loaded_dict_end = 0;
*dms = false;
}
}
pub(crate) fn check_dict_validity(
&self,
block_end: usize,
max_dist: u32,
loaded_dict_end: &mut u32,
dms: &mut bool,
) {
let block_end_idx = block_end.wrapping_sub(self.base) as u32;
let lde = *loaded_dict_end;
debug_assert!(block_end_idx >= lde);
if block_end_idx > lde.wrapping_add(max_dist) || lde != self.dict_limit {
*loaded_dict_end = 0;
*dms = false;
}
}
}
impl Default for Window {
fn default() -> Self {
Self::new()
}
}
pub(crate) fn reduce_table(table: &mut [u32], reducer_value: u32) {
let reducer_threshold = reducer_value + WINDOW_START_INDEX;
for v in table {
*v = if *v < reducer_threshold {
0
} else {
*v - reducer_value
};
}
}
pub(crate) fn reduce_table_btlazy2(table: &mut [u32], reducer_value: u32) {
use super::lazy::DUBT_UNSORTED_MARK;
let reducer_threshold = reducer_value + WINDOW_START_INDEX;
for v in table {
*v = if *v == DUBT_UNSORTED_MARK {
DUBT_UNSORTED_MARK
} else if *v < reducer_threshold {
0
} else {
*v - reducer_value
};
}
}
fn bitmix(mut val: u64, len: u64) -> u64 {
const K: u64 = 0x9FB2_1C65_1E98_DF25;
val ^= val.rotate_right(49) ^ val.rotate_right(24);
val = val.wrapping_mul(K);
val ^= (val >> 35).wrapping_add(len);
val = val.wrapping_mul(K);
val ^ (val >> 28)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TableLoadMethod {
Fast,
Full,
}
#[derive(Debug)]
pub(crate) struct MatchState {
pub(crate) window: Window,
pub(crate) loaded_dict_end: u32,
pub(crate) next_to_update: u32,
pub(crate) hash_table: super::table::Table<u32>,
pub(crate) chain_table: super::table::Table<u32>,
pub(crate) cparams: CParams,
pub(crate) force_non_contiguous: bool,
pub(crate) use_row_match_finder: bool,
pub(crate) tag_table: super::table::Table<u8>,
pub(crate) hash_cache: [u32; super::row::ROW_HASH_CACHE_SIZE],
pub(crate) row_hash_log: u32,
pub(crate) hash_salt: u64,
pub(crate) hash_salt_entropy: u32,
pub(crate) lazy_skipping: bool,
pub(crate) hash_log3: u32,
pub(crate) hash_table3: super::table::Table<u32>,
pub(crate) opt: Option<alloc::boxed::Box<super::opt::OptState>>,
pub(crate) dict: Option<alloc::sync::Arc<super::cdict::CDict>>,
pub(crate) dms: bool,
}
impl MatchState {
pub(crate) fn new(cparams: CParams) -> Self {
let mut ms = Self::empty(cparams);
ms.reset(cparams);
ms
}
pub(crate) fn new_with(cparams: CParams, use_row: bool, for_cdict: bool) -> Self {
let mut ms = Self::empty(cparams);
ms.reset_with(cparams, use_row, for_cdict);
ms
}
fn empty(cparams: CParams) -> Self {
Self {
window: Window::new(),
loaded_dict_end: 0,
next_to_update: 0,
hash_table: super::table::Table::new(),
chain_table: super::table::Table::new(),
cparams,
force_non_contiguous: false,
use_row_match_finder: false,
tag_table: super::table::Table::new(),
hash_cache: [0; super::row::ROW_HASH_CACHE_SIZE],
row_hash_log: 0,
hash_salt: 0,
hash_salt_entropy: 0,
lazy_skipping: false,
hash_log3: 0,
hash_table3: super::table::Table::new(),
opt: None,
dict: None,
dms: false,
}
}
pub(crate) fn reset(&mut self, cparams: CParams) {
let use_row = row_match_finder_used(
cparams.strategy,
resolve_row_match_finder_mode(ParamSwitch::Auto, &cparams),
);
self.reset_with(cparams, use_row, false);
}
pub(crate) fn reset_with(&mut self, cparams: CParams, use_row: bool, for_cdict: bool) {
self.reset_impl(cparams, use_row, for_cdict, false);
}
pub(crate) fn reset_keep_indices(&mut self, cparams: CParams, use_row: bool) {
self.reset_impl(cparams, use_row, false, true);
}
fn reset_impl(&mut self, cparams: CParams, use_row: bool, for_cdict: bool, keep: bool) {
let h_size = 1usize << cparams.hash_log;
let c_size = if cparams.strategy == Strategy::Fast || use_row {
0
} else {
1usize << cparams.chain_log
};
let hash_log3 = if cparams.min_match == 3 && !for_cdict {
HASHLOG3_MAX.min(cparams.window_log)
} else {
0
};
let h3_size = if hash_log3 > 0 {
1usize << hash_log3
} else {
0
};
let keep = keep
&& !for_cdict
&& (self.dms || self.dict.is_none())
&& !self.window.base_in_dict
&& !self.window.dict_base_in_dict
&& self.cparams.strategy == cparams.strategy
&& self.use_row_match_finder == use_row
&& self.hash_table.len() == h_size
&& self.chain_table.len() == c_size
&& self.hash_table3.len() == h3_size
&& self.window.next_src.wrapping_sub(self.window.base)
<= (CURRENT_MAX - INDEXOVERFLOW_MARGIN) as usize;
if !keep {
self.window = Window::new();
}
self.lazy_skipping = false;
self.invalidate();
if !keep {
self.hash_table.reset_zeroed(h_size);
self.chain_table.reset_zeroed(c_size);
self.hash_table3.reset_zeroed(h3_size);
}
self.use_row_match_finder = use_row;
if use_row {
if for_cdict {
self.tag_table.reset_zeroed(h_size);
self.hash_salt = 0;
} else {
self.tag_table.resize(h_size);
self.advance_hash_salt();
}
let row_log = cparams.search_log.clamp(4, 6);
debug_assert!(cparams.hash_log >= row_log);
self.row_hash_log = cparams.hash_log - row_log;
}
self.hash_log3 = hash_log3;
if cparams.strategy >= Strategy::BtOpt && self.opt.is_none() && !for_cdict {
self.opt = Some(alloc::boxed::Box::new(super::opt::OptState::new()));
}
self.cparams = cparams;
self.force_non_contiguous = false;
}
fn advance_hash_salt(&mut self) {
self.hash_salt = bitmix(self.hash_salt, 8) ^ bitmix(u64::from(self.hash_salt_entropy), 4);
}
pub(crate) fn clear_hash_salt(&mut self) {
self.hash_salt = 0;
self.hash_salt_entropy = 0;
}
pub(crate) fn invalidate(&mut self) {
self.window.clear();
self.next_to_update = self.window.dict_limit;
self.loaded_dict_end = 0;
self.dms = false;
self.dict = None;
if let Some(opt) = self.opt.as_deref_mut() {
opt.stats.lit_length_sum = 0;
}
}
pub(crate) fn update_window(&mut self, src: usize, src_size: usize) {
if !self.window.update(src, src_size, self.force_non_contiguous) {
self.force_non_contiguous = false;
self.next_to_update = self.window.dict_limit;
}
}
#[inline(always)]
pub(crate) fn lowest_match_index(&self, curr: u32, window_log: u32) -> u32 {
let max_distance = 1u32 << window_log;
let lowest_valid = self.window.low_limit;
let within_window = if curr.wrapping_sub(lowest_valid) > max_distance {
curr - max_distance
} else {
lowest_valid
};
if self.loaded_dict_end != 0 {
lowest_valid
} else {
within_window
}
}
#[inline(always)]
pub(crate) fn lowest_prefix_index(&self, curr: u32, window_log: u32) -> u32 {
let max_distance = 1u32 << window_log;
let lowest_valid = self.window.dict_limit;
let within_window = if curr.wrapping_sub(lowest_valid) > max_distance {
curr - max_distance
} else {
lowest_valid
};
if self.loaded_dict_end != 0 {
lowest_valid
} else {
within_window
}
}
pub(crate) fn overflow_correct_if_needed(&mut self, ip: usize, iend: usize) {
let cycle_log = cycle_log(self.cparams.chain_log, self.cparams.strategy);
let max_dist = 1u32 << self.cparams.window_log;
if self.window.need_overflow_correction(iend) {
let correction = self.window.correct_overflow(cycle_log, max_dist, ip);
reduce_table(&mut self.hash_table, correction);
if self.cparams.strategy == Strategy::BtLazy2 {
reduce_table_btlazy2(&mut self.chain_table, correction);
} else {
reduce_table(&mut self.chain_table, correction);
}
reduce_table(&mut self.hash_table3, correction);
self.next_to_update = self.next_to_update.saturating_sub(correction);
self.loaded_dict_end = 0;
self.dms = false;
}
}
pub(crate) fn prepare_block(&mut self, start: usize, block_size: usize) {
let max_dist = 1u32 << self.cparams.window_log;
let end = start + block_size;
self.overflow_correct_if_needed(start, end);
self.window
.check_dict_validity(end, max_dist, &mut self.loaded_dict_end, &mut self.dms);
self.window
.enforce_max_dist(start, max_dist, &mut self.loaded_dict_end, &mut self.dms);
if self.next_to_update < self.window.low_limit {
self.next_to_update = self.window.low_limit;
}
}
pub(crate) fn fill_hash_table(&mut self, buf: &[u8], end: usize, dtlm: TableLoadMethod) {
const FAST_HASH_FILL_STEP: usize = 3;
let h_bits = self.cparams.hash_log;
let mls = self.cparams.min_match;
assert!(end <= buf.len());
let mut ip = self.window.pos(self.next_to_update);
while ip + FAST_HASH_FILL_STEP + HASH_READ_SIZE < end + 2 {
let curr = self.window.index(ip);
let hash0 = hash_at_buf(buf, ip, h_bits, mls);
self.hash_table[hash0] = curr;
if dtlm == TableLoadMethod::Full {
for p in 1..FAST_HASH_FILL_STEP {
let hash = hash_at_buf(buf, ip + p, h_bits, mls);
if self.hash_table[hash] == 0 {
self.hash_table[hash] = curr + p as u32;
}
}
}
ip += FAST_HASH_FILL_STEP;
}
}
pub(crate) fn fill_hash_table_for_cdict(
&mut self,
buf: &[u8],
end: usize,
dtlm: TableLoadMethod,
) {
const FAST_HASH_FILL_STEP: usize = 3;
let h_bits = self.cparams.hash_log + SHORT_CACHE_TAG_BITS;
let mls = self.cparams.min_match;
assert!(end <= buf.len());
let mut ip = self.window.pos(self.next_to_update);
while ip + FAST_HASH_FILL_STEP + HASH_READ_SIZE < end + 2 {
let curr = self.window.index(ip);
write_tagged_index(
&mut self.hash_table,
hash_at_buf(buf, ip, h_bits, mls),
curr,
);
if dtlm == TableLoadMethod::Full {
for p in 1..FAST_HASH_FILL_STEP {
let hash_and_tag = hash_at_buf(buf, ip + p, h_bits, mls);
if self.hash_table[hash_and_tag >> SHORT_CACHE_TAG_BITS] == 0 {
write_tagged_index(&mut self.hash_table, hash_and_tag, curr + p as u32);
}
}
}
ip += FAST_HASH_FILL_STEP;
}
}
pub(crate) fn ext_buf<'a>(&'a self, buf: &'a [u8]) -> &'a [u8] {
match &self.dict {
Some(d) if self.window.dict_base_in_dict => &d.content,
_ => buf,
}
}
}
pub(crate) const SHORT_CACHE_TAG_BITS: u32 = 8;
pub(crate) const SHORT_CACHE_TAG_MASK: u32 = (1 << SHORT_CACHE_TAG_BITS) - 1;
#[inline(always)]
pub(crate) fn write_tagged_index(table: &mut [u32], hash_and_tag: usize, index: u32) {
let hash = hash_and_tag >> SHORT_CACHE_TAG_BITS;
let tag = hash_and_tag as u32 & SHORT_CACHE_TAG_MASK;
debug_assert!(index >> (32 - SHORT_CACHE_TAG_BITS) == 0);
table[hash] = (index << SHORT_CACHE_TAG_BITS) | tag;
}
fn hash_at_buf(buf: &[u8], pos: usize, h_bits: u32, mls: u32) -> usize {
super::seq_store::hash_at(buf, pos, h_bits, mls)
}
pub(crate) fn build_seq_store(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> bool {
debug_assert!(end - start <= super::params::BLOCKSIZE_MAX);
if end - start < MIN_SEQ_STORE_BLOCK {
return false;
}
ss.reset();
let curr = ms.window.index(start);
if curr > ms.next_to_update + 384 {
ms.next_to_update = curr - 192u32.min(curr - ms.next_to_update - 384);
}
let last_ll_size = if ms.window.has_ext_dict() {
match ms.cparams.strategy {
Strategy::Fast => compress_block_fast_ext_dict(ms, ss, rep, buf, start, end),
Strategy::DFast => {
super::dfast::compress_block_double_fast_ext_dict(ms, ss, rep, buf, start, end)
}
Strategy::Greedy | Strategy::Lazy | Strategy::Lazy2 | Strategy::BtLazy2 => {
super::lazy::compress_block_lazy_ext_dict(ms, ss, rep, buf, start, end)
}
Strategy::BtOpt | Strategy::BtUltra | Strategy::BtUltra2 => {
super::opt::compress_block_opt_ext_dict(ms, ss, rep, buf, start, end)
}
}
} else if ms.dms {
match ms.cparams.strategy {
Strategy::Fast => compress_block_fast_dict_match_state(ms, ss, rep, buf, start, end),
Strategy::DFast => super::dfast::compress_block_double_fast_dict_match_state(
ms, ss, rep, buf, start, end,
),
Strategy::Greedy | Strategy::Lazy | Strategy::Lazy2 | Strategy::BtLazy2 => {
super::lazy::compress_block_lazy_dict_match_state(ms, ss, rep, buf, start, end)
}
Strategy::BtOpt | Strategy::BtUltra | Strategy::BtUltra2 => {
super::opt::compress_block_opt_dict_match_state(ms, ss, rep, buf, start, end)
}
}
} else {
match ms.cparams.strategy {
Strategy::Fast => compress_block_fast(ms, ss, rep, buf, start, end),
Strategy::DFast => {
super::dfast::compress_block_double_fast(ms, ss, rep, buf, start, end)
}
Strategy::Greedy | Strategy::Lazy | Strategy::Lazy2 | Strategy::BtLazy2 => {
super::lazy::compress_block_lazy(ms, ss, rep, buf, start, end)
}
Strategy::BtOpt | Strategy::BtUltra | Strategy::BtUltra2 => {
super::opt::compress_block_opt(ms, ss, rep, buf, start, end)
}
}
};
ss.store_last_literals(&buf[end - last_ll_size..end]);
true
}
pub(crate) type BlockCompressor =
fn(&mut MatchState, &mut SeqStore, &mut [u32; 3], &[u8], usize, usize) -> usize;
pub(crate) fn select_block_compressor(ms: &MatchState) -> BlockCompressor {
use super::{dfast, lazy, opt};
if ms.window.has_ext_dict() {
match ms.cparams.strategy {
Strategy::Fast => compress_block_fast_ext_dict,
Strategy::DFast => dfast::compress_block_double_fast_ext_dict,
Strategy::Greedy | Strategy::Lazy | Strategy::Lazy2 | Strategy::BtLazy2 => {
lazy::compress_block_lazy_ext_dict
}
Strategy::BtOpt | Strategy::BtUltra | Strategy::BtUltra2 => {
opt::compress_block_opt_ext_dict
}
}
} else if ms.dms {
match ms.cparams.strategy {
Strategy::Fast => compress_block_fast_dict_match_state,
Strategy::DFast => dfast::compress_block_double_fast_dict_match_state,
Strategy::Greedy | Strategy::Lazy | Strategy::Lazy2 | Strategy::BtLazy2 => {
lazy::compress_block_lazy_dict_match_state
}
Strategy::BtOpt | Strategy::BtUltra | Strategy::BtUltra2 => {
opt::compress_block_opt_dict_match_state
}
}
} else {
match ms.cparams.strategy {
Strategy::Fast => compress_block_fast,
Strategy::DFast => dfast::compress_block_double_fast,
Strategy::Greedy | Strategy::Lazy | Strategy::Lazy2 | Strategy::BtLazy2 => {
lazy::compress_block_lazy
}
Strategy::BtOpt | Strategy::BtUltra | Strategy::BtUltra2 => opt::compress_block_opt,
}
}
}
#[inline(never)]
pub(crate) fn compress_block_fast(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
debug_assert!(ms.cparams.strategy == Strategy::Fast);
let use_cmov = ms.cparams.window_log < 19;
match (ms.cparams.min_match, use_cmov) {
(5, true) => no_dict_generic::<5, true>(ms, ss, rep, buf, start, end),
(6, true) => no_dict_generic::<6, true>(ms, ss, rep, buf, start, end),
(7, true) => no_dict_generic::<7, true>(ms, ss, rep, buf, start, end),
(_, true) => no_dict_generic::<4, true>(ms, ss, rep, buf, start, end),
(5, false) => no_dict_generic::<5, false>(ms, ss, rep, buf, start, end),
(6, false) => no_dict_generic::<6, false>(ms, ss, rep, buf, start, end),
(7, false) => no_dict_generic::<7, false>(ms, ss, rep, buf, start, end),
(_, false) => no_dict_generic::<4, false>(ms, ss, rep, buf, start, end),
}
}
#[allow(unsafe_code)]
#[inline(always)]
pub(crate) unsafe fn hash_mls<const MLS: u32>(p: *const u8, h_bits: u32) -> usize {
unsafe {
match MLS {
5 => hash5_ptr(p, h_bits),
6 => hash6_ptr(p, h_bits),
7 => hash7_ptr(p, h_bits),
8 => hash8_ptr(p, h_bits),
_ => hash4_ptr(p, h_bits),
}
}
}
pub(super) struct FastSearch {
pub(super) prime: u64,
pub(super) step: usize,
pub(super) lim: usize,
pub(super) base: *const u8,
pub(super) ht: *mut u32,
pub(super) low: u64,
pub(super) shift: u64,
pub(super) lowest: *const u8,
pub(super) iend: *const u8,
}
pub(super) struct FastCursor {
pub(super) ip0: *const u8,
pub(super) ip2: *const u8,
pub(super) hash0: usize,
pub(super) hash1: usize,
pub(super) match_idx: u64,
}
pub(super) const FAST_REP: u32 = 0;
pub(super) const FAST_MATCH0: u32 = 1;
pub(super) const FAST_MATCH1: u32 = 2;
pub(super) const FAST_LIMIT: u32 = 3;
#[allow(unsafe_code)]
#[inline(always)]
pub(crate) unsafe fn hash_with(p: *const u8, prime: u64, shift: u64) -> usize {
debug_assert!(shift < 64);
(unsafe { read_le64(p) }.wrapping_mul(prime) >> shift) as usize
}
#[inline(always)]
pub(crate) const fn hash_prime<const MLS: u32>() -> u64 {
use super::seq_store::{PRIME4BYTES, PRIME5BYTES, PRIME6BYTES, PRIME7BYTES, PRIME8BYTES};
match MLS {
5 => PRIME5BYTES << 24,
6 => PRIME6BYTES << 16,
7 => PRIME7BYTES << 8,
8 => PRIME8BYTES,
_ => (PRIME4BYTES as u64) << 32,
}
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn fast_search_rust<const MLS: u32, const USE_CMOV: bool>(
s: &FastSearch,
c: &mut FastCursor,
rep_offset1: u32,
) -> u32 {
static DUMMY: [u8; 4] = [0x12, 0x34, 0x56, 0x78];
let chk = |p: *const u8, n: usize| {
debug_assert!(
(p as usize) >= (s.lowest as usize) && (p as usize) + n <= (s.iend as usize),
"read out of the window"
);
};
let base = s.base;
let low = s.low as u32;
let ht = s.ht;
let idx = |p: *const u8| (p as usize).wrapping_sub(base as usize) as u32;
unsafe {
let hash = |p: *const u8| {
chk(p, HASH_READ_SIZE);
hash_with(p, hash_prime::<MLS>(), s.shift)
};
let match_found = |cur: *const u8, match_idx: u32| -> bool {
if USE_CMOV {
let valid = match_idx >= low;
let mval_addr = core::hint::select_unpredictable(
valid,
base.wrapping_add(match_idx as usize),
DUMMY.as_ptr(),
);
if valid {
chk(mval_addr, 4);
}
if read32(cur) != read32(mval_addr) {
return false;
}
valid
} else {
let mval = if match_idx >= low {
let m = base.wrapping_add(match_idx as usize);
chk(m, 4);
read32(m)
} else {
read32(cur) ^ 1
};
read32(cur) == mval
}
};
let FastCursor {
mut ip0,
mut ip2,
mut hash0,
mut hash1,
match_idx,
} = *c;
let mut match_idx = match_idx as u32;
let (step, lim) = (s.step, s.lim);
loop {
let rep_ptr = ip2.wrapping_sub(rep_offset1 as usize);
chk(rep_ptr, 4);
let rval = read32(rep_ptr);
*ht.add(hash0) = idx(ip0);
if (read32(ip2) == rval) & (rep_offset1 > 0) {
*c = FastCursor {
ip0,
ip2,
hash0,
hash1,
match_idx: u64::from(match_idx),
};
return FAST_REP;
}
if match_found(ip0, match_idx) {
*c = FastCursor {
ip0,
ip2,
hash0,
hash1,
match_idx: u64::from(match_idx),
};
return FAST_MATCH0;
}
match_idx = *ht.add(hash1);
hash0 = hash1;
hash1 = hash(ip2);
ip0 = ip0.wrapping_add(1);
*ht.add(hash0) = idx(ip0);
if match_found(ip0, match_idx) {
*c = FastCursor {
ip0,
ip2,
hash0,
hash1,
match_idx: u64::from(match_idx),
};
return FAST_MATCH1;
}
match_idx = *ht.add(hash1);
hash0 = hash1;
hash1 = hash(ip2.wrapping_add(1));
ip0 = ip2;
ip2 = ip0.wrapping_add(step);
if ip2 as usize >= lim {
*c = FastCursor {
ip0,
ip2,
hash0,
hash1,
match_idx: u64::from(match_idx),
};
return FAST_LIMIT;
}
}
}
}
#[allow(unsafe_code)]
#[inline(always)]
fn no_dict_generic<const MLS: u32, const USE_CMOV: bool>(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
const K_STEP_INCR: usize = 1 << (K_SEARCH_STRENGTH - 1);
let cparams = ms.cparams;
let hlog = cparams.hash_log;
assert!(start <= end && end <= buf.len());
assert!(ms.hash_table.len() == 1usize << hlog && hlog <= 32);
let window_start = ms.window.pos(ms.window.dict_limit);
assert!(window_start <= start, "window start is not in the buffer");
assert!(end.wrapping_sub(ms.window.base) <= u32::MAX as usize);
ss.reserve(end - start);
let step_size = cparams.target_length as usize + (cparams.target_length == 0) as usize + 1;
let bp = buf.as_ptr();
let base = bp.wrapping_add(ms.window.base);
let istart = bp.wrapping_add(start);
let end_index = ms.window.index(end);
let prefix_start_index = ms.lowest_prefix_index(end_index, cparams.window_log);
let prefix_start = base.wrapping_add(prefix_start_index as usize);
let iend = bp.wrapping_add(end);
let ilimit = iend.wrapping_sub(HASH_READ_SIZE);
let lowest = bp.wrapping_add(window_start);
let ht = ms.hash_table.as_mut_ptr();
let idx = |p: *const u8| (p as usize).wrapping_sub(base as usize) as u32;
let chk = |p: *const u8, n: usize| {
debug_assert!(
(p as usize) >= (lowest as usize) && (p as usize) + n <= (iend as usize),
"read out of the window"
);
};
let mut anchor = istart;
let mut ip0 = istart;
let mut rep_offset1 = rep[0];
let mut rep_offset2 = rep[1];
let mut offset_saved1 = 0u32;
let mut offset_saved2 = 0u32;
if ip0 == prefix_start {
ip0 = ip0.wrapping_add(1);
}
{
let curr = idx(ip0);
let window_low = ms.lowest_prefix_index(curr, cparams.window_log);
let max_rep = curr.wrapping_sub(window_low);
if rep_offset2 > max_rep {
offset_saved2 = rep_offset2;
rep_offset2 = 0;
}
if rep_offset1 > max_rep {
offset_saved1 = rep_offset1;
rep_offset1 = 0;
}
}
unsafe {
let hash = |p: *const u8| {
chk(p, HASH_READ_SIZE);
hash_mls::<MLS>(p, hlog)
};
let mut s = FastSearch {
prime: hash_prime::<MLS>(),
step: step_size,
lim: 0,
base,
ht,
low: u64::from(prefix_start_index),
shift: u64::from(64 - hlog),
lowest,
iend,
};
'start: loop {
#[cfg(all(target_arch = "x86_64", not(feature = "portable")))]
if rep_offset1 != 0 && crate::cpu::Features::detect().bmi2 {
let lit_base = ss.lit_buf.as_mut_ptr();
let seq_base = ss.sequences.as_mut_ptr();
let mut ctx = super::block_asm::FastCtx {
prime: hash_prime::<MLS>(),
step_size,
step: step_size,
lim: 0,
next_step: 0,
anchor,
iend,
ilimit,
prefix_start,
lit_limit_w: (iend as usize)
.saturating_sub(super::seq_store::WILDCOPY_OVERLENGTH),
lit: lit_base.add(ss.lit_len),
seq: seq_base.add(ss.nb_seq),
rep1: u64::from(rep_offset1),
rep2: u64::from(rep_offset2),
llt: 0,
llpos: core::ptr::null_mut(),
};
super::block_asm::fast_block(
&mut ctx,
ip0,
ht,
base,
u64::from(prefix_start_index),
0usize.wrapping_sub(rep_offset1 as usize),
u64::from(64 - hlog),
);
anchor = ctx.anchor;
rep_offset1 = ctx.rep1 as u32;
rep_offset2 = ctx.rep2 as u32;
debug_assert!(istart <= anchor && anchor <= iend);
debug_assert!(rep_offset1 != 0 && (ctx.rep1 >> 32) == 0 && (ctx.rep2 >> 32) == 0);
debug_assert!(ctx.lit >= lit_base && ctx.seq >= seq_base);
ss.lit_len = ctx.lit as usize - lit_base as usize;
ss.nb_seq = (ctx.seq as usize - seq_base as usize)
/ core::mem::size_of::<super::seq_store::SeqDef>();
debug_assert!(ss.lit_len <= ss.max_nb_lit && ss.nb_seq <= ss.max_nb_seq);
if ctx.llt != 0 {
debug_assert!(ss.long_length_type == super::seq_store::LongLengthType::None);
ss.long_length_type = if ctx.llt == 1 {
super::seq_store::LongLengthType::LiteralLength
} else {
super::seq_store::LongLengthType::MatchLength
};
ss.long_length_pos = ((ctx.llpos as usize - seq_base as usize)
/ core::mem::size_of::<super::seq_store::SeqDef>())
as u32;
}
break 'start;
}
let mut step = step_size;
let mut next_step = ip0.wrapping_add(K_STEP_INCR);
let ip1 = ip0.wrapping_add(1);
let ip2 = ip0.wrapping_add(step);
let ip3 = ip2.wrapping_add(1);
if ip3 >= ilimit {
break 'start;
}
s.lim = (next_step as usize).min(ilimit as usize - 1);
s.step = step;
let hash0 = hash(ip0);
let mut cur = FastCursor {
ip0,
ip2,
hash0,
hash1: hash(ip1),
match_idx: u64::from(*ht.add(hash0)),
};
let current0: u32;
let mut match0: *const u8;
let mut m_length: usize;
let offcode: u32;
loop {
let exit = fast_search_rust::<MLS, USE_CMOV>(&s, &mut cur, rep_offset1);
if exit == FAST_LIMIT {
let ip2 = cur.ip2;
if ip2 >= next_step {
step += 1;
prefetch_l1(cur.ip0.wrapping_add(1 + 64));
prefetch_l1(cur.ip0.wrapping_add(1 + 128));
next_step = next_step.wrapping_add(K_STEP_INCR);
}
if ip2.wrapping_add(1) >= ilimit {
break 'start;
}
s.lim = (next_step as usize).min(ilimit as usize - 1);
s.step = step;
continue;
}
ip0 = cur.ip0;
current0 = idx(ip0);
if exit == FAST_REP {
let ip1 = ip0.wrapping_add(1);
ip0 = cur.ip2;
match0 = ip0.wrapping_sub(rep_offset1 as usize);
chk(match0.wrapping_sub(1), 1);
m_length = (*ip0.sub(1) == *match0.sub(1)) as usize;
ip0 = ip0.wrapping_sub(m_length);
match0 = match0.wrapping_sub(m_length);
offcode = REPCODE1_TO_OFFBASE;
m_length += 4;
*ht.add(cur.hash1) = idx(ip1);
} else {
if exit == FAST_MATCH0 {
*ht.add(cur.hash1) = idx(ip0.wrapping_add(1));
} else if step <= 4 {
*ht.add(cur.hash1) = idx(cur.ip2);
}
(match0, m_length, offcode) = offset_match(
base,
cur.match_idx as u32,
&mut ip0,
anchor,
prefix_start,
&mut rep_offset1,
&mut rep_offset2,
);
}
break;
}
chk(match0, 0);
m_length += count(ip0.add(m_length), match0.add(m_length), iend);
ss.store_seq_unchecked(
buf,
anchor as usize - bp as usize,
ip0 as usize - anchor as usize,
end,
offcode,
m_length,
);
ip0 = ip0.add(m_length);
anchor = ip0;
if ip0 <= ilimit {
debug_assert!(base.wrapping_add(current0 as usize + 2) > istart);
*ht.add(hash(base.wrapping_add(current0 as usize + 2))) = current0 + 2;
*ht.add(hash(ip0.sub(2))) = idx(ip0.sub(2));
if rep_offset2 > 0 {
while ip0 <= ilimit && {
let r = ip0.wrapping_sub(rep_offset2 as usize);
chk(r, 4);
read32(ip0) == read32(r)
} {
let r = ip0.wrapping_sub(rep_offset2 as usize);
let r_length = count(ip0.add(4), r.add(4), iend) + 4;
core::mem::swap(&mut rep_offset1, &mut rep_offset2);
*ht.add(hash(ip0)) = idx(ip0);
ip0 = ip0.add(r_length);
ss.store_seq_unchecked(
buf,
anchor as usize - bp as usize,
0,
end,
REPCODE1_TO_OFFBASE,
r_length,
);
anchor = ip0;
}
}
}
}
}
if offset_saved1 != 0 && rep_offset1 != 0 {
offset_saved2 = offset_saved1;
}
rep[0] = if rep_offset1 != 0 {
rep_offset1
} else {
offset_saved1
};
rep[1] = if rep_offset2 != 0 {
rep_offset2
} else {
offset_saved2
};
iend as usize - anchor as usize
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn offset_match(
base: *const u8,
match_idx: u32,
ip0: &mut *const u8,
anchor: *const u8,
prefix_start: *const u8,
rep_offset1: &mut u32,
rep_offset2: &mut u32,
) -> (*const u8, usize, u32) {
let mut match0 = base.wrapping_add(match_idx as usize);
*rep_offset2 = *rep_offset1;
*rep_offset1 = (*ip0 as usize - match0 as usize) as u32;
let offcode = offset_to_offbase(*rep_offset1);
let mut m_length = 4;
unsafe {
while ((*ip0 > anchor) & (match0 > prefix_start)) && *ip0.sub(1) == *match0.sub(1) {
*ip0 = ip0.sub(1);
match0 = match0.sub(1);
m_length += 1;
}
}
(match0, m_length, offcode)
}
#[inline(always)]
pub(crate) fn compress_block_fast_ext_dict(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
debug_assert!(ms.cparams.strategy == Strategy::Fast);
let end_index = ms.window.index(end);
let low_limit = ms.lowest_match_index(end_index, ms.cparams.window_log);
if end_index - low_limit <= 1 << 16 {
return ext_dict_cmov(ms, ss, rep, buf, start, end);
}
ext_dict_branch(ms, ss, rep, buf, start, end)
}
#[inline(never)]
fn ext_dict_branch(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
ext_dict_mls::<false>(ms, ss, rep, buf, start, end)
}
#[inline(never)]
fn ext_dict_cmov(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
#[cfg(all(target_arch = "x86_64", not(feature = "portable")))]
if crate::cpu::Features::detect().bmi2 {
#[allow(unsafe_code)]
return unsafe { ext_dict_bmi2(ms, ss, rep, buf, start, end) };
}
ext_dict_mls::<true>(ms, ss, rep, buf, start, end)
}
#[cfg(all(target_arch = "x86_64", not(feature = "portable")))]
#[inline(never)]
#[target_feature(enable = "bmi1,bmi2,lzcnt")]
fn ext_dict_bmi2(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
ext_dict_mls::<true>(ms, ss, rep, buf, start, end)
}
#[inline(always)]
fn ext_dict_mls<const CMOV: bool>(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
match ms.cparams.min_match {
5 => ext_dict_generic::<5, CMOV>(ms, ss, rep, buf, start, end),
6 => ext_dict_generic::<6, CMOV>(ms, ss, rep, buf, start, end),
7 => ext_dict_generic::<7, CMOV>(ms, ss, rep, buf, start, end),
_ => ext_dict_generic::<4, CMOV>(ms, ss, rep, buf, start, end),
}
}
pub(crate) struct ExtWindow {
pub(crate) base: *const u8,
pub(crate) dict_base: *const u8,
pub(crate) dict_start_index: u32,
pub(crate) prefix_start_index: u32,
pub(crate) dict_start: *const u8,
pub(crate) dict_end: *const u8,
pub(crate) prefix_start: *const u8,
pub(crate) istart: *const u8,
pub(crate) iend: *const u8,
}
impl ExtWindow {
pub(crate) fn new(
w: &Window,
buf: &[u8],
ext: &[u8],
start: usize,
end: usize,
dict_start_index: u32,
prefix_start_index: u32,
) -> Self {
assert!(start <= end && end <= buf.len());
assert!(dict_start_index <= prefix_start_index);
let prefix_start = w.pos(prefix_start_index);
assert!(prefix_start <= start, "prefix start is not in the buffer");
assert!(end.wrapping_sub(w.base) <= u32::MAX as usize);
let dict_start = w.dict_base.wrapping_add(dict_start_index as usize);
let dict_end = w.dict_base.wrapping_add(prefix_start_index as usize);
assert!(
dict_start <= dict_end && dict_end <= ext.len(),
"extDict is not in the buffer"
);
let bp = buf.as_ptr();
let ep = ext.as_ptr();
ExtWindow {
base: bp.wrapping_add(w.base),
dict_base: ep.wrapping_add(w.dict_base),
dict_start_index,
prefix_start_index,
dict_start: ep.wrapping_add(dict_start),
dict_end: ep.wrapping_add(dict_end),
prefix_start: bp.wrapping_add(prefix_start),
istart: bp.wrapping_add(start),
iend: bp.wrapping_add(end),
}
}
#[inline(always)]
pub(crate) fn idx(&self, p: *const u8) -> u32 {
(p as usize).wrapping_sub(self.base as usize) as u32
}
#[inline(always)]
pub(crate) fn pos(&self, i: u32) -> *const u8 {
if i < self.prefix_start_index {
self.dict_base.wrapping_add(i as usize)
} else {
self.base.wrapping_add(i as usize)
}
}
#[inline(always)]
pub(crate) fn seg_end(&self, i: u32) -> *const u8 {
if i < self.prefix_start_index {
self.dict_end
} else {
self.iend
}
}
#[inline(always)]
pub(crate) fn seg_start(&self, i: u32) -> *const u8 {
if i < self.prefix_start_index {
self.dict_start
} else {
self.prefix_start
}
}
#[inline(always)]
pub(crate) fn chk(&self, p: *const u8, n: usize) {
let (p, e) = (p as usize, (p as usize).wrapping_add(n));
debug_assert!(
(p >= self.prefix_start as usize && e <= self.iend as usize)
|| (p >= self.dict_start as usize && e <= self.dict_end as usize),
"read out of the window"
);
}
#[allow(unsafe_code)]
#[inline(always)]
pub(crate) unsafe fn count2(&self, ip: *const u8, m: *const u8, m_end: *const u8) -> usize {
self.chk(ip, 0);
self.chk(m, 0);
unsafe { count_2segments(ip, m, self.iend, m_end, self.prefix_start) }
}
}
#[allow(unsafe_code)]
#[inline(always)]
fn ext_dict_generic<const MLS: u32, const CMOV: bool>(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
const K_STEP_INCR: usize = 1 << (K_SEARCH_STRENGTH - 1);
let cparams = ms.cparams;
let hlog = cparams.hash_log;
assert!(ms.hash_table.len() == 1usize << hlog && hlog <= 32);
let step_size = cparams.target_length as usize + (cparams.target_length == 0) as usize + 1;
let end_index = ms.window.index(end);
let low_limit = ms.lowest_match_index(end_index, cparams.window_log);
let dict_start_index = low_limit;
let dict_limit = ms.window.dict_limit;
let prefix_start_index = dict_limit.max(low_limit);
if prefix_start_index == dict_start_index {
return compress_block_fast(ms, ss, rep, buf, start, end);
}
let w = ExtWindow::new(
&ms.window,
buf,
ms.ext_buf(buf),
start,
end,
dict_start_index,
prefix_start_index,
);
let bp = buf.as_ptr();
let base = w.base;
let istart = w.istart;
let iend = w.iend;
let ilimit = iend.wrapping_sub(8);
let prefix_start = w.prefix_start;
let ht = ms.hash_table.as_mut_ptr();
let mut offset_1 = rep[0];
let mut offset_2 = rep[1];
let mut offset_saved1 = 0u32;
let mut offset_saved2 = 0u32;
let mut ip0 = istart;
let mut anchor = istart;
{
let curr = w.idx(ip0);
let max_rep = curr.wrapping_sub(dict_start_index);
if offset_2 >= max_rep {
offset_saved2 = offset_2;
offset_2 = 0;
}
if offset_1 >= max_rep {
offset_saved1 = offset_1;
offset_1 = 0;
}
}
let (dict_base, base_) = (w.dict_base, w.base);
let cand = |idx: u32, ip0: *const u8| {
let m = if CMOV {
core::hint::select_unpredictable(idx < prefix_start_index, dict_base, base_)
.wrapping_add(idx as usize)
} else {
w.pos(idx)
};
let valid = idx >= dict_start_index;
if valid {
w.chk(m, 4);
}
unsafe { cand_match::<CMOV, false>(valid, m, ip0) }
};
unsafe {
let hash = |p: *const u8| {
w.chk(p, HASH_READ_SIZE);
hash_mls::<MLS>(p, hlog)
};
'start: loop {
let mut step = step_size;
let mut next_step = ip0.wrapping_add(K_STEP_INCR);
let mut ip1 = ip0.wrapping_add(1);
let mut ip2 = ip0.wrapping_add(step);
let mut ip3 = ip2.wrapping_add(1);
if ip3 >= ilimit {
break 'start;
}
let mut hash0 = hash(ip0);
let mut hash1 = hash(ip1);
let mut idx = *ht.add(hash0);
let current0: u32;
let mut match0: *const u8;
let mut m_length: usize;
let offcode: u32;
let match_end: *const u8;
'search: loop {
{
let current2 = w.idx(ip2);
let rep_index = current2.wrapping_sub(offset_1);
let rep_match = w.pos(rep_index);
let rval = if (prefix_start_index.wrapping_sub(rep_index) >= 4) & (offset_1 > 0)
{
w.chk(rep_match, 4);
read32(rep_match)
} else {
read32(ip2) ^ 1 };
let c0 = w.idx(ip0);
*ht.add(hash0) = c0;
if read32(ip2) == rval {
ip0 = ip2;
match0 = rep_match;
match_end = w.seg_end(rep_index);
debug_assert!(match0 != prefix_start && match0 != w.dict_start);
w.chk(match0.wrapping_sub(1), 1);
m_length = (*ip0.sub(1) == *match0.sub(1)) as usize;
ip0 = ip0.wrapping_sub(m_length);
match0 = match0.wrapping_sub(m_length);
offcode = REPCODE1_TO_OFFBASE;
m_length += 4;
current0 = c0;
break 'search;
}
if cand(idx, ip0) {
current0 = c0;
(match0, m_length, offcode, match_end) = ext_offset_match(
&w,
idx,
c0,
&mut ip0,
anchor,
&mut offset_1,
&mut offset_2,
);
break 'search;
}
}
idx = *ht.add(hash1);
hash0 = hash1;
hash1 = hash(ip2);
ip0 = ip1;
ip1 = ip2;
ip2 = ip3;
let c0 = w.idx(ip0);
*ht.add(hash0) = c0;
if cand(idx, ip0) {
current0 = c0;
(match0, m_length, offcode, match_end) = ext_offset_match(
&w,
idx,
c0,
&mut ip0,
anchor,
&mut offset_1,
&mut offset_2,
);
break 'search;
}
idx = *ht.add(hash1);
hash0 = hash1;
hash1 = hash(ip2);
ip0 = ip1;
ip1 = ip2;
ip2 = ip0.wrapping_add(step);
ip3 = ip1.wrapping_add(step);
if ip2 >= next_step {
step += 1;
prefetch_l1(ip1.wrapping_add(64));
prefetch_l1(ip1.wrapping_add(128));
next_step = next_step.wrapping_add(K_STEP_INCR);
}
if ip3 >= ilimit {
break 'start;
}
}
m_length += w.count2(ip0.add(m_length), match0.add(m_length), match_end);
ss.store_seq(
buf,
anchor as usize - bp as usize,
ip0 as usize - anchor as usize,
end,
offcode,
m_length,
);
ip0 = ip0.add(m_length);
anchor = ip0;
if ip1 < ip0 {
*ht.add(hash1) = w.idx(ip1);
}
if ip0 <= ilimit {
debug_assert!(base.wrapping_add(current0 as usize + 2) > istart);
*ht.add(hash(base.wrapping_add(current0 as usize + 2))) = current0 + 2;
*ht.add(hash(ip0.sub(2))) = w.idx(ip0.sub(2));
while ip0 <= ilimit {
let rep_index2 = w.idx(ip0).wrapping_sub(offset_2);
let rep_match2 = w.pos(rep_index2);
if (index_overlap_check(prefix_start_index, rep_index2) & (offset_2 > 0)) && {
w.chk(rep_match2, 4);
read32(rep_match2) == read32(ip0)
} {
let rep_end2 = w.seg_end(rep_index2);
let rep_length2 = w.count2(ip0.add(4), rep_match2.add(4), rep_end2) + 4;
core::mem::swap(&mut offset_1, &mut offset_2);
ss.store_seq(
buf,
anchor as usize - bp as usize,
0,
end,
REPCODE1_TO_OFFBASE,
rep_length2,
);
*ht.add(hash(ip0)) = w.idx(ip0);
ip0 = ip0.add(rep_length2);
anchor = ip0;
continue;
}
break;
}
}
}
}
if offset_saved1 != 0 && offset_1 != 0 {
offset_saved2 = offset_saved1;
}
rep[0] = if offset_1 != 0 {
offset_1
} else {
offset_saved1
};
rep[1] = if offset_2 != 0 {
offset_2
} else {
offset_saved2
};
iend as usize - anchor as usize
}
static DUMMY8: [u8; 8] = [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0];
#[inline(always)]
pub(crate) fn select_addr(valid: bool, candidate: *const u8) -> *const u8 {
core::hint::select_unpredictable(valid, candidate, DUMMY8.as_ptr())
}
#[allow(unsafe_code)]
#[inline(always)]
pub(crate) fn then_valid(eq: bool, valid: bool) -> bool {
if !eq {
return false;
}
#[cfg(all(any(target_arch = "x86_64", target_arch = "aarch64"), not(miri)))]
unsafe {
core::arch::asm!("", options(nomem, nostack, preserves_flags));
}
valid
}
#[allow(unsafe_code)]
#[inline(always)]
pub(crate) unsafe fn cand_match<const CMOV: bool, const LONG: bool>(
valid: bool,
cand: *const u8,
ip: *const u8,
) -> bool {
unsafe {
let rd = |p: *const u8| {
if LONG {
read_le64(p)
} else {
u64::from(read32(p))
}
};
if CMOV {
then_valid(rd(select_addr(valid, cand)) == rd(ip), valid)
} else {
valid && rd(cand) == rd(ip)
}
}
}
#[inline(always)]
pub(crate) fn index_overlap_check(prefix_lowest_index: u32, rep_index: u32) -> bool {
prefix_lowest_index.wrapping_sub(1).wrapping_sub(rep_index) >= 3
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn ext_offset_match(
w: &ExtWindow,
idx: u32,
current0: u32,
ip0: &mut *const u8,
anchor: *const u8,
offset_1: &mut u32,
offset_2: &mut u32,
) -> (*const u8, usize, u32, *const u8) {
let offset = current0 - idx;
let low_match_ptr = w.seg_start(idx);
let match_end = w.seg_end(idx);
let mut match0 = w.pos(idx);
*offset_2 = *offset_1;
*offset_1 = offset;
let offcode = offset_to_offbase(offset);
let mut m_length = 4;
unsafe {
while ((*ip0 > anchor) & (match0 > low_match_ptr)) && *ip0.sub(1) == *match0.sub(1) {
*ip0 = ip0.sub(1);
match0 = match0.sub(1);
m_length += 1;
}
}
(match0, m_length, offcode, match_end)
}
pub(crate) struct DmsView {
pub(crate) base: *const u8,
pub(crate) hash_table: *const u32,
pub(crate) chain_table: *const u32,
pub(crate) tag_table: *const u8,
pub(crate) hash_log: u32,
pub(crate) chain_log: u32,
pub(crate) row_hash_log: u32,
pub(crate) dict_limit: u32,
pub(crate) low_limit: u32,
pub(crate) end: *const u8,
pub(crate) high_limit: u32,
pub(crate) start: *const u8,
}
impl DmsView {
pub(crate) fn new(cd: &super::cdict::CDict) -> Self {
let ms = &cd.ms;
let w = &ms.window;
let cp = &ms.cparams;
let content = cd.content.as_ptr();
assert!(w.low_limit <= w.dict_limit);
let start = w.pos(w.low_limit);
let end = w.next_src;
assert!(
start <= end && end <= cd.content.len(),
"dictionary window is not in its content"
);
assert!(cp.hash_log + SHORT_CACHE_TAG_BITS <= 32);
assert!(ms.hash_table.len() == 1usize << cp.hash_log);
assert!(ms.chain_table.is_empty() || ms.chain_table.len() == 1usize << cp.chain_log);
assert!(ms.tag_table.is_empty() || ms.tag_table.len() == ms.hash_table.len());
DmsView {
base: content.wrapping_add(w.base),
hash_table: ms.hash_table.as_ptr(),
chain_table: ms.chain_table.as_ptr(),
tag_table: ms.tag_table.as_ptr(),
hash_log: cp.hash_log,
chain_log: cp.chain_log,
row_hash_log: ms.row_hash_log,
dict_limit: w.dict_limit,
low_limit: w.low_limit,
end: content.wrapping_add(end),
high_limit: w.index(end),
start: content.wrapping_add(start),
}
}
#[inline(always)]
pub(crate) fn chk(&self, p: *const u8, n: usize) {
let (p, e) = (p as usize, (p as usize).wrapping_add(n));
debug_assert!(
p >= self.start as usize && e <= self.end as usize,
"read out of the dictionary"
);
}
}
#[inline(always)]
pub(crate) fn compare_packed_tags(packed_tag1: usize, packed_tag2: usize) -> bool {
(packed_tag1 as u32 & SHORT_CACHE_TAG_MASK) == (packed_tag2 as u32 & SHORT_CACHE_TAG_MASK)
}
#[inline(never)]
pub(crate) fn compress_block_fast_dict_match_state(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
debug_assert!(ms.cparams.strategy == Strategy::Fast);
#[cfg(all(target_arch = "x86_64", not(feature = "portable")))]
if crate::cpu::Features::detect().bmi2 {
#[allow(unsafe_code)]
return unsafe { dms_bmi2(ms, ss, rep, buf, start, end) };
}
dms_mls(ms, ss, rep, buf, start, end)
}
#[cfg(all(target_arch = "x86_64", not(feature = "portable")))]
#[inline(never)]
#[target_feature(enable = "bmi1,bmi2,lzcnt")]
fn dms_bmi2(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
dms_mls(ms, ss, rep, buf, start, end)
}
#[inline(always)]
fn dms_mls(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
match ms.cparams.min_match {
5 => dms_generic::<5>(ms, ss, rep, buf, start, end),
6 => dms_generic::<6>(ms, ss, rep, buf, start, end),
7 => dms_generic::<7>(ms, ss, rep, buf, start, end),
_ => dms_generic::<4>(ms, ss, rep, buf, start, end),
}
}
#[allow(unsafe_code)]
#[inline(always)]
fn dms_generic<const MLS: u32>(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
const K_STEP_INCR: usize = 1 << K_SEARCH_STRENGTH;
let cparams = ms.cparams;
let hlog = cparams.hash_log;
assert!(start <= end && end <= buf.len());
assert!(ms.hash_table.len() == 1usize << hlog && hlog <= 32);
assert!(!ms.window.has_ext_dict());
let window_start = ms.window.pos(ms.window.dict_limit);
assert!(window_start <= start, "window start is not in the buffer");
assert!(end.wrapping_sub(ms.window.base) <= u32::MAX as usize);
let cd = ms.dict.clone().expect("attached dictionary");
let d = DmsView::new(&cd);
debug_assert_eq!(ms.loaded_dict_end, ms.window.dict_limit);
let step_size = cparams.target_length as usize + (cparams.target_length == 0) as usize;
let bp = buf.as_ptr();
let base = bp.wrapping_add(ms.window.base);
let istart = bp.wrapping_add(start);
let mut ip0 = istart;
let mut ip1 = ip0.wrapping_add(step_size);
let mut anchor = istart;
let prefix_start_index = ms.window.dict_limit;
let prefix_start = base.wrapping_add(prefix_start_index as usize);
let iend = bp.wrapping_add(end);
let ilimit = iend.wrapping_sub(HASH_READ_SIZE);
let mut offset_1 = rep[0];
let mut offset_2 = rep[1];
let dict_hash_table = d.hash_table;
let dict_start_index = d.dict_limit;
let dict_base = d.base;
let dict_start = dict_base.wrapping_add(dict_start_index as usize);
let dict_end = d.end;
assert!(prefix_start_index >= d.high_limit);
let dict_index_delta = prefix_start_index - d.high_limit;
let dict_and_prefix_length =
(start - window_start) as u32 + (dict_end as usize - dict_start as usize) as u32;
let dict_hbits = d.hash_log + SHORT_CACHE_TAG_BITS;
let ht = ms.hash_table.as_mut_ptr();
let idx = |p: *const u8| (p as usize).wrapping_sub(base as usize) as u32;
let chk = |p: *const u8, n: usize| {
if (p as usize) >= (dict_start as usize) && (p as usize) < (dict_end as usize) {
d.chk(p, n);
} else {
debug_assert!(
(p as usize) >= (prefix_start as usize) && (p as usize) + n <= (iend as usize),
"read out of the window"
);
}
};
ip0 = ip0.wrapping_add((dict_and_prefix_length == 0) as usize);
assert!(offset_1 <= dict_and_prefix_length && offset_2 <= dict_and_prefix_length);
assert!(step_size >= 1);
unsafe {
let hash = |p: *const u8| {
chk(p, HASH_READ_SIZE);
hash_mls::<MLS>(p, hlog)
};
let dict_hash = |p: *const u8| hash_mls::<MLS>(p, dict_hbits);
let rep_pos = |rep_index: u32| {
if rep_index < prefix_start_index {
dict_base.wrapping_add(rep_index.wrapping_sub(dict_index_delta) as usize)
} else {
base.wrapping_add(rep_index as usize)
}
};
'outer: while ip1 <= ilimit {
let m_length: usize;
let mut hash0 = hash(ip0);
let dict_hash_and_tag0 = dict_hash(ip0);
let mut dict_match_index_and_tag =
*dict_hash_table.add(dict_hash_and_tag0 >> SHORT_CACHE_TAG_BITS);
let mut dict_tags_match =
compare_packed_tags(dict_match_index_and_tag as usize, dict_hash_and_tag0);
let mut match_index = *ht.add(hash0);
let mut curr = idx(ip0);
let mut step = step_size;
let mut next_step = ip0.wrapping_add(K_STEP_INCR);
loop {
let mtch = base.wrapping_add(match_index as usize);
let rep_index = curr.wrapping_add(1).wrapping_sub(offset_1);
let rep_match = rep_pos(rep_index);
let hash1 = hash(ip1);
let dict_hash_and_tag1 = dict_hash(ip1);
*ht.add(hash0) = curr;
if index_overlap_check(prefix_start_index, rep_index) && {
chk(rep_match, 4);
read32(rep_match) == read32(ip0.add(1))
} {
let rep_match_end = if rep_index < prefix_start_index {
dict_end
} else {
iend
};
m_length = count_2segments(
ip0.add(1 + 4),
rep_match.add(4),
iend,
rep_match_end,
prefix_start,
) + 4;
ip0 = ip0.add(1);
ss.store_seq(
buf,
anchor as usize - bp as usize,
ip0 as usize - anchor as usize,
end,
REPCODE1_TO_OFFBASE,
m_length,
);
break;
}
if dict_tags_match {
let dict_match_index = dict_match_index_and_tag >> SHORT_CACHE_TAG_BITS;
let mut dict_match = dict_base.wrapping_add(dict_match_index as usize);
if dict_match_index > dict_start_index && {
chk(dict_match, 4);
read32(dict_match) == read32(ip0)
} {
if match_index <= prefix_start_index {
let offset = curr - dict_match_index - dict_index_delta;
let mut ml = count_2segments(
ip0.add(4),
dict_match.add(4),
iend,
dict_end,
prefix_start,
) + 4;
while ((ip0 > anchor) & (dict_match > dict_start))
&& *ip0.sub(1) == *dict_match.sub(1)
{
ip0 = ip0.sub(1);
dict_match = dict_match.sub(1);
ml += 1;
} offset_2 = offset_1;
offset_1 = offset;
m_length = ml;
ss.store_seq(
buf,
anchor as usize - bp as usize,
ip0 as usize - anchor as usize,
end,
offset_to_offbase(offset),
m_length,
);
break;
}
}
}
#[cfg(debug_assertions)]
if match_index >= prefix_start_index {
chk(mtch, 4);
}
if then_valid(
read32(ip0) == read32(select_addr(match_index >= prefix_start_index, mtch)),
match_index >= prefix_start_index,
) {
let mut mtch = mtch;
let offset = (ip0 as usize - mtch as usize) as u32;
let mut ml = count(ip0.add(4), mtch.add(4), iend) + 4;
while ((ip0 > anchor) & (mtch > prefix_start)) && *ip0.sub(1) == *mtch.sub(1) {
ip0 = ip0.sub(1);
mtch = mtch.sub(1);
ml += 1;
} offset_2 = offset_1;
offset_1 = offset;
m_length = ml;
ss.store_seq(
buf,
anchor as usize - bp as usize,
ip0 as usize - anchor as usize,
end,
offset_to_offbase(offset),
m_length,
);
break;
}
dict_match_index_and_tag =
*dict_hash_table.add(dict_hash_and_tag1 >> SHORT_CACHE_TAG_BITS);
dict_tags_match =
compare_packed_tags(dict_match_index_and_tag as usize, dict_hash_and_tag1);
match_index = *ht.add(hash1);
if ip1 >= next_step {
step += 1;
next_step = next_step.wrapping_add(K_STEP_INCR);
}
ip0 = ip1;
ip1 = ip1.wrapping_add(step);
if ip1 > ilimit {
break 'outer;
}
curr = idx(ip0);
hash0 = hash1;
}
debug_assert!(m_length != 0);
ip0 = ip0.add(m_length);
anchor = ip0;
if ip0 <= ilimit {
debug_assert!(base.wrapping_add(curr as usize + 2) > istart);
*ht.add(hash(base.wrapping_add(curr as usize + 2))) = curr + 2;
*ht.add(hash(ip0.sub(2))) = idx(ip0.sub(2));
while ip0 <= ilimit {
let current2 = idx(ip0);
let rep_index2 = current2.wrapping_sub(offset_2);
let rep_match2 = rep_pos(rep_index2);
if index_overlap_check(prefix_start_index, rep_index2) && {
chk(rep_match2, 4);
read32(rep_match2) == read32(ip0)
} {
let rep_end2 = if rep_index2 < prefix_start_index {
dict_end
} else {
iend
};
let rep_length2 = count_2segments(
ip0.add(4),
rep_match2.add(4),
iend,
rep_end2,
prefix_start,
) + 4;
core::mem::swap(&mut offset_1, &mut offset_2);
ss.store_seq(
buf,
anchor as usize - bp as usize,
0,
end,
REPCODE1_TO_OFFBASE,
rep_length2,
);
*ht.add(hash(ip0)) = current2;
ip0 = ip0.add(rep_length2);
anchor = ip0;
continue;
}
break;
}
}
debug_assert!(ip0 == anchor);
ip1 = ip0.wrapping_add(step_size);
}
}
rep[0] = offset_1;
rep[1] = offset_2;
iend as usize - anchor as usize
}
#[cfg(test)]
pub(super) mod tests {
use super::super::params::{CParams, one_shot_cparams};
use super::super::seq_store::{
MINMATCH, REP_START_VALUE, SeqStore, offbase_is_offset, offbase_to_offset,
};
use super::*;
use alloc::vec;
use alloc::vec::Vec;
fn replay(ss: &SeqStore, rep: &mut [u32; 3], out: &mut Vec<u8>) {
let lits = ss.literals();
let mut lp = 0;
for i in 0..ss.nb_seq {
let len = ss.sequence_length(i);
let s = ss.sequences[i];
out.extend_from_slice(&lits[lp..lp + len.lit_length as usize]);
lp += len.lit_length as usize;
let ll0 = len.lit_length == 0;
let offset = if offbase_is_offset(s.off_base) {
let o = offbase_to_offset(s.off_base);
rep[2] = rep[1];
rep[1] = rep[0];
rep[0] = o;
o
} else {
let r = s.off_base - 1 + ll0 as u32;
if r == 0 {
rep[0]
} else {
let o = if r == 3 { rep[0] - 1 } else { rep[r as usize] };
if r >= 2 {
rep[2] = rep[1];
}
rep[1] = rep[0];
rep[0] = o;
o
}
};
assert!(len.match_length >= MINMATCH);
let from = out.len() - offset as usize;
for k in 0..len.match_length as usize {
let b = out[from + k];
out.push(b);
}
}
out.extend_from_slice(&lits[lp..]);
}
pub(crate) fn roundtrip(src: &[u8], cparams: CParams, block_size: usize) -> usize {
let mut ms = MatchState::new(cparams);
let mut ss = SeqStore::new(block_size, cparams.min_match);
ms.update_window(0, src.len());
let mut rep = REP_START_VALUE;
let mut dec_rep = REP_START_VALUE;
let mut out = Vec::new();
let mut pos = 0;
let mut nb_seq = 0;
while pos < src.len() {
let bs = block_size.min(src.len() - pos);
ms.prepare_block(pos, bs);
let mut next_rep = rep;
if build_seq_store(&mut ms, &mut ss, &mut next_rep, src, pos, pos + bs) {
replay(&ss, &mut dec_rep, &mut out);
rep = next_rep;
nb_seq += ss.nb_seq;
assert_eq!(&dec_rep[..2], &rep[..2]);
} else {
out.extend_from_slice(&src[pos..pos + bs]);
}
assert_eq!(&out[..], &src[..pos + bs], "block at {pos}");
pos += bs;
}
nb_seq
}
pub(crate) fn xorshift(state: &mut u64) -> u64 {
*state ^= *state << 13;
*state ^= *state >> 7;
*state ^= *state << 17;
*state
}
pub(crate) fn texty(n: usize, seed: u64) -> Vec<u8> {
const WORDS: [&[u8]; 12] = [
b"the ",
b"quick ",
b"brown ",
b"fox ",
b"jumps ",
b"over ",
b"lazy ",
b"dog ",
b"zstd ",
b"compress ",
b"block ",
b"\n",
];
let mut s = seed | 1;
let mut v = Vec::with_capacity(n + 16);
while v.len() < n {
let r = xorshift(&mut s);
if r.is_multiple_of(17) {
v.push((r >> 8) as u8);
} else {
v.extend_from_slice(WORDS[(r >> 16) as usize % WORDS.len()]);
}
}
v.truncate(n);
v
}
pub(crate) fn roundtrip_ring(
src: &[u8],
cparams: CParams,
block_size: usize,
) -> (usize, usize) {
let window = 1usize << cparams.window_log;
let ring_size = window + block_size;
let mut ring = alloc::vec![0u8; ring_size + 32];
let mut ms = MatchState::new(cparams);
let mut ss = SeqStore::new(block_size, cparams.min_match);
let mut rep = REP_START_VALUE;
let mut dec_rep = REP_START_VALUE;
let mut out = Vec::new();
let (mut pos, mut at, mut nb_seq, mut ext) = (0, 0, 0, 0);
while pos < src.len() {
let bs = block_size.min(src.len() - pos);
if at + bs > ring_size {
at = 0;
}
ring[at..at + bs].copy_from_slice(&src[pos..pos + bs]);
ms.update_window(at, bs);
ms.prepare_block(at, bs);
ext += usize::from(ms.window.has_ext_dict());
let mut next_rep = rep;
if build_seq_store(&mut ms, &mut ss, &mut next_rep, &ring, at, at + bs) {
replay(&ss, &mut dec_rep, &mut out);
rep = next_rep;
nb_seq += ss.nb_seq;
assert_eq!(&dec_rep[..2], &rep[..2]);
} else {
out.extend_from_slice(&src[pos..pos + bs]);
}
assert_eq!(&out[..], &src[..pos + bs], "block at {pos}");
pos += bs;
at += bs;
}
(nb_seq, ext)
}
#[test]
fn roundtrip_ring_variants() {
let mut src = texty(150_000, 7);
src.extend_from_slice(&random(5000, 8));
src.extend_from_slice(&src.clone()[..60_000]);
src.extend_from_slice(&texty(100_000, 17));
for mls in 3..=8 {
for (window_log, bs) in [(10, 1 << 10), (14, 3000), (16, 1 << 15), (17, 1 << 17)] {
for target_length in [0, 1, 7] {
let cp = CParams {
window_log,
chain_log: 16,
hash_log: 14,
search_log: 1,
min_match: mls,
target_length,
strategy: Strategy::Fast,
};
let (n, ext) = roundtrip_ring(&src, cp, bs);
assert!(
n > 1000 && ext > 0,
"mls {mls} wlog {window_log}: {n} {ext}"
);
}
}
}
}
pub(crate) fn random(n: usize, seed: u64) -> Vec<u8> {
let mut s = seed | 1;
(0..n).map(|_| xorshift(&mut s) as u8).collect()
}
#[test]
fn roundtrip_levels() {
let inputs: [Vec<u8>; 7] = [
texty(1000, 1),
texty(100_000, 2),
texty(300_000, 3),
random(50_000, 4),
vec![0u8; 200_000],
(0..70_000u32).map(|i| (i % 251) as u8).collect(),
{
let mut v = random(20_000, 5);
v.extend_from_within(..);
v.extend_from_slice(&texty(30_000, 6));
v
},
];
for src in &inputs {
for level in [-50, -5, -1, 1, 2] {
let cp = one_shot_cparams(level, src.len() as u64);
if cp.strategy != Strategy::Fast {
continue; }
let bs = super::super::params::block_size_max(&cp, src.len() as u64);
roundtrip(src, cp, bs);
}
}
}
#[test]
fn roundtrip_all_variants() {
let mut src = texty(150_000, 7);
src.extend_from_slice(&random(5000, 8));
src.extend_from_slice(&src.clone()[..40_000]);
for mls in 3..=8 {
for window_log in [10, 14, 18, 19, 22] {
for target_length in [0, 1, 7] {
let cp = CParams {
window_log,
chain_log: 16,
hash_log: 14,
search_log: 1,
min_match: mls,
target_length,
strategy: Strategy::Fast,
};
let n = roundtrip(&src, cp, (1 << 17).min(1 << window_log));
assert!(n > 1000, "mls {mls} wlog {window_log}: {n} sequences");
}
}
}
}
#[test]
fn small_blocks() {
let src = texty(5000, 9);
let cp = one_shot_cparams(1, src.len() as u64);
for bs in [1, 6, 7, 8, 9, 20, 33, 100, 1000] {
roundtrip(&src, cp, bs);
}
for n in 0..40 {
let s = texty(n, 10);
roundtrip(&s, one_shot_cparams(1, n as u64), 1 << 17);
}
}
#[test]
fn repetitive_matches() {
let src = vec![0u8; 300_000];
let cp = one_shot_cparams(1, src.len() as u64);
let mut ms = MatchState::new(cp);
let mut ss = SeqStore::new(1 << 17, cp.min_match);
ms.update_window(0, src.len());
let mut rep = REP_START_VALUE;
ms.prepare_block(0, 1 << 17);
assert!(build_seq_store(
&mut ms,
&mut ss,
&mut rep,
&src,
0,
1 << 17
));
assert_eq!(ss.nb_seq, 1);
assert_eq!(ss.sequences[0].off_base, REPCODE1_TO_OFFBASE);
assert_eq!(ss.sequence_length(0).lit_length, 2);
assert_eq!(ss.sequence_length(0).match_length, (1 << 17) - 2);
assert_eq!(rep, [1, 4, 8]);
}
#[test]
fn window_indices() {
let mut w = Window::new();
assert!(w.is_empty());
assert!(!w.update(0, 100, false));
assert_eq!(w.index(0), WINDOW_START_INDEX);
assert_eq!((w.dict_limit, w.low_limit), (2, 2));
assert!(w.update(100, 50, false));
assert_eq!(w.index(149), 151);
assert!(!w.update(1000, 50, false));
assert_eq!(w.dict_limit, 152);
assert_eq!(w.low_limit, 2);
assert_eq!(w.index(1000), 152);
assert!(w.has_ext_dict());
let mut w = Window::new();
w.update(0, 1 << 20, false);
let mut lde = 0;
w.enforce_max_dist(1 << 19, 1 << 17, &mut lde, &mut false);
assert_eq!(w.low_limit, (1 << 19) + 2 - (1 << 17));
assert_eq!(w.dict_limit, w.low_limit);
}
#[test]
fn overflow_correction() {
let cp = one_shot_cparams(1, 1 << 30);
let mut ms = MatchState::new(cp);
let big = (CURRENT_MAX as usize) + 1000;
ms.window.update(0, big + (1 << 17), false);
ms.hash_table[0] = 5;
ms.hash_table[1] = (big - 10) as u32 + 2;
let start = big;
ms.prepare_block(start, 1 << 17);
assert_eq!(ms.window.nb_overflow_corrections, 1);
let curr = ms.window.index(start);
let max_dist = 1u32 << cp.window_log;
assert!(curr < 2 * max_dist + (1 << cp.chain_log) + 2);
assert_eq!(ms.hash_table[0], 0);
assert_eq!(ms.window.index(big - 10), ms.hash_table[1]);
assert!(ms.window.low_limit >= WINDOW_START_INDEX);
}
#[test]
fn fill_table() {
let src = texty(1000, 11);
let cp = one_shot_cparams(1, 1000);
let mut ms = MatchState::new(cp);
ms.update_window(0, src.len());
ms.fill_hash_table(&src, src.len(), TableLoadMethod::Fast);
let h = super::super::seq_store::hash_at(&src, 3, cp.hash_log, cp.min_match);
assert!(ms.hash_table[h] >= 5); assert!(
ms.hash_table
.iter()
.all(|&v| v == 0 || (2..1002).contains(&v))
);
}
#[test]
fn keep_indices() {
let src = texty(1000, 11);
let cp = one_shot_cparams(1, 1000);
let mut ms = MatchState::new(cp);
ms.update_window(0, src.len());
ms.fill_hash_table(&src, src.len(), TableLoadMethod::Fast);
let filled = ms.hash_table.iter().filter(|&&v| v != 0).count();
assert!(filled > 0);
ms.reset_keep_indices(cp, false);
assert!(!ms.window.has_ext_dict());
assert_eq!(ms.window.dict_limit, 1002);
assert_eq!(ms.next_to_update, 1002);
assert_eq!(ms.hash_table.iter().filter(|&&v| v != 0).count(), filled);
ms.update_window(0, src.len());
assert_eq!(ms.window.index(0), 1002);
assert_eq!(ms.window.dict_limit, 1002);
assert!(!ms.window.has_ext_dict());
let cp2 = one_shot_cparams(3, 1000);
ms.reset_keep_indices(cp2, false);
assert_eq!(ms.window, Window::new());
assert!(ms.hash_table.iter().all(|&v| v == 0));
ms.reset_keep_indices(cp, false);
ms.window.next_src = ms
.window
.base
.wrapping_add((CURRENT_MAX - INDEXOVERFLOW_MARGIN) as usize + 1);
ms.hash_table[0] = 7;
ms.reset_keep_indices(cp, false);
assert_eq!(ms.window, Window::new());
assert_eq!(ms.hash_table[0], 0);
}
}