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
// taken from https://docs.rs/tokio/latest/src/tokio/io/read_buf.rs.html#23-27
// based on https://rust-lang.github.io/rfcs/2930-read-buf.html

use core::mem::MaybeUninit;

use crate::weak_slice::WeakSliceMut;

/// House delta (rusty_zlib): the buffer is `MaybeUninit<u8>` and is never zeroed. Every push
/// writes all 3 bytes of its slot, and only `[..filled]` is ever read, so nothing reads a byte
/// that was not written. Upstream zeroed 48 KiB per block, then (house delta 1) per init.
pub(crate) struct SymBuf<'a> {
    buf: WeakSliceMut<'a, MaybeUninit<u8>>,
    filled: usize,
}

impl<'a> SymBuf<'a> {
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = (u16, u8)> + '_ {
        let filled = &self.buf.as_slice()[..self.filled];
        // SAFETY: every byte below `filled` was written by `push_lit` or `push_dist`, which
        // both write all 3 bytes of the slot they append.
        let filled: &[u8] =
            unsafe { core::slice::from_raw_parts(filled.as_ptr().cast(), filled.len()) };
        filled.chunks_exact(3).map(|chunk| match *chunk {
            [dist_low, dist_high, lc] => (u16::from_le_bytes([dist_low, dist_high]), lc),
            _ => unreachable!("chunks are exactly 3 elements wide"),
        })
    }

    #[inline]
    pub fn should_flush_block(&self) -> bool {
        self.filled == self.buf.len() - 3
    }

    /// Returns true if there are no bytes in this ReadBuf
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.filled == 0
    }

    /// Clears the buffer, resetting the filled region to empty.
    ///
    /// The number of initialized bytes is not changed, and the contents of the buffer are not modified.
    ///
    /// House delta (rusty_zlib): upstream zeroed the WHOLE buffer here (`lit_bufsize * 3`
    /// bytes, 48 KiB at the default mem_level) on every block, so that `push_lit` could write
    /// only the literal byte. Only `[..filled]` is ever read, so `push_lit` now writes its
    /// zero distance itself and this is O(1). The buffer is zeroed once at allocation.
    #[inline]
    pub fn clear(&mut self) {
        self.filled = 0;
    }

    #[inline(always)]
    pub fn push_lit(&mut self, byte: u8) {
        // A literal is stored as distance 0 followed by the byte. One bounds check, as
        // upstream had: the checked store at `filled + 2` proves the whole slot is in range.
        let i = self.filled;
        let buf = self.buf.as_mut_slice();
        buf[i + 2] = MaybeUninit::new(byte);
        // SAFETY: `filled <= buf.len()` always holds, so `i + 2` cannot have wrapped, and the
        // store above proved `i + 2 < buf.len()`; bytes `i` and `i + 1` are therefore in bounds.
        unsafe { core::ptr::write_unaligned(buf.as_mut_ptr().add(i).cast::<[u8; 2]>(), [0, 0]) };

        self.filled += 3;
    }

    #[inline(always)]
    pub fn push_dist(&mut self, dist: u16, len: u8) {
        let buf = &mut self.buf.as_mut_slice()[self.filled..][..3];

        // Write both dist bytes as a single 2-byte store. This avoids the
        // `movb %ch, [mem]` instruction pattern (store from high-byte register
        // alias) that LLVM otherwise emits when dist arrives as a wide register.
        // That pattern triggers the Intel Raptor Lake CPU errata, causing silent
        // 2-byte stores that corrupt the adjacent `len` byte.
        // SAFETY: buf has at least 3 bytes (guaranteed above), so the unaligned
        // 2-byte write at offset 0 stays within bounds.
        unsafe {
            core::ptr::write_unaligned(buf.as_mut_ptr().cast::<[u8; 2]>(), dist.to_le_bytes())
        };
        buf[2] = MaybeUninit::new(len);

        self.filled += 3;
    }

    pub(crate) unsafe fn from_raw_parts(ptr: *mut u8, lit_bufsize: usize) -> Self {
        Self {
            buf: unsafe { WeakSliceMut::from_raw_parts_mut(ptr.cast(), lit_bufsize * 3) },
            filled: 0,
        }
    }

    pub(crate) unsafe fn clone_to(&self, ptr: *mut u8) -> Self {
        // An untyped copy: bytes beyond `filled` may be uninitialized, which is fine here.
        unsafe { ptr.copy_from_nonoverlapping(self.buf.as_ptr().cast(), self.buf.len()) };
        Self {
            buf: unsafe { WeakSliceMut::from_raw_parts_mut(ptr.cast(), self.buf.len()) },
            filled: self.filled,
        }
    }
}