const TABLE: [u16; 16] = [
0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, 0xA001, 0x6C00, 0x7800, 0xB401,
0x5000, 0x9C01, 0x8801, 0x4400,
];
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Crc(u16);
impl Crc {
#[must_use]
pub const fn new() -> Self {
Self(0)
}
pub fn update(&mut self, bytes: &[u8]) {
for &byte in bytes {
self.0 = nibble(nibble(self.0, byte & 0xF), byte >> 4);
}
}
#[must_use]
pub const fn value(self) -> u16 {
self.0
}
pub(crate) fn then(self, next: Self, len: u32) -> Self {
let mut step = zero_byte();
let mut crc = self.0;
for bit in 0..u32::BITS {
if len.wrapping_shr(bit) & 1 == 1 {
crc = apply(&step, crc);
}
step = step.map(|column| apply(&step, column));
}
Self(crc ^ next.0)
}
}
type Matrix = [u16; 16];
fn apply(m: &Matrix, v: u16) -> u16 {
(0..16u32)
.zip(m)
.filter(|&(i, _)| v.wrapping_shr(i) & 1 == 1)
.fold(0, |acc, (_, column)| acc ^ column)
}
fn zero_byte() -> Matrix {
core::array::from_fn(|i| {
let bit = 1u16.wrapping_shl(u32::try_from(i).unwrap_or(0));
nibble(nibble(bit, 0), 0)
})
}
fn nibble(crc: u16, nibble: u8) -> u16 {
let entry = |i: u16| TABLE.get(usize::from(i & 0xF)).copied().unwrap_or(0);
let tmp = entry(crc);
let crc = (crc >> 4) & 0x0FFF;
crc ^ tmp ^ entry(u16::from(nibble))
}
#[cfg(test)]
mod tests {
use super::Crc;
fn crc(bytes: &[u8]) -> u16 {
let mut c = Crc::new();
c.update(bytes);
c.value()
}
#[test]
fn then_joins_two_crcs() {
let bytes: std::vec::Vec<u8> = (0..=255u8).cycle().take(1000).collect();
for split in [0, 1, 2, 13, 14, 500, 999, 1000] {
let (a, b) = bytes.split_at(split);
let (mut ca, mut cb) = (Crc::new(), Crc::new());
ca.update(a);
cb.update(b);
let len = u32::try_from(b.len()).unwrap();
assert_eq!(ca.then(cb, len).value(), crc(&bytes), "split at {split}");
}
}
#[test]
fn known_vectors() {
assert_eq!(crc(b""), 0x0000);
assert_eq!(crc(b"123456789"), 0xBB3D);
assert_eq!(crc(&[0x00]), 0x0000);
assert_eq!(crc(&[0x01]), 0xC0C1);
assert_eq!(crc(&[0xFF]), 0x4040);
assert_eq!(crc(b"A"), 0x30C0);
}
#[test]
fn a_file_ending_in_its_crc_checks_to_zero() {
let mut bytes = b"any bytes at all".to_vec();
let c = crc(&bytes);
bytes.extend_from_slice(&c.to_le_bytes());
assert_eq!(crc(&bytes), 0);
}
#[test]
fn updates_compose() {
let mut c = Crc::new();
c.update(b"1234");
c.update(b"56789");
assert_eq!(c.value(), crc(b"123456789"));
}
}