const POLY: u32 = 0x82F6_3B78;
const TABLE: [u32; 256] = build_table();
const fn build_table() -> [u32; 256] {
let mut table = [0u32; 256];
let mut n = 0usize;
while n < 256 {
let mut crc = n as u32;
let mut k = 0;
while k < 8 {
crc = if crc & 1 != 0 {
POLY ^ (crc >> 1)
} else {
crc >> 1
};
k += 1;
}
table[n] = crc;
n += 1;
}
table
}
#[must_use]
pub fn crc32c(seed: u32, data: &[u8]) -> u32 {
let mut crc = seed;
for &byte in data {
crc = (crc >> 8) ^ TABLE[((crc ^ u32::from(byte)) & 0xff) as usize];
}
crc
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn matches_the_standard_check_value() {
assert_eq!(crc32c(!0, b"123456789") ^ !0, 0xE306_9283);
}
#[test]
fn empty_input_returns_the_seed() {
assert_eq!(crc32c(0, b""), 0);
assert_eq!(crc32c(0xdead_beef, b""), 0xdead_beef);
}
#[test]
fn continuation_equals_a_single_pass() {
let whole = crc32c(!0, b"ferrosys");
let split = crc32c(crc32c(!0, b"ferro"), b"sys");
assert_eq!(whole, split);
}
#[test]
fn known_seed_over_a_single_zero_byte() {
assert_eq!(crc32c(0, &[0]), TABLE[0]);
assert_eq!(crc32c(0, &[0]), 0);
}
}