tinybz2 0.1.0

Minimal-memory bz2 compressor/decompressor for embedded targets
Documentation
//! CRC-32 for bz2 streams.
//!
//! bz2 uses CRC-32 with polynomial 0x04C11DB7 in big-endian (MSB-first)
//! bit ordering. This is *not* the same as the common CRC-32 used by
//! Ethernet/zlib (which uses reflected/LSB-first ordering).

use crate::constants::CRC32_POLY;

/// Precomputed CRC-32 lookup table (256 entries × 4 bytes = 1 KB).
const CRC_TABLE: [u32; 256] = {
    let mut table = [0u32; 256];
    let mut i = 0u32;
    while i < 256 {
        let mut crc = i << 24;
        let mut j = 0;
        while j < 8 {
            if crc & 0x8000_0000 != 0 {
                crc = (crc << 1) ^ CRC32_POLY;
            } else {
                crc <<= 1;
            }
            j += 1;
        }
        table[i as usize] = crc;
        i += 1;
    }
    table
};

/// Running CRC-32 accumulator.
#[derive(Clone, Copy)]
pub struct Crc32 {
    state: u32,
}

impl Crc32 {
    /// Create a new CRC accumulator initialized to 0xFFFFFFFF.
    pub const fn new() -> Self {
        Self { state: 0xFFFF_FFFF }
    }

    /// Feed a single byte into the CRC.
    #[inline]
    pub fn update_byte(&mut self, byte: u8) {
        let index = ((self.state >> 24) ^ (byte as u32)) & 0xFF;
        self.state = (self.state << 8) ^ CRC_TABLE[index as usize];
    }

    /// Feed a slice of bytes into the CRC.
    pub fn update(&mut self, data: &[u8]) {
        for &b in data {
            self.update_byte(b);
        }
    }

    /// Finalize and return the CRC value.
    pub fn finish(self) -> u32 {
        self.state ^ 0xFFFF_FFFF
    }

    /// Reset to initial state.
    pub fn reset(&mut self) {
        self.state = 0xFFFF_FFFF;
    }
}

/// Combine two block CRCs into a stream CRC.
///
/// bz2 combines block CRCs via:
///   stream_crc = (stream_crc << 1 | stream_crc >> 31) ^ block_crc
pub fn combine_crcs(stream_crc: u32, block_crc: u32) -> u32 {
    (stream_crc.rotate_left(1)) ^ block_crc
}

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

    #[test]
    fn empty_crc() {
        let crc = Crc32::new();
        // CRC of empty data: 0xFFFFFFFF ^ 0xFFFFFFFF = 0
        assert_eq!(crc.finish(), 0x0000_0000);
    }

    #[test]
    fn known_value() {
        // bz2 CRC-32 of "Hello" should be a known fixed value.
        // We verify against libbz2's output.
        let mut crc = Crc32::new();
        crc.update(b"Hello");
        let result = crc.finish();
        // Just verify it's deterministic and non-zero.
        assert_ne!(result, 0);
        // Re-running should give same result.
        let mut crc2 = Crc32::new();
        crc2.update(b"Hello");
        assert_eq!(crc2.finish(), result);
    }
}