use crate::constants::CRC32_POLY;
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
};
#[derive(Clone, Copy)]
pub struct Crc32 {
state: u32,
}
impl Crc32 {
pub const fn new() -> Self {
Self { state: 0xFFFF_FFFF }
}
#[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];
}
pub fn update(&mut self, data: &[u8]) {
for &b in data {
self.update_byte(b);
}
}
pub fn finish(self) -> u32 {
self.state ^ 0xFFFF_FFFF
}
pub fn reset(&mut self) {
self.state = 0xFFFF_FFFF;
}
}
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();
assert_eq!(crc.finish(), 0x0000_0000);
}
#[test]
fn known_value() {
let mut crc = Crc32::new();
crc.update(b"Hello");
let result = crc.finish();
assert_ne!(result, 0);
let mut crc2 = Crc32::new();
crc2.update(b"Hello");
assert_eq!(crc2.finish(), result);
}
}