use super::CRC32C_POLYNOMIAL;
pub(crate) const SLICE: usize = 8;
const fn build_tables() -> [[u32; 256]; SLICE] {
let mut tables = [[0u32; 256]; SLICE];
let mut index = 0usize;
while index < 256 {
let mut crc = index as u32;
let mut bit = 0;
while bit < 8 {
crc = if crc & 1 != 0 {
(crc >> 1) ^ CRC32C_POLYNOMIAL
} else {
crc >> 1
};
bit += 1;
}
tables[0][index] = crc;
index += 1;
}
let mut level = 1usize;
while level < SLICE {
let mut index = 0usize;
while index < 256 {
let previous = tables[level - 1][index];
tables[level][index] = (previous >> 8) ^ tables[0][(previous & 0xFF) as usize];
index += 1;
}
level += 1;
}
tables
}
pub(crate) static TABLES: [[u32; 256]; SLICE] = build_tables();
#[inline]
pub(crate) fn update_state_scalar(mut state: u32, data: &[u8]) -> u32 {
let mut rest = data;
while let Some((chunk, tail)) = split_chunk(rest) {
let low = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]) ^ state;
let high = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]);
state = TABLES[7][(low & 0xFF) as usize]
^ TABLES[6][((low >> 8) & 0xFF) as usize]
^ TABLES[5][((low >> 16) & 0xFF) as usize]
^ TABLES[4][((low >> 24) & 0xFF) as usize]
^ TABLES[3][(high & 0xFF) as usize]
^ TABLES[2][((high >> 8) & 0xFF) as usize]
^ TABLES[1][((high >> 16) & 0xFF) as usize]
^ TABLES[0][((high >> 24) & 0xFF) as usize];
rest = tail;
}
for &byte in rest {
state = (state >> 8) ^ TABLES[0][((state ^ u32::from(byte)) & 0xFF) as usize];
}
state
}
#[inline]
pub(crate) fn split_chunk(data: &[u8]) -> Option<(&[u8; SLICE], &[u8])> {
if data.len() < SLICE {
return None;
}
let (head, tail) = data.split_at(SLICE);
let head: &[u8; SLICE] = head.try_into().ok()?;
Some((head, tail))
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn tables_are_internally_consistent() {
for level in 1..SLICE {
let lower = &TABLES[level - 1];
let upper = &TABLES[level];
for (index, (&previous, &actual)) in lower.iter().zip(upper.iter()).enumerate() {
let expected = (previous >> 8) ^ TABLES[0][(previous & 0xFF) as usize];
assert_eq!(actual, expected, "table {level} entry {index}");
}
}
}
#[test]
fn split_chunk_reports_none_below_eight_bytes() {
for len in 0..SLICE {
let data = vec![0u8; len];
assert!(split_chunk(&data).is_none(), "len {len}");
}
}
#[test]
fn split_chunk_splits_at_exactly_eight_bytes() {
let data: Vec<u8> = (0..20u8).collect();
let (chunk, tail) = split_chunk(&data).expect("20 bytes is at least one chunk");
assert_eq!(chunk, &[0, 1, 2, 3, 4, 5, 6, 7]);
assert_eq!(tail, &data[8..]);
}
}