use super::compress::EntropyTables;
use super::fast::{DmsView, ExtWindow, HASH_READ_SIZE, MatchState, hash_mls, index_overlap_check};
use super::hist::hist_count_simple;
use super::huf_enc::HufRepeat;
use super::ldm::RawSeq;
use super::params::{BLOCKSIZE_MAX, Strategy};
use super::seq_store::{
MAX_LL, MAX_ML, MAX_OFF, MINMATCH, REP_NUM, SeqStore, count, count_2segments, hash3_ptr,
highbit32, ll_code, ml_code, offset_to_offbase, read32, update_rep,
};
use crate::cpu::prefetch_l1;
use crate::fse::{LL_BITS, ML_BITS};
use alloc::vec;
use alloc::vec::Vec;
pub(crate) const OPT_NUM: u32 = 1 << 12;
const OPT_SIZE: usize = OPT_NUM as usize + 3;
const LITFREQ_ADD: u32 = 2;
const MAX_PRICE: i32 = 1 << 30;
const PREDEF_THRESHOLD: usize = 8;
const BITCOST_ACCURACY: u32 = 8;
const BITCOST_MULTIPLIER: u32 = 1 << BITCOST_ACCURACY;
const MAX_LIT: usize = 255;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PriceType {
Dynamic,
Predef,
}
#[derive(Clone, Copy, Debug, Default)]
struct Optimal {
price: i32,
off: u32,
mlen: u32,
litlen: u32,
rep: [u32; 3],
}
#[derive(Clone, Debug)]
pub(crate) struct DictCosts {
lit_freq: [u32; MAX_LIT + 1],
lit_length_freq: [u32; MAX_LL as usize + 1],
match_length_freq: [u32; MAX_ML as usize + 1],
off_code_freq: [u32; MAX_OFF as usize + 1],
}
impl DictCosts {
pub(crate) fn new(e: &EntropyTables) -> Option<alloc::boxed::Box<DictCosts>> {
if e.huf.repeat != HufRepeat::Valid {
return None;
}
let freq = |bit_cost: u32, scale_log: u32| {
if bit_cost != 0 {
1u32.wrapping_shl(scale_log.wrapping_sub(bit_cost))
} else {
1 }
};
let mut c = alloc::boxed::Box::new(DictCosts {
lit_freq: [0; MAX_LIT + 1],
lit_length_freq: [0; MAX_LL as usize + 1],
match_length_freq: [0; MAX_ML as usize + 1],
off_code_freq: [0; MAX_OFF as usize + 1],
});
for (lit, f) in c.lit_freq.iter_mut().enumerate() {
*f = freq(e.huf.table.nb_bits(lit as u32), 11);
}
for (ll, f) in c.lit_length_freq.iter_mut().enumerate() {
*f = freq(e.fse.ll.max_nb_bits(ll as u32), 10);
}
for (ml, f) in c.match_length_freq.iter_mut().enumerate() {
*f = freq(e.fse.ml.max_nb_bits(ml as u32), 10);
}
for (of, f) in c.off_code_freq.iter_mut().enumerate() {
*f = freq(e.fse.of.max_nb_bits(of as u32), 10);
}
Some(c)
}
}
#[derive(Clone, Copy, Debug, Default)]
struct Match {
off: u32,
len: u32,
}
#[derive(Clone, Debug)]
pub(crate) struct OptStats {
lit_freq: [u32; MAX_LIT + 1],
lit_length_freq: [u32; MAX_LL as usize + 1],
match_length_freq: [u32; MAX_ML as usize + 1],
off_code_freq: [u32; MAX_OFF as usize + 1],
lit_sum: u32,
pub(crate) lit_length_sum: u32,
match_length_sum: u32,
off_code_sum: u32,
lit_sum_base_price: u32,
lit_length_sum_base_price: u32,
match_length_sum_base_price: u32,
off_code_sum_base_price: u32,
price_type: PriceType,
ll_code_price: [u32; MAX_LL as usize + 1],
ml_code_price: [u32; MAX_ML as usize + 1],
ml_len_price: [u32; 128],
dirty_ll: u64,
dirty_ml: u64,
}
pub(crate) struct OptState {
pub(crate) stats: OptStats,
price_table: Vec<Optimal>,
match_table: Vec<Match>,
pub(crate) dict_costs: Option<alloc::boxed::Box<DictCosts>>,
}
impl core::fmt::Debug for OptState {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("OptState")
.field("stats", &self.stats)
.finish_non_exhaustive()
}
}
impl OptState {
pub(crate) fn new() -> Self {
OptState {
stats: OptStats {
lit_freq: [0; MAX_LIT + 1],
lit_length_freq: [0; MAX_LL as usize + 1],
match_length_freq: [0; MAX_ML as usize + 1],
off_code_freq: [0; MAX_OFF as usize + 1],
lit_sum: 0,
lit_length_sum: 0,
match_length_sum: 0,
off_code_sum: 0,
lit_sum_base_price: 0,
lit_length_sum_base_price: 0,
match_length_sum_base_price: 0,
off_code_sum_base_price: 0,
price_type: PriceType::Dynamic,
ll_code_price: [0; MAX_LL as usize + 1],
ml_code_price: [0; MAX_ML as usize + 1],
ml_len_price: [0; 128],
dirty_ll: 0,
dirty_ml: 0,
},
price_table: vec![Optimal::default(); OPT_SIZE],
match_table: vec![Match::default(); OPT_SIZE],
dict_costs: None,
}
}
}
#[inline(always)]
fn bit_weight(stat: u32) -> u32 {
highbit32(stat + 1) * BITCOST_MULTIPLIER
}
#[inline(always)]
fn frac_weight(raw_stat: u32) -> u32 {
let stat = raw_stat + 1;
let hb = highbit32(stat);
let b_weight = hb * BITCOST_MULTIPLIER;
let f_weight = (stat << BITCOST_ACCURACY) >> hb;
debug_assert!(hb + BITCOST_ACCURACY < 31);
b_weight + f_weight
}
#[inline(always)]
fn weight<const OPT_LEVEL: u32>(stat: u32) -> u32 {
if OPT_LEVEL > 0 {
frac_weight(stat)
} else {
bit_weight(stat)
}
}
#[rustfmt::skip]
const ML_CODE_BASES: [u8; 44] = [
0, 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, 34, 36, 38, 40, 44, 48, 56, 64, 80, 96, 128,
];
fn downscale_stats(table: &mut [u32], shift: u32, base1: bool) -> u32 {
debug_assert!(shift < 30);
let mut sum = 0u32;
for t in table.iter_mut() {
let base = if base1 { 1 } else { u32::from(*t > 0) };
let new_stat = base + (*t >> shift);
sum += new_stat;
*t = new_stat;
}
sum
}
fn scale_stats(table: &mut [u32], log_target: u32) -> u32 {
let prev_sum: u32 = table.iter().fold(0u32, |a, &b| a.wrapping_add(b));
let factor = prev_sum >> log_target;
debug_assert!(log_target < 30);
if factor <= 1 {
return prev_sum;
}
downscale_stats(table, highbit32(factor), true)
}
impl OptStats {
fn set_base_prices<const OPT_LEVEL: u32>(&mut self) {
self.lit_sum_base_price = weight::<OPT_LEVEL>(self.lit_sum);
self.lit_length_sum_base_price = weight::<OPT_LEVEL>(self.lit_length_sum);
self.match_length_sum_base_price = weight::<OPT_LEVEL>(self.match_length_sum);
self.off_code_sum_base_price = weight::<OPT_LEVEL>(self.off_code_sum);
let mut d = core::mem::take(&mut self.dirty_ll);
while d != 0 {
let code = d.trailing_zeros() as usize;
d &= d - 1;
self.ll_code_price[code] = (u32::from(LL_BITS[code]) * BITCOST_MULTIPLIER)
.wrapping_sub(weight::<OPT_LEVEL>(self.lit_length_freq[code]));
}
let dynamic = self.price_type == PriceType::Dynamic;
let mut d = core::mem::take(&mut self.dirty_ml);
while d != 0 {
let code = d.trailing_zeros() as usize;
d &= d - 1;
let p = (u32::from(ML_BITS[code]) * BITCOST_MULTIPLIER)
.wrapping_sub(weight::<OPT_LEVEL>(self.match_length_freq[code]));
self.ml_code_price[code] = p;
if dynamic && code < ML_CODE_BASES.len() - 1 {
let (lo, hi) = (ML_CODE_BASES[code], ML_CODE_BASES[code + 1]);
self.ml_len_price[lo as usize..hi as usize].fill(p);
}
}
}
fn set_all_prices<const OPT_LEVEL: u32>(&mut self) {
self.dirty_ll = (1 << (MAX_LL + 1)) - 1;
self.dirty_ml = (1 << (MAX_ML + 1)) - 1;
if self.price_type == PriceType::Predef {
for (ml_base, p) in self.ml_len_price.iter_mut().enumerate() {
*p = weight::<OPT_LEVEL>(ml_base as u32);
}
}
self.set_base_prices::<OPT_LEVEL>();
}
#[inline(always)]
fn match_off_price<const OPT_LEVEL: u32>(&self, off_base: u32) -> u32 {
let off_code = highbit32(off_base);
if self.price_type == PriceType::Predef {
return (16 + off_code) * BITCOST_MULTIPLIER;
}
let mut price = (off_code * BITCOST_MULTIPLIER).wrapping_add(
self.off_code_sum_base_price
.wrapping_sub(weight::<OPT_LEVEL>(self.off_code_freq[off_code as usize])),
);
if OPT_LEVEL < 2 && off_code >= 20 {
price = price.wrapping_add((off_code - 19) * 2 * BITCOST_MULTIPLIER);
}
price
.wrapping_add(BITCOST_MULTIPLIER / 5)
.wrapping_add(self.match_length_sum_base_price)
}
#[inline(always)]
fn ml_len_price<const OPT_LEVEL: u32>(&self, match_length: u32) -> u32 {
debug_assert!(match_length >= MINMATCH);
let ml_base = match_length - MINMATCH;
if ml_base < 128 {
return self.ml_len_price[ml_base as usize];
}
if self.price_type == PriceType::Predef {
return weight::<OPT_LEVEL>(ml_base);
}
self.ml_code_price[(highbit32(ml_base) + 36).min(u32::from(MAX_ML)) as usize]
}
fn rescale_freqs<const OPT_LEVEL: u32>(&mut self, src: &[u8], dict: Option<&DictCosts>) {
self.price_type = PriceType::Dynamic;
if self.lit_length_sum == 0 {
if src.len() <= PREDEF_THRESHOLD {
self.price_type = PriceType::Predef;
}
if let Some(d) = dict {
self.price_type = PriceType::Dynamic;
self.lit_freq = d.lit_freq;
self.lit_sum = d.lit_freq.iter().sum();
self.lit_length_freq = d.lit_length_freq;
self.lit_length_sum = d.lit_length_freq.iter().sum();
self.match_length_freq = d.match_length_freq;
self.match_length_sum = d.match_length_freq.iter().sum();
self.off_code_freq = d.off_code_freq;
self.off_code_sum = d.off_code_freq.iter().sum();
self.set_all_prices::<OPT_LEVEL>();
return;
}
let mut lit = MAX_LIT as u32;
hist_count_simple(&mut self.lit_freq, &mut lit, src);
self.lit_sum = downscale_stats(&mut self.lit_freq, 8, false);
const BASE_LL_FREQS: [u32; MAX_LL as usize + 1] = [
4, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
];
self.lit_length_freq = BASE_LL_FREQS;
self.lit_length_sum = BASE_LL_FREQS.iter().sum();
self.match_length_freq = [1; MAX_ML as usize + 1];
self.match_length_sum = MAX_ML as u32 + 1;
const BASE_OFC_FREQS: [u32; MAX_OFF as usize + 1] = [
6, 2, 1, 1, 2, 3, 4, 4, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1,
];
self.off_code_freq = BASE_OFC_FREQS;
self.off_code_sum = BASE_OFC_FREQS.iter().sum();
} else {
self.lit_sum = scale_stats(&mut self.lit_freq, 12);
self.lit_length_sum = scale_stats(&mut self.lit_length_freq, 11);
self.match_length_sum = scale_stats(&mut self.match_length_freq, 11);
self.off_code_sum = scale_stats(&mut self.off_code_freq, 11);
}
self.set_all_prices::<OPT_LEVEL>();
}
#[inline(always)]
fn lit_price<const OPT_LEVEL: u32>(&self, lit: u8) -> i32 {
if self.price_type == PriceType::Predef {
return (6 * BITCOST_MULTIPLIER) as i32; }
let lit_price_max = self.lit_sum_base_price.wrapping_sub(BITCOST_MULTIPLIER);
debug_assert!(self.lit_sum_base_price >= BITCOST_MULTIPLIER);
let lit_price = weight::<OPT_LEVEL>(self.lit_freq[lit as usize]).min(lit_price_max);
self.lit_sum_base_price.wrapping_sub(lit_price) as i32
}
#[inline(always)]
fn ll_price<const OPT_LEVEL: u32>(&self, lit_length: u32) -> i32 {
debug_assert!(lit_length as usize <= BLOCKSIZE_MAX);
if self.price_type == PriceType::Predef {
return weight::<OPT_LEVEL>(lit_length) as i32;
}
if lit_length as usize == BLOCKSIZE_MAX {
return BITCOST_MULTIPLIER as i32 + self.ll_price::<OPT_LEVEL>(lit_length - 1);
}
self.ll_code_price[ll_code(lit_length) as usize]
.wrapping_add(self.lit_length_sum_base_price) as i32
}
#[inline(always)]
fn ll_incprice<const OPT_LEVEL: u32>(&self, lit_length: u32) -> i32 {
self.ll_price::<OPT_LEVEL>(lit_length) - self.ll_price::<OPT_LEVEL>(lit_length - 1)
}
#[inline(always)]
fn match_price<const OPT_LEVEL: u32>(&self, off_base: u32, match_length: u32) -> i32 {
self.match_off_price::<OPT_LEVEL>(off_base)
.wrapping_add(self.ml_len_price::<OPT_LEVEL>(match_length)) as i32
}
#[inline]
fn update_stats(&mut self, literals: &[u8], off_base: u32, match_length: u32) {
for &l in literals {
self.lit_freq[l as usize] += LITFREQ_ADD;
}
self.lit_sum += literals.len() as u32 * LITFREQ_ADD;
let ll = ll_code(literals.len() as u32) as usize;
self.lit_length_freq[ll] += 1;
self.lit_length_sum += 1;
let off_code = highbit32(off_base) as usize;
debug_assert!(off_code <= MAX_OFF as usize);
self.off_code_freq[off_code] += 1;
self.off_code_sum += 1;
let ml = ml_code(match_length - MINMATCH) as usize;
self.match_length_freq[ml] += 1;
self.match_length_sum += 1;
self.dirty_ll |= 1 << ll;
self.dirty_ml |= 1 << ml;
}
}
#[inline(always)]
fn new_rep(rep: [u32; 3], off_base: u32, ll0: bool) -> [u32; 3] {
let mut r = rep;
update_rep(&mut r, off_base, ll0);
r
}
struct Bt {
base: *const u8,
hash_table: *mut u32,
bt: *mut u32,
hash_table3: *mut u32,
hash_log: u32,
hash_log3: u32,
bt_mask: u32,
search_log: u32,
window_log: u32,
low_limit: u32,
dict_limit: u32,
loaded_dict_end: u32,
next_to_update: u32,
sufficient_len: u32,
lowest: *const u8,
iend: *const u8,
dict_base: *const u8,
dict_lowest: *const u8,
dict_end: *const u8,
prefix_start: *const u8,
dms: OptDms,
}
#[derive(Clone, Copy)]
struct OptDms {
hash_table: *const u32,
bt: *const u32,
hash_log: u32,
bt_mask: u32,
low_limit: u32,
high_limit: u32,
}
impl OptDms {
const NONE: OptDms = OptDms {
hash_table: core::ptr::null(),
bt: core::ptr::null(),
hash_log: 0,
bt_mask: 0,
low_limit: 0,
high_limit: 0,
};
}
impl Bt {
#[inline(always)]
fn idx(&self, p: *const u8) -> u32 {
(p as usize).wrapping_sub(self.base as usize) as u32
}
#[inline(always)]
fn pos(&self, i: u32) -> *const u8 {
self.base.wrapping_add(i as usize)
}
#[inline(always)]
fn chk(&self, p: *const u8, n: usize) {
let (p, e) = (p as usize, (p as usize).wrapping_add(n));
debug_assert!(
(p >= self.lowest as usize && e <= self.iend as usize)
|| (p >= self.dict_lowest as usize && e <= self.dict_end as usize),
"read out of the window"
);
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn count_ext(&self, ip: *const u8, m: *const u8, ilimit: *const u8) -> usize {
self.chk(m, 0);
unsafe { count_2segments(ip, m, ilimit, self.dict_end, self.prefix_start) }
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn tree_count<const EXT: bool>(
&self,
ip: *const u8,
match_index: u32,
match_length: usize,
iend: *const u8,
) -> (usize, *const u8) {
unsafe {
if !EXT {
let m = self.pos(match_index);
self.chk(m, 0);
let ml = match_length + count(ip.add(match_length), m.add(match_length), iend);
return (ml, m.add(ml));
}
if match_index as usize + match_length >= self.dict_limit as usize {
let mp = self.base.wrapping_add(match_index as usize + match_length);
self.chk(mp, 0);
let n = count(ip.add(match_length), mp, iend);
(match_length + n, mp.add(n))
} else {
let dm = self.dict_base.wrapping_add(match_index as usize);
let ml =
match_length + self.count_ext(ip.add(match_length), dm.add(match_length), iend);
let m_ml = if match_index as usize + ml >= self.dict_limit as usize {
self.base.wrapping_add(match_index as usize + ml)
} else {
dm.add(ml)
};
(ml, m_ml)
}
}
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn prefetch_next<const MLS: u32>(&self, ip: *const u8, iend: *const u8) {
let left = (iend as usize).saturating_sub(ip as usize);
unsafe {
if left < 1 + HASH_READ_SIZE {
return;
}
let nip = ip.add(1);
let curr = self.idx(ip);
let head = *self.hash_table.add(hash_mls::<MLS>(nip, self.hash_log));
prefetch_l1(self.bt.add(2 * (head & self.bt_mask) as usize).cast());
prefetch_l1(self.pos(head));
prefetch_l1(self.bt.add(2 * ((curr + 1) & self.bt_mask) as usize).cast());
if MLS == 3 {
prefetch_l1(self.hash_table3.add(hash3_ptr(nip, self.hash_log3)).cast());
}
if left >= 2 + HASH_READ_SIZE {
prefetch_l1(
self.hash_table
.add(hash_mls::<MLS>(ip.add(2), self.hash_log))
.cast(),
);
}
}
}
#[inline(always)]
fn lowest_match_index(&self, curr: u32) -> u32 {
let max_distance = 1u32 << self.window_log;
let lowest_valid = self.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
}
}
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn read_minmatch<const LENGTH: u32>(p: *const u8) -> u32 {
let v = unsafe { read32(p) };
if LENGTH == 3 {
if cfg!(target_endian = "little") {
v << 8
} else {
v >> 8
}
} else {
v
}
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn insert_and_find_first_index_hash3(
s: &Bt,
next_to_update3: &mut u32,
ip: *const u8,
) -> u32 {
let hash_log3 = s.hash_log3;
let mut idx = *next_to_update3;
let target = s.idx(ip);
unsafe {
s.chk(ip, 4);
let hash3 = hash3_ptr(ip, hash_log3);
while idx < target {
let p = s.pos(idx);
s.chk(p, 4);
*s.hash_table3.add(hash3_ptr(p, hash_log3)) = idx;
idx += 1;
}
*next_to_update3 = target;
*s.hash_table3.add(hash3)
}
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn insert_bt1<const MLS: u32, const EXT: bool>(
s: &Bt,
ip: *const u8,
iend: *const u8,
target: u32,
) -> u32 {
let bt = s.bt;
let bt_mask = s.bt_mask;
let curr = s.idx(ip);
let bt_low = curr.saturating_sub(bt_mask);
let mut common_length_smaller = 0usize;
let mut common_length_larger = 0usize;
let mut dummy32 = 0u32;
let dummy: *mut u32 = &mut dummy32;
let window_low = s.lowest_match_index(target);
let mut match_end_idx = curr + 8 + 1;
let mut best_length = 8usize;
let mut nb_compares = 1u32 << s.search_log;
debug_assert!(curr <= target);
debug_assert!(window_low > 0);
unsafe {
s.chk(ip, 8);
s.prefetch_next::<MLS>(ip, iend);
let h = hash_mls::<MLS>(ip, s.hash_log);
let mut match_index = *s.hash_table.add(h);
let mut smaller_ptr = bt.add(2 * (curr & bt_mask) as usize);
let mut larger_ptr = smaller_ptr.add(1);
*s.hash_table.add(h) = curr;
while nb_compares > 0 && match_index >= window_low {
let next_ptr = bt.add(2 * (match_index & bt_mask) as usize);
let mut match_length = common_length_smaller.min(common_length_larger);
debug_assert!(match_index < curr);
let m_ml;
(match_length, m_ml) = s.tree_count::<EXT>(ip, match_index, match_length, iend);
if match_length > best_length {
best_length = match_length;
if match_length > (match_end_idx - match_index) as usize {
match_end_idx = match_index + match_length as u32;
}
}
if ip.add(match_length) == iend {
break;
}
if *m_ml < *ip.add(match_length) {
*smaller_ptr = match_index;
common_length_smaller = match_length;
if match_index <= bt_low {
smaller_ptr = dummy;
break;
}
smaller_ptr = next_ptr.add(1);
match_index = *next_ptr.add(1);
} else {
*larger_ptr = match_index;
common_length_larger = match_length;
if match_index <= bt_low {
larger_ptr = dummy;
break;
}
larger_ptr = next_ptr;
match_index = *next_ptr;
}
nb_compares -= 1;
}
*smaller_ptr = 0;
*larger_ptr = 0;
}
let positions = if best_length > 384 {
192.min((best_length - 384) as u32) } else {
0
};
debug_assert!(match_end_idx > curr + 8);
positions.max(match_end_idx - (curr + 8))
}
#[allow(unsafe_code)]
#[inline(always)]
unsafe fn update_tree<const MLS: u32, const EXT: bool>(s: &mut Bt, ip: *const u8, iend: *const u8) {
let target = s.idx(ip);
let mut idx = s.next_to_update;
while idx < target {
let forward = unsafe { insert_bt1::<MLS, EXT>(s, s.pos(idx), iend, target) };
debug_assert!(idx < idx.wrapping_add(forward));
idx += forward;
}
s.next_to_update = target;
}
#[allow(unsafe_code, clippy::too_many_arguments)]
#[inline(never)]
unsafe fn get_all_matches<const MLS: u32, const EXT: bool, const DMS: bool>(
s: &mut Bt,
matches: &mut [Match],
next_to_update3: &mut u32,
ip: *const u8,
iend: *const u8,
rep: &[u32; 3],
ll0: u32,
length_to_beat: u32,
) -> u32 {
if (ip as usize) < (s.pos(s.next_to_update) as usize) {
return 0; }
let ilimit = iend;
let sufficient_len = s.sufficient_len;
let min_match = if MLS == 3 { 3 } else { 4 };
let bt = s.bt;
let bt_mask = s.bt_mask;
let mut common_length_smaller = 0usize;
let mut common_length_larger = 0usize;
let mut dummy32 = 0u32;
let dummy: *mut u32 = &mut dummy32;
let mut mnum = 0usize;
let mut nb_compares = 1u32 << s.search_log;
let mut best_length = (length_to_beat - 1) as usize;
debug_assert!(matches.len() >= OPT_SIZE);
debug_assert!(ll0 <= 1);
unsafe {
s.prefetch_next::<MLS>(ip, iend);
update_tree::<MLS, EXT>(s, ip, iend);
let curr = s.idx(ip);
let dict_limit = s.dict_limit;
let bt_low = curr.saturating_sub(bt_mask);
let window_low = s.lowest_match_index(curr);
let match_low = if window_low != 0 { window_low } else { 1 };
let mut match_end_idx = curr + 8 + 1; s.chk(ip, 8);
let h = hash_mls::<MLS>(ip, s.hash_log);
let mut match_index = *s.hash_table.add(h);
let mut smaller_ptr = bt.add(2 * (curr & bt_mask) as usize);
let mut larger_ptr = smaller_ptr.add(1);
let last_r = REP_NUM + ll0;
for rep_code in ll0..last_r {
let rep_offset = if rep_code == REP_NUM {
rep[0].wrapping_sub(1)
} else {
rep[rep_code as usize]
};
let rep_index = curr.wrapping_sub(rep_offset);
let mut rep_len = 0usize;
debug_assert!(curr >= dict_limit);
if rep_offset.wrapping_sub(1) < curr - dict_limit {
if rep_index >= window_low && {
let r = ip.sub(rep_offset as usize);
s.chk(r, 4);
read_minmatch::<MLS>(ip) == read_minmatch::<MLS>(r)
} {
rep_len = count(
ip.add(min_match),
ip.add(min_match).sub(rep_offset as usize),
ilimit,
) + min_match;
}
} else if EXT {
let rep_match = s.dict_base.wrapping_add(rep_index as usize);
if (rep_offset.wrapping_sub(1) < curr - window_low)
& index_overlap_check(dict_limit, rep_index)
&& {
s.chk(rep_match, 4);
read_minmatch::<MLS>(ip) == read_minmatch::<MLS>(rep_match)
}
{
rep_len = s.count_ext(ip.add(min_match), rep_match.add(min_match), ilimit)
+ min_match;
}
} else if DMS {
let dms_index_delta = window_low.wrapping_sub(s.dms.high_limit);
let rep_match = s
.dict_base
.wrapping_add(rep_index.wrapping_sub(dms_index_delta) as usize);
if (rep_offset.wrapping_sub(1)
< curr.wrapping_sub(s.dms.low_limit.wrapping_add(dms_index_delta)))
& index_overlap_check(dict_limit, rep_index)
&& {
s.chk(rep_match, 4);
read_minmatch::<MLS>(ip) == read_minmatch::<MLS>(rep_match)
}
{
rep_len = s.count_ext(ip.add(min_match), rep_match.add(min_match), ilimit)
+ min_match;
}
}
if rep_len > best_length {
best_length = rep_len;
matches[mnum] = Match {
off: rep_code - ll0 + 1, len: rep_len as u32,
};
mnum += 1;
if (rep_len > sufficient_len as usize) | (ip.add(rep_len) == ilimit) {
return mnum as u32; }
}
}
if MLS == 3 && best_length < MLS as usize {
let match_index3 = insert_and_find_first_index_hash3(s, next_to_update3, ip);
if (match_index3 >= match_low) & (curr.wrapping_sub(match_index3) < (1 << 18)) {
debug_assert!(match_index3 < curr);
let mlen = if !EXT || match_index3 >= dict_limit {
let m = s.pos(match_index3);
s.chk(m, 0);
count(ip, m, ilimit)
} else {
let m = s.dict_base.wrapping_add(match_index3 as usize);
s.count_ext(ip, m, ilimit)
};
if mlen >= MLS as usize {
best_length = mlen;
debug_assert!(mnum == 0); matches[0] = Match {
off: offset_to_offbase(curr - match_index3),
len: mlen as u32,
};
mnum = 1;
if (mlen > sufficient_len as usize) | (ip.add(mlen) == ilimit) {
s.next_to_update = curr + 1; return 1;
}
}
}
}
*s.hash_table.add(h) = curr;
while nb_compares > 0 && match_index >= match_low {
let next_ptr = bt.add(2 * (match_index & bt_mask) as usize);
let mut match_length = common_length_smaller.min(common_length_larger);
debug_assert!(curr > match_index);
let m_ml;
(match_length, m_ml) = s.tree_count::<EXT>(ip, match_index, match_length, ilimit);
if match_length > best_length {
debug_assert!(match_end_idx > match_index);
if match_length > (match_end_idx - match_index) as usize {
match_end_idx = match_index + match_length as u32;
}
best_length = match_length;
matches[mnum] = Match {
off: offset_to_offbase(curr - match_index),
len: match_length as u32,
};
mnum += 1;
if (match_length > OPT_NUM as usize) | (ip.add(match_length) == ilimit) {
if DMS {
nb_compares = 0; }
break;
}
}
if *m_ml < *ip.add(match_length) {
*smaller_ptr = match_index;
common_length_smaller = match_length;
if match_index <= bt_low {
smaller_ptr = dummy;
break;
}
smaller_ptr = next_ptr.add(1);
match_index = *next_ptr.add(1);
} else {
*larger_ptr = match_index;
common_length_larger = match_length;
if match_index <= bt_low {
larger_ptr = dummy;
break;
}
larger_ptr = next_ptr;
match_index = *next_ptr;
}
nb_compares -= 1;
}
*smaller_ptr = 0;
*larger_ptr = 0;
if DMS && nb_compares > 0 {
let d = s.dms;
let dms_index_delta = window_low.wrapping_sub(d.high_limit);
let dms_bt_low = if d.bt_mask < d.high_limit - d.low_limit {
d.high_limit - d.bt_mask
} else {
d.low_limit
};
let dms_h = hash_mls::<MLS>(ip, d.hash_log);
let mut dict_match_index = *d.hash_table.add(dms_h);
common_length_smaller = 0;
common_length_larger = 0;
while nb_compares > 0 && dict_match_index > d.low_limit {
let next_ptr = d.bt.add(2 * (dict_match_index & d.bt_mask) as usize);
let mut match_length = common_length_smaller.min(common_length_larger);
let mut m = s.dict_base.wrapping_add(dict_match_index as usize);
s.chk(m, 0);
if m.wrapping_add(match_length) as usize <= s.dict_end as usize {
match_length += s.count_ext(ip.add(match_length), m.add(match_length), ilimit);
}
if dict_match_index as usize + match_length >= d.high_limit as usize {
m = s
.base
.wrapping_add(dict_match_index.wrapping_add(dms_index_delta) as usize);
}
if match_length > best_length {
let match_index = dict_match_index.wrapping_add(dms_index_delta);
if match_length > match_end_idx.wrapping_sub(match_index) as usize {
match_end_idx = match_index + match_length as u32;
}
best_length = match_length;
matches[mnum] = Match {
off: offset_to_offbase(curr - match_index),
len: match_length as u32,
};
mnum += 1;
if (match_length > OPT_NUM as usize) | (ip.add(match_length) == ilimit) {
break; }
}
if dict_match_index <= dms_bt_low {
break; }
let mm = m.wrapping_add(match_length);
s.chk(mm, 1);
if *mm < *ip.add(match_length) {
common_length_smaller = match_length;
dict_match_index = *next_ptr.add(1);
} else {
common_length_larger = match_length;
dict_match_index = *next_ptr;
}
nb_compares -= 1;
}
}
debug_assert!(match_end_idx > curr + 8);
s.next_to_update = match_end_idx - 8; }
mnum as u32
}
#[inline(never)]
pub(crate) fn compress_block_opt(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
match ms.cparams.strategy {
Strategy::BtOpt => {
opt_dispatch::<0, false, false, false>(ms, ss, rep, buf, start, end, &[])
}
Strategy::BtUltra => {
opt_dispatch::<2, false, false, false>(ms, ss, rep, buf, start, end, &[])
}
Strategy::BtUltra2 => {
let curr = ms.window.index(start);
let first_block = ms.opt.as_ref().is_some_and(|o| o.stats.lit_length_sum == 0);
if first_block
&& ms.window.dict_limit == ms.window.low_limit
&& curr == ms.window.dict_limit
&& end - start > PREDEF_THRESHOLD
{
init_stats_ultra::<false>(ms, ss, rep, buf, start, end, &[]);
}
opt_dispatch::<2, false, false, false>(ms, ss, rep, buf, start, end, &[])
}
s => unreachable!("not an optimal strategy: {s:?}"),
}
}
#[inline(never)]
pub(crate) fn compress_block_opt_dict_match_state(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
match ms.cparams.strategy {
Strategy::BtOpt => opt_dispatch::<0, false, true, false>(ms, ss, rep, buf, start, end, &[]),
Strategy::BtUltra | Strategy::BtUltra2 => {
opt_dispatch::<2, false, true, false>(ms, ss, rep, buf, start, end, &[])
}
s => unreachable!("not an optimal strategy: {s:?}"),
}
}
#[allow(unsafe_code)]
pub(crate) fn update_tree_for_dict(ms: &mut MatchState, buf: &[u8], end: usize) {
let cparams = ms.cparams;
assert!(end <= buf.len() && end >= HASH_READ_SIZE);
assert!(cparams.hash_log <= 32 && ms.hash_table.len() == 1usize << cparams.hash_log);
assert!(cparams.chain_log >= 1 && cparams.chain_log <= 32);
assert!(ms.chain_table.len() == 1usize << cparams.chain_log);
assert!(!ms.window.has_ext_dict());
let window_start = ms.window.pos(ms.window.dict_limit);
assert!(window_start <= ms.window.pos(ms.next_to_update));
assert!(end.wrapping_sub(ms.window.base) <= u32::MAX as usize);
let bp = buf.as_ptr();
let base = bp.wrapping_add(ms.window.base);
let iend = bp.wrapping_add(end);
let mut s = Bt {
base,
hash_table: ms.hash_table.as_mut_ptr(),
bt: ms.chain_table.as_mut_ptr(),
hash_table3: ms.hash_table3.as_mut_ptr(),
hash_log: cparams.hash_log,
hash_log3: ms.hash_log3,
bt_mask: (1u32 << (cparams.chain_log - 1)) - 1,
search_log: cparams.search_log,
window_log: cparams.window_log,
low_limit: ms.window.low_limit,
dict_limit: ms.window.dict_limit,
loaded_dict_end: ms.loaded_dict_end,
next_to_update: ms.next_to_update,
sufficient_len: cparams.target_length.min(OPT_NUM - 1),
lowest: bp.wrapping_add(window_start),
iend,
dict_base: base,
dict_lowest: iend,
dict_end: iend,
prefix_start: bp.wrapping_add(window_start),
dms: OptDms::NONE,
};
let ip = iend.wrapping_sub(HASH_READ_SIZE);
unsafe {
match cparams.min_match {
5 => update_tree::<5, false>(&mut s, ip, iend),
6 => update_tree::<6, false>(&mut s, ip, iend),
7 => update_tree::<7, false>(&mut s, ip, iend),
_ => update_tree::<4, false>(&mut s, ip, iend),
}
}
ms.next_to_update = s.next_to_update;
}
#[inline(never)]
pub(crate) fn compress_block_opt_ext_dict(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
) -> usize {
match ms.cparams.strategy {
Strategy::BtOpt => opt_dispatch::<0, true, false, false>(ms, ss, rep, buf, start, end, &[]),
Strategy::BtUltra | Strategy::BtUltra2 => {
opt_dispatch::<2, true, false, false>(ms, ss, rep, buf, start, end, &[])
}
s => unreachable!("not an optimal strategy: {s:?}"),
}
}
fn init_stats_ultra<const LDM: bool>(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &[u32; 3],
buf: &[u8],
start: usize,
end: usize,
ldm: &[RawSeq],
) {
let mut tmp_rep = *rep; let src_size = end - start;
debug_assert!(ss.nb_seq == 0); debug_assert!(ms.window.dict_limit == ms.window.low_limit); debug_assert!(ms.window.dict_limit.wrapping_sub(ms.next_to_update) <= 1); opt_dispatch::<2, false, false, LDM>(ms, ss, &mut tmp_rep, buf, start, end, ldm);
ss.reset();
ms.window.base = ms.window.base.wrapping_sub(src_size);
ms.window.dict_limit += src_size as u32;
ms.window.low_limit = ms.window.dict_limit;
ms.next_to_update = ms.window.dict_limit;
}
#[inline(never)]
pub(crate) fn compress_block_opt_ldm(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
ldm: &[RawSeq],
) -> usize {
let opt0 = ms.cparams.strategy == Strategy::BtOpt;
debug_assert!(ms.cparams.strategy >= Strategy::BtOpt);
if ms.window.has_ext_dict() {
if opt0 {
opt_dispatch::<0, true, false, true>(ms, ss, rep, buf, start, end, ldm)
} else {
opt_dispatch::<2, true, false, true>(ms, ss, rep, buf, start, end, ldm)
}
} else if ms.dms {
if opt0 {
opt_dispatch::<0, false, true, true>(ms, ss, rep, buf, start, end, ldm)
} else {
opt_dispatch::<2, false, true, true>(ms, ss, rep, buf, start, end, ldm)
}
} else if opt0 {
opt_dispatch::<0, false, false, true>(ms, ss, rep, buf, start, end, ldm)
} else {
if ms.cparams.strategy == Strategy::BtUltra2 {
let curr = ms.window.index(start);
let first_block = ms.opt.as_ref().is_some_and(|o| o.stats.lit_length_sum == 0);
if first_block
&& ss.nb_seq == 0
&& ms.window.dict_limit == ms.window.low_limit
&& curr == ms.window.dict_limit
&& end - start > PREDEF_THRESHOLD
{
init_stats_ultra::<true>(ms, ss, rep, buf, start, end, ldm);
}
}
opt_dispatch::<2, false, false, true>(ms, ss, rep, buf, start, end, ldm)
}
}
#[inline(always)]
fn opt_dispatch<const OPT_LEVEL: u32, const EXT: bool, const DMS: bool, const LDM: bool>(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
ldm: &[RawSeq],
) -> usize {
match ms.cparams.min_match.clamp(3, 6) {
3 => opt_generic::<3, OPT_LEVEL, EXT, DMS, LDM>(ms, ss, rep, buf, start, end, ldm),
4 => opt_generic::<4, OPT_LEVEL, EXT, DMS, LDM>(ms, ss, rep, buf, start, end, ldm),
5 => opt_generic::<5, OPT_LEVEL, EXT, DMS, LDM>(ms, ss, rep, buf, start, end, ldm),
_ => opt_generic::<6, OPT_LEVEL, EXT, DMS, LDM>(ms, ss, rep, buf, start, end, ldm),
}
}
struct OptLdm<'a> {
seq: &'a [RawSeq],
pos: usize,
pos_in_sequence: usize,
start_pos_in_block: u32,
end_pos_in_block: u32,
offset: u32,
}
impl<'a> OptLdm<'a> {
fn new(seq: &'a [RawSeq]) -> Self {
OptLdm {
seq,
pos: 0,
pos_in_sequence: 0,
start_pos_in_block: 0,
end_pos_in_block: 0,
offset: 0,
}
}
fn skip_bytes(&mut self, nb_bytes: usize) {
let mut curr_pos = (self.pos_in_sequence + nb_bytes) as u32;
while curr_pos != 0 && self.pos < self.seq.len() {
let s = self.seq[self.pos];
if curr_pos >= s.lit_length + s.match_length {
curr_pos -= s.lit_length + s.match_length;
self.pos += 1;
} else {
self.pos_in_sequence = curr_pos as usize;
break;
}
}
if curr_pos == 0 || self.pos == self.seq.len() {
self.pos_in_sequence = 0;
}
}
fn get_next_match(&mut self, curr_pos_in_block: u32, block_bytes_remaining: u32) {
if self.pos >= self.seq.len() {
self.start_pos_in_block = u32::MAX;
self.end_pos_in_block = u32::MAX;
return;
}
let curr_seq = self.seq[self.pos];
let pis = self.pos_in_sequence as u32;
debug_assert!(pis <= curr_seq.lit_length + curr_seq.match_length);
let curr_block_end_pos = curr_pos_in_block + block_bytes_remaining;
let literals_bytes_remaining = curr_seq.lit_length.saturating_sub(pis);
let match_bytes_remaining = if literals_bytes_remaining == 0 {
curr_seq.match_length - (pis - curr_seq.lit_length)
} else {
curr_seq.match_length
};
if literals_bytes_remaining >= block_bytes_remaining {
self.start_pos_in_block = u32::MAX;
self.end_pos_in_block = u32::MAX;
self.skip_bytes(block_bytes_remaining as usize);
return;
}
self.start_pos_in_block = curr_pos_in_block + literals_bytes_remaining;
self.end_pos_in_block = self.start_pos_in_block + match_bytes_remaining;
self.offset = curr_seq.offset;
if self.end_pos_in_block > curr_block_end_pos {
self.end_pos_in_block = curr_block_end_pos;
self.skip_bytes((curr_block_end_pos - curr_pos_in_block) as usize);
} else {
self.skip_bytes((literals_bytes_remaining + match_bytes_remaining) as usize);
}
}
#[inline]
fn maybe_add_match(
&self,
matches: &mut [Match],
nb_matches: &mut usize,
curr_pos_in_block: u32,
min_match: u32,
) {
let pos_diff = curr_pos_in_block.wrapping_sub(self.start_pos_in_block);
let candidate_match_length = self
.end_pos_in_block
.wrapping_sub(self.start_pos_in_block)
.wrapping_sub(pos_diff);
if curr_pos_in_block < self.start_pos_in_block
|| curr_pos_in_block >= self.end_pos_in_block
|| candidate_match_length < min_match
{
return;
}
let n = *nb_matches;
if n == 0 || (candidate_match_length > matches[n - 1].len && n < OPT_NUM as usize) {
matches[n] = Match {
off: offset_to_offbase(self.offset),
len: candidate_match_length,
};
*nb_matches = n + 1;
}
}
#[inline]
fn process_match_candidate(
&mut self,
matches: &mut [Match],
nb_matches: &mut usize,
curr_pos_in_block: u32,
remaining_bytes: u32,
min_match: u32,
) {
if self.pos >= self.seq.len() {
return;
}
if curr_pos_in_block >= self.end_pos_in_block {
if curr_pos_in_block > self.end_pos_in_block {
let pos_overshoot = curr_pos_in_block - self.end_pos_in_block;
self.skip_bytes(pos_overshoot as usize);
}
self.get_next_match(curr_pos_in_block, remaining_bytes);
}
self.maybe_add_match(matches, nb_matches, curr_pos_in_block, min_match);
}
}
#[allow(unsafe_code)]
#[inline(always)]
fn opt_generic<
const MLS: u32,
const OPT_LEVEL: u32,
const EXT: bool,
const DMS: bool,
const LDM: bool,
>(
ms: &mut MatchState,
ss: &mut SeqStore,
rep: &mut [u32; 3],
buf: &[u8],
start: usize,
end: usize,
ldm: &[RawSeq],
) -> usize {
let cparams = ms.cparams;
assert!(start <= end && end <= buf.len());
assert!(cparams.hash_log <= 32 && ms.hash_table.len() == 1usize << cparams.hash_log);
assert!(cparams.chain_log >= 1 && cparams.chain_log <= 32);
assert!(ms.chain_table.len() == 1usize << cparams.chain_log);
assert!(cparams.search_log < 32);
if MLS == 3 {
assert!(ms.hash_log3 >= 1 && ms.hash_log3 <= 32);
assert!(ms.hash_table3.len() == 1usize << ms.hash_log3);
}
assert!(EXT == ms.window.has_ext_dict());
assert!(!(EXT && DMS));
let window_start = ms.window.pos(ms.window.dict_limit);
assert!(window_start <= start, "window start is not in the buffer");
assert!(ms.next_to_update >= ms.window.dict_limit);
assert!(end.wrapping_sub(ms.window.base) <= u32::MAX as usize);
let cd = if DMS {
Some(ms.dict.clone().expect("attached dictionary"))
} else {
None
};
let (dict_base, dict_lowest, dict_end, dms) = if EXT {
let w = ExtWindow::new(
&ms.window,
buf,
ms.ext_buf(buf),
start,
end,
ms.window.low_limit,
ms.window.dict_limit,
);
(w.dict_base, w.dict_start, w.dict_end, OptDms::NONE)
} else if let Some(cd) = &cd {
let d = DmsView::new(cd);
assert!(d.chain_log >= 1 && d.chain_log <= 32 && d.hash_log <= 32);
assert!(cd.ms.chain_table.len() == 1usize << d.chain_log);
assert!(ms.window.dict_limit >= d.high_limit);
let dms = OptDms {
hash_table: d.hash_table,
bt: d.chain_table,
hash_log: d.hash_log,
bt_mask: (1u32 << (d.chain_log - 1)) - 1,
low_limit: d.low_limit,
high_limit: d.high_limit,
};
(d.base, d.start, d.end, dms)
} else {
(buf.as_ptr(), buf.as_ptr(), buf.as_ptr(), OptDms::NONE)
};
debug_assert!(OPT_LEVEL <= 2);
let mut st = ms.opt.take().expect("optimal parser state");
let OptState {
stats,
price_table,
match_table,
dict_costs,
} = &mut *st;
assert!(price_table.len() == OPT_SIZE && match_table.len() == OPT_SIZE);
let opt = &mut price_table[..];
let matches = &mut match_table[..];
let bp = buf.as_ptr();
let base = bp.wrapping_add(ms.window.base);
let istart = bp.wrapping_add(start);
let iend = bp.wrapping_add(end);
let ilimit = iend.wrapping_sub(8);
let prefix_start = base.wrapping_add(ms.window.dict_limit as usize);
let sufficient_len = cparams.target_length.min(OPT_NUM - 1);
let min_match = if cparams.min_match == 3 { 3 } else { 4 };
let mut next_to_update3 = ms.next_to_update;
let mut s = Bt {
base,
hash_table: ms.hash_table.as_mut_ptr(),
bt: ms.chain_table.as_mut_ptr(),
hash_table3: ms.hash_table3.as_mut_ptr(),
hash_log: cparams.hash_log,
hash_log3: ms.hash_log3,
bt_mask: (1u32 << (cparams.chain_log - 1)) - 1,
search_log: cparams.search_log,
window_log: cparams.window_log,
low_limit: ms.window.low_limit,
dict_limit: ms.window.dict_limit,
loaded_dict_end: ms.loaded_dict_end,
next_to_update: ms.next_to_update,
sufficient_len,
lowest: bp.wrapping_add(window_start),
iend,
dict_base,
dict_lowest,
dict_end,
prefix_start,
dms,
};
let mut ip = istart;
let mut anchor = istart;
let mut last_stretch = Optimal::default();
let mut opt_ldm = OptLdm::new(ldm);
if LDM {
opt_ldm.get_next_match(0, (end - start) as u32);
}
let block_pos = |p: *const u8| (p as usize - istart as usize) as u32;
let block_rest = |p: *const u8| (iend as usize - p as usize) as u32;
stats.rescale_freqs::<OPT_LEVEL>(&buf[start..end], dict_costs.as_deref());
ip = ip.wrapping_add((ip == prefix_start) as usize);
unsafe {
'main: while ip < ilimit {
let mut cur: u32;
let mut last_pos: u32;
'shortest_path: {
{
let litlen = (ip as usize - anchor as usize) as u32;
let ll0 = u32::from(litlen == 0);
#[allow(unused_mut)]
let mut nb_matches = get_all_matches::<MLS, EXT, DMS>(
&mut s,
matches,
&mut next_to_update3,
ip,
iend,
rep,
ll0,
min_match,
) as usize;
if LDM {
opt_ldm.process_match_candidate(
matches,
&mut nb_matches,
block_pos(ip),
block_rest(ip),
min_match,
);
}
if nb_matches == 0 {
ip = ip.add(1);
continue 'main;
}
opt[0].mlen = 0;
opt[0].litlen = litlen;
opt[0].price = stats.ll_price::<OPT_LEVEL>(litlen);
opt[0].rep = *rep;
let max_ml = matches[nb_matches - 1].len;
let max_off_base = matches[nb_matches - 1].off;
if max_ml > sufficient_len {
last_stretch.litlen = 0;
last_stretch.mlen = max_ml;
last_stretch.off = max_off_base;
cur = 0;
last_pos = max_ml;
break 'shortest_path;
}
debug_assert!(opt[0].price >= 0);
let mut pos = 1u32;
while pos < min_match {
let o = &mut opt[pos as usize];
o.price = MAX_PRICE;
o.mlen = 0;
o.litlen = litlen + pos;
pos += 1;
}
for m in &matches[..nb_matches] {
let off_base = m.off;
let end = m.len;
while pos <= end {
let match_price = stats.match_price::<OPT_LEVEL>(off_base, pos);
let sequence_price = opt[0].price + match_price;
let o = &mut opt[pos as usize];
o.mlen = pos;
o.off = off_base;
o.litlen = 0; o.price = sequence_price + stats.ll_price::<OPT_LEVEL>(0);
pos += 1;
}
}
last_pos = pos - 1;
opt[pos as usize].price = MAX_PRICE;
}
if OPT_LEVEL == 2 {
align_hot_loop!(32);
}
cur = 1;
while cur <= last_pos {
let inr = ip.add(cur as usize);
debug_assert!(cur <= OPT_NUM);
let c = cur as usize;
{
let litlen = opt[c - 1].litlen + 1;
s.chk(ip.add(c - 1), 1);
let price = opt[c - 1].price
+ stats.lit_price::<OPT_LEVEL>(*ip.add(c - 1))
+ stats.ll_incprice::<OPT_LEVEL>(litlen);
debug_assert!(price < 1_000_000_000); if price <= opt[c].price {
let prev_match = opt[c];
opt[c] = opt[c - 1];
opt[c].litlen = litlen;
opt[c].price = price;
if OPT_LEVEL >= 1 && prev_match.litlen == 0 && stats.ll_incprice::<OPT_LEVEL>(1) < 0 && ip.add(c) < iend
{
s.chk(ip.add(c), 1);
let lit = stats.lit_price::<OPT_LEVEL>(*ip.add(c));
let with1literal =
prev_match.price + lit + stats.ll_incprice::<OPT_LEVEL>(1);
let with_more_literals =
price + lit + stats.ll_incprice::<OPT_LEVEL>(litlen + 1);
if with1literal < with_more_literals
&& with1literal < opt[c + 1].price
{
let prev = (cur - prev_match.mlen) as usize;
debug_assert!(cur >= prev_match.mlen);
let new_reps = new_rep(
opt[prev].rep,
prev_match.off,
opt[prev].litlen == 0,
);
opt[c + 1] = prev_match; opt[c + 1].rep = new_reps;
opt[c + 1].litlen = 1;
opt[c + 1].price = with1literal;
if last_pos < cur + 1 {
last_pos = cur + 1;
}
}
}
}
}
debug_assert!(cur >= opt[c].mlen);
if opt[c].litlen == 0 {
let prev = (cur - opt[c].mlen) as usize;
opt[c].rep = new_rep(opt[prev].rep, opt[c].off, opt[prev].litlen == 0);
}
if inr > ilimit {
cur += 1;
continue;
}
if cur == last_pos {
break;
}
if OPT_LEVEL == 0
&& opt[c + 1].price <= opt[c].price + (BITCOST_MULTIPLIER / 2) as i32
{
cur += 1;
continue;
}
debug_assert!(opt[c].price >= 0);
{
let ll0 = u32::from(opt[c].litlen == 0);
let previous_price = opt[c].price;
let base_price = previous_price + stats.ll_price::<OPT_LEVEL>(0);
let reps = opt[c].rep;
#[allow(unused_mut)]
let mut nb_matches = get_all_matches::<MLS, EXT, DMS>(
&mut s,
matches,
&mut next_to_update3,
inr,
iend,
&reps,
ll0,
min_match,
) as usize;
if LDM {
opt_ldm.process_match_candidate(
matches,
&mut nb_matches,
block_pos(inr),
block_rest(inr),
min_match,
);
}
if nb_matches == 0 {
cur += 1;
continue;
}
let longest_ml = matches[nb_matches - 1].len;
if longest_ml > sufficient_len
|| cur + longest_ml >= OPT_NUM
|| ip.add((cur + longest_ml) as usize) >= iend
{
last_stretch.mlen = longest_ml;
last_stretch.off = matches[nb_matches - 1].off;
last_stretch.litlen = 0;
last_pos = cur + longest_ml;
break 'shortest_path;
}
for match_nb in 0..nb_matches {
let offset = matches[match_nb].off;
let last_ml = matches[match_nb].len;
let start_ml = if match_nb > 0 {
matches[match_nb - 1].len + 1
} else {
min_match
};
let off_price = (base_price as u32)
.wrapping_add(stats.match_off_price::<OPT_LEVEL>(offset));
let mut mlen = last_ml;
while mlen >= start_ml {
let pos = cur + mlen;
let price = off_price
.wrapping_add(stats.ml_len_price::<OPT_LEVEL>(mlen))
as i32;
if pos > last_pos || price < opt[pos as usize].price {
while last_pos < pos {
last_pos += 1;
opt[last_pos as usize].price = MAX_PRICE;
opt[last_pos as usize].litlen = 1;
}
let o = &mut opt[pos as usize];
o.mlen = mlen;
o.off = offset;
o.litlen = 0;
o.price = price;
} else if OPT_LEVEL == 0 {
break;
}
mlen -= 1;
}
}
}
opt[last_pos as usize + 1].price = MAX_PRICE;
cur += 1;
}
last_stretch = opt[last_pos as usize];
debug_assert!(last_pos >= last_stretch.mlen);
cur = last_pos - last_stretch.mlen;
}
debug_assert!(opt[0].mlen == 0);
debug_assert!(last_pos >= last_stretch.mlen);
debug_assert!(cur == last_pos - last_stretch.mlen);
if last_stretch.mlen == 0 {
debug_assert!(
last_stretch.litlen as usize
== (ip as usize - anchor as usize) + last_pos as usize
);
ip = ip.add(last_pos as usize);
continue 'main;
}
debug_assert!(last_stretch.off > 0);
if last_stretch.litlen == 0 {
let c = cur as usize;
*rep = new_rep(opt[c].rep, last_stretch.off, opt[c].litlen == 0);
} else {
*rep = last_stretch.rep;
debug_assert!(cur >= last_stretch.litlen);
cur -= last_stretch.litlen;
}
{
let store_end = cur as usize + 2;
let mut store_start;
let mut stretch_pos = cur as usize;
debug_assert!(store_end < OPT_SIZE);
if last_stretch.litlen > 0 {
opt[store_end].litlen = last_stretch.litlen;
opt[store_end].mlen = 0;
store_start = store_end - 1;
opt[store_start] = last_stretch;
}
{
opt[store_end] = last_stretch; store_start = store_end;
}
loop {
let next_stretch = opt[stretch_pos];
opt[store_start].litlen = next_stretch.litlen;
if next_stretch.mlen == 0 {
break;
}
store_start -= 1;
opt[store_start] = next_stretch; debug_assert!(
(next_stretch.litlen + next_stretch.mlen) as usize <= stretch_pos
);
stretch_pos -= (next_stretch.litlen + next_stretch.mlen) as usize;
}
for (k, o) in opt[store_start..=store_end].iter().enumerate() {
let llen = o.litlen as usize;
let mlen = o.mlen;
let off_base = o.off;
let advance = llen + mlen as usize;
if mlen == 0 {
debug_assert!(store_start + k == store_end);
ip = anchor.add(llen);
continue; }
let a = anchor as usize - bp as usize;
debug_assert!(a + llen <= end);
stats.update_stats(&buf[a..a + llen], off_base, mlen);
ss.store_seq(buf, a, llen, end, off_base, mlen as usize);
anchor = anchor.add(advance);
ip = anchor;
}
}
stats.set_base_prices::<OPT_LEVEL>();
}
}
ms.next_to_update = s.next_to_update;
ms.opt = Some(st);
iend as usize - anchor as usize
}
#[cfg(test)]
mod tests {
use super::super::fast::tests::{random, roundtrip, roundtrip_ring, texty, xorshift};
use super::super::params::{CParams, Strategy, block_size_max, one_shot_cparams};
use super::*;
const OPT: [Strategy; 3] = [Strategy::BtOpt, Strategy::BtUltra, Strategy::BtUltra2];
fn inputs() -> [Vec<u8>; 6] {
[
texty(1000, 1),
texty(300_000, 3),
random(50_000, 4),
alloc::vec![0u8; 200_000],
(0..70_000u32).map(|i| (i % 251) as u8).collect(),
{
let mut v = random(20_000, 5);
v.extend_from_slice(&texty(30_000, 6));
v.extend_from_within(..25_000);
v
},
]
}
#[test]
fn roundtrip_levels() {
for src in &inputs() {
for level in 11..=22 {
let cp = one_shot_cparams(level, src.len() as u64);
if !OPT.contains(&cp.strategy) {
continue;
}
roundtrip(src, cp, block_size_max(&cp, src.len() as u64));
}
}
}
#[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 strategy in OPT {
for mls in 3..=7 {
for (search_log, target_length) in [(1, 4), (4, 32), (7, 256), (9, 999)] {
for window_log in [10, 17, 22] {
let cp = CParams {
window_log,
chain_log: 16,
hash_log: 15,
search_log,
min_match: mls,
target_length,
strategy,
};
let n = roundtrip(&src, cp, (1 << 17).min(1 << window_log));
assert!(
n > 1000,
"{strategy:?} mls {mls} slog {search_log} wlog {window_log}: {n} sequences"
);
}
}
}
}
}
#[test]
fn small_blocks() {
let src = texty(5000, 9);
for level in [16, 18, 19, 22] {
let cp = one_shot_cparams(level, src.len() as u64);
for bs in [1, 6, 7, 8, 9, 16, 17, 20, 33, 100, 1000] {
roundtrip(&src, cp, bs);
}
}
for n in 0..60 {
let s = texty(n, 10);
for level in [12, 16, 19, 22] {
roundtrip(&s, one_shot_cparams(level, n as u64), 1 << 17);
}
}
}
#[test]
fn long_matches() {
let mut src = random(10_000, 11);
src.extend_from_within(..10_000);
src.extend(core::iter::repeat_n(b'a', 20_000));
src.extend_from_slice(&texty(10_000, 12));
src.extend_from_within(5_000..25_000);
src.extend((0..200_000u32).map(|i| (i % 3) as u8));
for level in [16, 17, 18, 19, 22] {
let cp = one_shot_cparams(level, src.len() as u64);
roundtrip(&src, cp, block_size_max(&cp, src.len() as u64));
}
}
#[test]
fn weights() {
assert_eq!(bit_weight(0), 0);
assert_eq!(bit_weight(1), 256);
assert_eq!(bit_weight(3), 512);
assert_eq!(frac_weight(0), 256);
assert_eq!(frac_weight(1), 512);
assert_eq!(frac_weight(2), 256 + 384);
let mut prev = 0;
for s in 0..100_000 {
let w = frac_weight(s);
assert!(w >= prev);
prev = w;
}
}
#[test]
fn scaling() {
let mut t = [0u32, 1, 2, 3, 1000, 5000];
assert_eq!(scale_stats(&mut t, 12), 6006);
let sum = scale_stats(&mut t, 10);
assert_eq!(t, [1, 1, 1, 1, 251, 1251]);
assert_eq!(sum, 1506);
let mut t = [0u32, 1, 4, 255, 256];
assert_eq!(downscale_stats(&mut t, 8, false), 5);
assert_eq!(t, [0, 1, 1, 1, 2]);
}
#[test]
fn ml_code_bases() {
for code in 0..ML_CODE_BASES.len() - 1 {
let (lo, hi) = (ML_CODE_BASES[code], ML_CODE_BASES[code + 1]);
assert!(lo < hi);
for b in lo..hi {
assert_eq!(ml_code(u32::from(b)), code as u32, "mlBase {b}");
}
}
assert_eq!(ML_CODE_BASES[0], 0);
assert_eq!(*ML_CODE_BASES.last().unwrap(), 128);
}
fn ref_ll_price<const L: u32>(s: &OptStats, lit_length: u32) -> i32 {
if s.price_type == PriceType::Predef {
return weight::<L>(lit_length) as i32;
}
if lit_length as usize == BLOCKSIZE_MAX {
return BITCOST_MULTIPLIER as i32 + ref_ll_price::<L>(s, lit_length - 1);
}
let c = ll_code(lit_length) as usize;
(u32::from(LL_BITS[c]) * BITCOST_MULTIPLIER) as i32 + weight::<L>(s.lit_length_sum) as i32
- weight::<L>(s.lit_length_freq[c]) as i32
}
fn ref_match_price<const L: u32>(s: &OptStats, off_base: u32, match_length: u32) -> u32 {
let off_code = highbit32(off_base);
let ml_base = match_length - MINMATCH;
if s.price_type == PriceType::Predef {
return weight::<L>(ml_base).wrapping_add((16 + off_code) * BITCOST_MULTIPLIER);
}
let mut price = (off_code * BITCOST_MULTIPLIER).wrapping_add(
weight::<L>(s.off_code_sum)
.wrapping_sub(weight::<L>(s.off_code_freq[off_code as usize])),
);
if L < 2 && off_code >= 20 {
price = price.wrapping_add((off_code - 19) * 2 * BITCOST_MULTIPLIER);
}
let c = ml_code(ml_base) as usize;
price = price.wrapping_add((u32::from(ML_BITS[c]) * BITCOST_MULTIPLIER).wrapping_add(
weight::<L>(s.match_length_sum).wrapping_sub(weight::<L>(s.match_length_freq[c])),
));
price.wrapping_add(BITCOST_MULTIPLIER / 5)
}
fn incremental_prices<const L: u32>(seed: u64) {
let mut r = seed;
let mut s = OptState::new().stats;
let lens: Vec<u32> = (0..=300u32)
.chain([1000, 4095, 65_535, 65_536, 131_071, BLOCKSIZE_MAX as u32])
.collect();
let rounds = if cfg!(miri) { 2 } else { 40 };
for round in 0..rounds {
if round % 7 == 0 {
s.lit_length_sum = 0;
}
let n = [10, 5000, 100_000][(xorshift(&mut r) % 3) as usize];
s.rescale_freqs::<L>(&texty(n, xorshift(&mut r)), None);
for _ in 0..(xorshift(&mut r) % 50) {
for _ in 0..(xorshift(&mut r) % 4) {
let ll = (xorshift(&mut r) % [20, 300, 70_000][(xorshift(&mut r) % 3) as usize])
as usize;
let lits = alloc::vec![(xorshift(&mut r) % 256) as u8; ll];
let off_base = 1 + (xorshift(&mut r) % (1 << (xorshift(&mut r) % 27))) as u32;
let ml = 3
+ (xorshift(&mut r) % [10, 200, 70_000][(xorshift(&mut r) % 3) as usize])
as u32;
s.update_stats(&lits, off_base, ml);
}
s.set_base_prices::<L>();
for &ll in &lens {
assert_eq!(s.ll_price::<L>(ll), ref_ll_price::<L>(&s, ll), "ll {ll}");
}
for off_base in [1u32, 2, 3, 4, 100, 70_000, 1 << 22, (1 << 30) + 5] {
for &ml in lens.iter().filter(|&&l| l >= MINMATCH) {
assert_eq!(
s.match_price::<L>(off_base, ml) as u32,
ref_match_price::<L>(&s, off_base, ml),
"off_base {off_base} ml {ml} {:?}",
s.price_type
);
}
}
}
}
}
#[test]
fn incremental_prices_match_libzstd() {
incremental_prices::<0>(1);
incremental_prices::<1>(2);
incremental_prices::<2>(3);
}
#[test]
fn roundtrip_ring_variants() {
let mut src = texty(100_000, 7);
src.extend_from_slice(&random(5000, 8));
src.extend_from_slice(&src.clone()[..40_000]);
src.extend_from_slice(&texty(50_000, 17));
for strategy in OPT {
for mls in 3..=6 {
for (search_log, target_length) in [(1, 4), (4, 32), (7, 256)] {
for (window_log, bs) in [(12, 4096), (15, 5000), (16, 1 << 15)] {
let cp = CParams {
window_log,
chain_log: 16,
hash_log: 15,
search_log,
min_match: mls,
target_length,
strategy,
};
let (n, ext) = roundtrip_ring(&src, cp, bs);
assert!(
n > 1000 && ext > 0,
"{strategy:?} mls {mls} slog {search_log} wlog {window_log}: {n} {ext}"
);
}
}
}
}
}
}