rusty_zlib 0.1.4

Remade-With-Rust fork of zlib-rs: a memory-safe, pure-Rust zlib (deflate/inflate, zlib and gzip), measured and tuned for the MATA stack
Documentation
use crate::deflate::compare256::first_chunk;
use crate::deflate::{H3_BITS, H3_MAX_DIST, H3_SIZE};
use crate::{
    deflate::{BlockState, DeflateStream, Strategy},
    DeflateFlush,
};

use self::{huff::deflate_huff, rle::deflate_rle, stored::deflate_stored};

mod fast;
mod huff;
mod medium;
mod quick;
mod quick_dyn;
mod rle;
mod slow;
mod stored;

macro_rules! flush_block {
    ($stream:expr, $is_last_block:expr) => {
        $crate::deflate::flush_block_only($stream, $is_last_block);

        if $stream.avail_out == 0 {
            return match $is_last_block {
                true => BlockState::FinishStarted,
                false => BlockState::NeedMore,
            };
        }
    };
}
pub(crate) use flush_block;

pub fn run(stream: &mut DeflateStream, flush: DeflateFlush) -> BlockState {
    match stream.state.strategy {
        _ if stream.state.level == 0 => deflate_stored(stream, flush),
        Strategy::HuffmanOnly => deflate_huff(stream, flush),
        Strategy::Rle => deflate_rle(stream, flush),
        Strategy::Default | Strategy::Filtered | Strategy::Fixed => {
            (stream.state.config().func)(stream, flush)
        }
    }
}

type CompressFunc = fn(&mut DeflateStream, flush: DeflateFlush) -> BlockState;

pub struct Config {
    pub good_length: u16, /* reduce lazy search above this match length */
    pub max_lazy: u16,    /* do not perform lazy search above this match length */
    pub nice_length: u16, /* quit search above this match length */
    pub max_chain: u16,
    pub func: CompressFunc,
    /// House delta: use the 3-byte rolling hash even when `max_chain <= 1024`. The 4-byte hash
    /// never offers a 3-byte match, and text is full of them. Only the dense table sets it.
    pub force_roll: bool,
    /// House delta: also consult the 3-byte match table when the hash chain finds nothing of
    /// length 4 or more (`deflate_slow` only). Only the dense table sets it.
    pub hash3: bool,
}

impl Config {
    const fn new(
        good_length: u16,
        max_lazy: u16,
        nice_length: u16,
        max_chain: u16,
        func: CompressFunc,
    ) -> Self {
        Self {
            good_length,
            max_lazy,
            nice_length,
            max_chain,
            func,
            force_roll: false,
            hash3: false,
        }
    }

    const fn hash3(mut self) -> Self {
        self.hash3 = true;
        self
    }

    const fn roll(mut self) -> Self {
        self.force_roll = true;
        self
    }
}

pub static CONFIGURATION_TABLE: [Config; 10] = {
    [
        Config::new(0, 0, 0, 0, stored::deflate_stored), // 0 /* store only */
        Config::new(0, 0, 0, 0, quick::deflate_quick),   // 1
        Config::new(4, 4, 8, 4, fast::deflate_fast),     // 2 /* max speed, no lazy matches */
        Config::new(4, 6, 16, 6, medium::deflate_medium), // 3
        Config::new(4, 12, 32, 24, medium::deflate_medium), // 4 /* lazy matches */
        Config::new(8, 16, 32, 32, medium::deflate_medium), // 5
        Config::new(8, 16, 128, 128, medium::deflate_medium), // 6
        Config::new(8, 32, 128, 256, slow::deflate_slow), // 7
        Config::new(32, 128, 258, 1024, slow::deflate_slow), // 8
        Config::new(32, 258, 258, 4096, slow::deflate_slow), // 9 /* max compression */
    ]
};

/// House delta (rusty_zlib): the opt-in dense level table (`LevelTable::Dense`).
///
/// It aims at miniz_oxide's output size, or smaller, at each level, while staying faster than
/// miniz_oxide at that level. Every entry was measured that way; see docs/house/dense-levels.md.
/// The zlib-ng table above stays the default, and its output is identical to upstream.
pub static DENSE_TABLE: [Config; 10] = {
    [
        Config::new(0, 0, 0, 0, stored::deflate_stored), // 0 /* store only */
        Config::new(0, 0, 0, 0, quick_dyn::deflate_quick_dyn), // 1
        Config::new(4, 6, 8, 4, fast::deflate_fast).hash3(), // 2
        Config::new(4, 8, 32, 16, slow::deflate_slow).hash3(), // 3
        Config::new(8, 16, 32, 32, slow::deflate_slow).hash3(), // 4
        Config::new(8, 16, 64, 64, slow::deflate_slow).hash3(), // 5
        Config::new(8, 16, 128, 128, slow::deflate_slow).hash3(), // 6
        Config::new(8, 32, 128, 256, slow::deflate_slow).hash3(), // 7
        Config::new(32, 128, 258, 1024, slow::deflate_slow).hash3(), // 8
        Config::new(32, 258, 258, 4096, slow::deflate_slow), // 9 /* = zlib-ng 9 */
    ]
};

/// House delta (rusty_zlib): the dense levels' 3-byte match table.
///
/// zlib-ng's hash chains are keyed on 4 bytes, so they never offer a match of length 3, and text
/// is full of them. This table maps a hash of the 3 bytes at a position to the most recent
/// position with that hash. It is consulted only when the chain found nothing of length 4 or more.
/// The candidate is verified byte by byte, and only accepted within `H3_MAX_DIST`, past which a
/// 3-byte match costs more than 3 literals.
#[inline(always)]
fn h3_index(b: &[u8; 3]) -> usize {
    let v = u32::from(b[0]) | u32::from(b[1]) << 8 | u32::from(b[2]) << 16;
    (v.wrapping_mul(0x9E37_79B1) >> (32 - H3_BITS)) as usize
}

/// Record `strstart` and return the previous position with the same 3-byte hash, if it is a
/// real 3-byte match within reach.
#[inline(always)]
pub(super) fn h3_probe(state: &mut crate::deflate::State<'_>) -> Option<usize> {
    let p = state.strstart;
    let window = state.window.filled();
    let cur: &[u8; 3] = first_chunk(&window[p..])?;
    let table = state.h3.as_mut()?.as_mut_slice();
    let slot = &mut table[h3_index(cur) & (H3_SIZE - 1)];
    let cand = usize::from(*slot);
    *slot = p as u16;
    let reach = Ord::min(H3_MAX_DIST, state.max_dist());
    if cand != 0 && cand < p && p - cand <= reach && window[cand..cand + 3] == cur[..] {
        Some(cand)
    } else {
        None
    }
}

/// Record the positions `start..start + count` (the body of an emitted match).
#[inline(always)]
pub(super) fn h3_insert_run(state: &mut crate::deflate::State<'_>, start: usize, count: usize) {
    let window = state.window.filled();
    let Some(h3) = state.h3.as_mut() else { return };
    let table = h3.as_mut_slice();
    for q in start..start + count {
        if let Some(b) = first_chunk::<u8, 3>(&window[q..]) {
            table[h3_index(b) & (H3_SIZE - 1)] = q as u16;
        }
    }
}