zexc 1.2.1

zex native lossless compressor — CLI zexc, library zexc, files *.zex
Documentation
//! Little-endian bit stream writer / reader (Zstd-style LIFO bit container).
//!
//! Zstandard's FSE/Huffman reverse-bitstream is sophisticated; this module provides
//! a practical forward LE bit packer used by the high-ratio backend for codes.

use alloc::vec::Vec;

/// Bit writer — packs bits LSB-first into a growing byte buffer.
#[derive(Debug, Default)]
pub struct BitWriter {
    buf: Vec<u8>,
    /// Partial byte accumulator (low bits filled first).
    acc: u64,
    /// Number of valid bits in `acc`.
    nbits: u32,
}

impl BitWriter {
    /// New empty writer.
    pub fn new() -> Self {
        Self::default()
    }

    /// With capacity hint (bytes).
    pub fn with_capacity(cap: usize) -> Self {
        Self {
            buf: Vec::with_capacity(cap),
            acc: 0,
            nbits: 0,
        }
    }

    /// Write the low `n` bits of `value` (n ≤ 32).
    #[inline]
    pub fn write_bits(&mut self, value: u32, n: u32) {
        debug_assert!(n <= 32);
        if n == 0 {
            return;
        }
        let mask = if n == 32 { u32::MAX } else { (1u32 << n) - 1 };
        self.acc |= u64::from(value & mask) << self.nbits;
        self.nbits += n;
        while self.nbits >= 8 {
            self.buf.push(self.acc as u8);
            self.acc >>= 8;
            self.nbits -= 8;
        }
    }

    /// Write a single bit (0 or 1).
    #[inline]
    pub fn write_bit(&mut self, bit: bool) {
        self.write_bits(u32::from(bit), 1);
    }

    /// Align to next byte boundary (pad with zeros).
    pub fn align_byte(&mut self) {
        if self.nbits > 0 {
            self.buf.push(self.acc as u8);
            self.acc = 0;
            self.nbits = 0;
        }
    }

    /// Finish and return the byte buffer (aligned).
    pub fn finish(mut self) -> Vec<u8> {
        self.align_byte();
        self.buf
    }

    /// Bytes written so far (not counting partial bits).
    pub fn len(&self) -> usize {
        self.buf.len()
    }

    /// Whether no complete bytes and no pending bits.
    pub fn is_empty(&self) -> bool {
        self.buf.is_empty() && self.nbits == 0
    }

    /// Access completed bytes without finishing.
    pub fn as_bytes(&self) -> &[u8] {
        &self.buf
    }
}

/// Bit reader — reads bits LSB-first from a slice.
#[derive(Debug, Clone)]
pub struct BitReader<'a> {
    data: &'a [u8],
    pos: usize,
    acc: u64,
    nbits: u32,
}

impl<'a> BitReader<'a> {
    /// Create over `data`.
    pub fn new(data: &'a [u8]) -> Self {
        Self {
            data,
            pos: 0,
            acc: 0,
            nbits: 0,
        }
    }

    #[inline]
    fn refill(&mut self) {
        while self.nbits <= 56 && self.pos < self.data.len() {
            self.acc |= u64::from(self.data[self.pos]) << self.nbits;
            self.nbits += 8;
            self.pos += 1;
        }
    }

    /// Read `n` bits (n ≤ 32). Returns `None` if stream exhausted.
    #[inline]
    pub fn read_bits(&mut self, n: u32) -> Option<u32> {
        debug_assert!(n <= 32);
        if n == 0 {
            return Some(0);
        }
        self.refill();
        if self.nbits < n {
            return None;
        }
        let mask = if n == 32 { u32::MAX } else { (1u32 << n) - 1 };
        let v = (self.acc as u32) & mask;
        self.acc >>= n;
        self.nbits -= n;
        Some(v)
    }

    /// Peek `n` bits without consuming them.
    #[inline]
    pub fn peek_bits(&mut self, n: u32) -> Option<u32> {
        debug_assert!(n <= 32);
        if n == 0 {
            return Some(0);
        }
        self.refill();
        if self.nbits < n {
            return None;
        }
        let mask = if n == 32 { u32::MAX } else { (1u32 << n) - 1 };
        Some((self.acc as u32) & mask)
    }

    /// Peek `n` bits, treating missing high bits at EOF as zero (for Huffman tables).
    ///
    /// Returns `None` only when the stream is completely empty (no bits left at all).
    #[inline]
    pub fn peek_bits_padded(&mut self, n: u32) -> Option<u32> {
        debug_assert!(n <= 32);
        if n == 0 {
            return Some(0);
        }
        self.refill();
        if self.nbits == 0 && self.pos >= self.data.len() {
            return None;
        }
        let mask = if n == 32 { u32::MAX } else { (1u32 << n) - 1 };
        Some((self.acc as u32) & mask)
    }

    /// Force refill of the bit accumulator from the byte stream.
    #[inline]
    pub fn ensure_bits(&mut self) {
        self.refill();
    }

    /// Number of bits currently buffered (not yet consumed).
    pub fn bits_available(&self) -> u32 {
        self.nbits
    }

    /// Read one bit.
    #[inline]
    pub fn read_bit(&mut self) -> Option<bool> {
        self.read_bits(1).map(|b| b != 0)
    }

    /// Skip to next byte boundary.
    pub fn align_byte(&mut self) {
        let rem = self.nbits % 8;
        if rem != 0 {
            self.acc >>= rem;
            self.nbits -= rem;
        }
    }

    /// Bytes remaining in the underlying slice (not counting buffered bits carefully).
    pub fn remaining_bytes(&self) -> usize {
        self.data.len().saturating_sub(self.pos)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bit_roundtrip() {
        let mut w = BitWriter::new();
        w.write_bits(0b1011, 4);
        w.write_bits(0xAB, 8);
        w.write_bits(0x1234, 16);
        w.write_bit(true);
        let bytes = w.finish();
        let mut r = BitReader::new(&bytes);
        assert_eq!(r.read_bits(4).unwrap(), 0b1011);
        assert_eq!(r.read_bits(8).unwrap(), 0xAB);
        assert_eq!(r.read_bits(16).unwrap(), 0x1234);
        assert!(r.read_bit().unwrap());
    }
}