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
#![forbid(unsafe_code)]

use crate::deflate::compare256::first_chunk;
use crate::deflate::hash_calc::StandardHashCalc;
use crate::{
    deflate::{
        fill_window, flush_pending, BlockState, BlockType, DeflateStream, State, StaticTreeDesc,
        MIN_LOOKAHEAD, STD_MAX_MATCH, STD_MIN_MATCH, WANT_MIN_MATCH,
    },
    DeflateFlush,
};

pub fn deflate_quick(stream: &mut DeflateStream, flush: DeflateFlush) -> BlockState {
    let mut state = &mut stream.state;

    macro_rules! quick_end_block {
        ($last:expr) => {
            if state.block_open > 0 {
                state
                    .bit_writer
                    .emit_end_block_and_align(&StaticTreeDesc::L.static_tree, $last);
                state.block_open = 0;
                state.block_start = state.strstart as isize;
                flush_pending(stream);
                #[allow(unused_assignments)]
                {
                    state = &mut stream.state;
                }
                if stream.avail_out == 0 {
                    return match $last {
                        true => BlockState::FinishStarted,
                        false => BlockState::NeedMore,
                    };
                }
            }
        };
    }

    macro_rules! quick_start_block {
        ($last:expr) => {
            state.bit_writer.emit_tree(BlockType::StaticTrees, $last);
            state.block_open = 1 + $last as u8;
            state.block_start = state.strstart as isize;
        };
    }

    let last = matches!(flush, DeflateFlush::Finish);

    if last && state.block_open != 2 {
        /* Emit end of previous block */
        quick_end_block!(false);
        /* Emit start of last block */
        quick_start_block!(last);
    } else if state.block_open == 0 && state.lookahead > 0 {
        /* Start new block only when we have lookahead data, so that if no
        input data is given an empty block will not be written */
        quick_start_block!(last);
    }

    loop {
        if state.bit_writer.pending.pending + State::BIT_BUF_SIZE.div_ceil(8) as usize
            >= state.pending_buf_size()
        {
            flush_pending(stream);
            state = &mut stream.state;
            if stream.avail_out == 0 {
                return if last
                    && stream.avail_in == 0
                    && state.bit_writer.bits_valid == 0
                    && state.block_open == 0
                {
                    BlockState::FinishStarted
                } else {
                    BlockState::NeedMore
                };
            }
        }

        if state.lookahead < MIN_LOOKAHEAD {
            fill_window(stream);
            state = &mut stream.state;

            if state.lookahead < MIN_LOOKAHEAD && matches!(flush, DeflateFlush::NoFlush) {
                return BlockState::NeedMore;
            }
            if state.lookahead == 0 {
                break;
            }

            if state.block_open == 0 {
                // Start new block when we have lookahead data,
                // so that if no input data is given an empty block will not be written
                quick_start_block!(last);
            }
        }

        if state.lookahead >= MIN_LOOKAHEAD {
            // Steady state: no refill and no flush is needed until `lookahead` drops below
            // MIN_LOOKAHEAD or the pending buffer fills, so run the positions in a tight loop
            // with the loop invariants (window, max_dist, flush threshold, cursor) in locals.
            // The exit test is exactly the two conditions the top of the outer loop acts on.
            let window = state.window.filled();
            let max_dist = state.max_dist();
            // `pending + 8 >= size` <=> `pending >= size.saturating_sub(8)`.
            let pending_limit = state
                .pending_buf_size()
                .saturating_sub(State::BIT_BUF_SIZE.div_ceil(8) as usize);
            let mut strstart = state.strstart;
            let mut lookahead = state.lookahead;
            // Held in locals for the whole loop: otherwise the u16 table stores force a
            // reload of both table pointers (and `prev`'s length) from `State` per position.
            let head = state.head.as_mut_slice();
            let prev = state.prev.as_mut_slice();

            loop {
                // `strstart + lookahead <= window_size` and `lookahead >= MIN_LOOKAHEAD`.
                let cur: &[u8; MIN_LOOKAHEAD] = first_chunk(&window[strstart..]).unwrap();
                let str_val = u32::from_le_bytes([cur[0], cur[1], cur[2], cur[3]]);

                let hash_head =
                    StandardHashCalc::quick_insert_value_slices(head, prev, strstart, str_val)
                        as usize;

                let mut matched = false;
                if hash_head < strstart && strstart - hash_head <= max_dist {
                    let m: &[u8; STD_MAX_MATCH] = first_chunk(&window[hash_head..]).unwrap();

                    if str_val == u32::from_le_bytes([m[0], m[1], m[2], m[3]]) {
                        let match_len =
                            crate::deflate::compare256::compare256_quick_slice(&cur[2..], &m[2..])
                                + 2;

                        if match_len >= WANT_MIN_MATCH {
                            // `lookahead >= MIN_LOOKAHEAD > STD_MAX_MATCH`, so the clamp to
                            // `lookahead` of the general path is the identity here.
                            let match_len = Ord::min(match_len, STD_MAX_MATCH);
                            let dist = (((strstart - hash_head - 1) & 0x7FFF) + 1) as u16;

                            state
                                .bit_writer
                                .emit_dist_static((match_len - STD_MIN_MATCH) as u8, dist);
                            lookahead -= match_len;
                            strstart += match_len;
                            matched = true;
                        }
                    }
                }

                if !matched {
                    state
                        .bit_writer
                        .emit_lit(StaticTreeDesc::L.static_tree, str_val as u8);
                    strstart += 1;
                    lookahead -= 1;
                }

                if lookahead < MIN_LOOKAHEAD || state.bit_writer.pending.pending >= pending_limit {
                    break;
                }
            }

            state.strstart = strstart;
            state.lookahead = lookahead;
            continue;
        }

        let lc = if state.lookahead >= WANT_MIN_MATCH {
            let strstart = state.strstart;
            let window = state.window.filled();

            // Invariant: `strstart + MIN_LOOKAHEAD <= window_size` (asserted at the end of
            // `fill_window`, and `strstart + lookahead <= window_size` otherwise), so this
            // fixed-size view never fails. Every read relative to `strstart` below is then
            // provably in bounds.
            let cur: &[u8; MIN_LOOKAHEAD] = first_chunk(&window[strstart..]).unwrap();
            let str_val = u32::from_le_bytes([cur[0], cur[1], cur[2], cur[3]]);

            let hash_head = StandardHashCalc::quick_insert_value_in(
                &mut state.head,
                &mut state.prev,
                strstart,
                str_val,
            ) as usize;

            // Same test as `0 < strstart - hash_head <= max_dist`, in unsigned form so LLVM
            // can carry `hash_head < strstart` into the window bounds below.
            if hash_head < strstart && strstart - hash_head <= state.max_dist() {
                // `hash_head < strstart`, so the 258 bytes from `hash_head` lie inside the
                // window.
                let m: &[u8; STD_MAX_MATCH] = first_chunk(&window[hash_head..]).unwrap();

                if str_val == u32::from_le_bytes([m[0], m[1], m[2], m[3]]) {
                    let mut match_len =
                        crate::deflate::compare256::compare256_quick_slice(&cur[2..], &m[2..]) + 2;

                    if match_len >= WANT_MIN_MATCH {
                        match_len = Ord::min(match_len, state.lookahead);
                        match_len = Ord::min(match_len, STD_MAX_MATCH);

                        // TODO do this with a debug_assert?
                        // check_match(s, state.strstart, hash_head, match_len);

                        // `0 < dist <= max_dist < 2^15` (MAX_WBITS == 15), so this is the
                        // identity; written so LLVM sees `dist - 1 < 2^15` and drops the
                        // distance-code table bounds check and the u16 conversion check.
                        let dist = (((strstart - hash_head - 1) & 0x7FFF) + 1) as u16;

                        state
                            .bit_writer
                            .emit_dist_static((match_len - STD_MIN_MATCH) as u8, dist);
                        state.lookahead -= match_len;
                        state.strstart += match_len;
                        continue;
                    }
                }
            }
            str_val as u8
        } else {
            state.window.filled()[state.strstart]
        };
        state.bit_writer.emit_lit(StaticTreeDesc::L.static_tree, lc);
        state.strstart += 1;
        state.lookahead -= 1;
    }

    state.insert = Ord::min(state.strstart, STD_MIN_MATCH - 1);

    quick_end_block!(last);

    if last {
        BlockState::FinishDone
    } else {
        BlockState::BlockDone
    }
}