1const TABLE: [u16; 16] = [
5 0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, 0xA001, 0x6C00, 0x7800, 0xB401,
6 0x5000, 0x9C01, 0x8801, 0x4400,
7];
8
9#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
17pub struct Crc(u16);
18
19impl Crc {
20 #[must_use]
22 pub const fn new() -> Self {
23 Self(0)
24 }
25
26 pub fn update(&mut self, bytes: &[u8]) {
28 for &byte in bytes {
29 self.0 = nibble(nibble(self.0, byte & 0xF), byte >> 4);
30 }
31 }
32
33 #[must_use]
35 pub const fn value(self) -> u16 {
36 self.0
37 }
38
39 pub(crate) fn then(self, next: Self, len: u32) -> Self {
44 let mut step = zero_byte();
45 let mut crc = self.0;
46 for bit in 0..u32::BITS {
47 if len.wrapping_shr(bit) & 1 == 1 {
48 crc = apply(&step, crc);
49 }
50 step = step.map(|column| apply(&step, column));
51 }
52 Self(crc ^ next.0)
53 }
54}
55
56type Matrix = [u16; 16];
58
59fn apply(m: &Matrix, v: u16) -> u16 {
60 (0..16u32)
61 .zip(m)
62 .filter(|&(i, _)| v.wrapping_shr(i) & 1 == 1)
63 .fold(0, |acc, (_, column)| acc ^ column)
64}
65
66fn zero_byte() -> Matrix {
68 core::array::from_fn(|i| {
69 let bit = 1u16.wrapping_shl(u32::try_from(i).unwrap_or(0));
70 nibble(nibble(bit, 0), 0)
71 })
72}
73
74fn nibble(crc: u16, nibble: u8) -> u16 {
75 let entry = |i: u16| TABLE.get(usize::from(i & 0xF)).copied().unwrap_or(0);
76 let tmp = entry(crc);
77 let crc = (crc >> 4) & 0x0FFF;
78 crc ^ tmp ^ entry(u16::from(nibble))
79}
80
81#[cfg(test)]
82mod tests {
83 use super::Crc;
84
85 fn crc(bytes: &[u8]) -> u16 {
86 let mut c = Crc::new();
87 c.update(bytes);
88 c.value()
89 }
90
91 #[test]
92 fn then_joins_two_crcs() {
93 let bytes: std::vec::Vec<u8> = (0..=255u8).cycle().take(1000).collect();
94 for split in [0, 1, 2, 13, 14, 500, 999, 1000] {
95 let (a, b) = bytes.split_at(split);
96 let (mut ca, mut cb) = (Crc::new(), Crc::new());
97 ca.update(a);
98 cb.update(b);
99 let len = u32::try_from(b.len()).unwrap();
100 assert_eq!(ca.then(cb, len).value(), crc(&bytes), "split at {split}");
101 }
102 }
103
104 #[test]
105 fn known_vectors() {
106 assert_eq!(crc(b""), 0x0000);
108 assert_eq!(crc(b"123456789"), 0xBB3D);
109 assert_eq!(crc(&[0x00]), 0x0000);
110 assert_eq!(crc(&[0x01]), 0xC0C1);
111 assert_eq!(crc(&[0xFF]), 0x4040);
112 assert_eq!(crc(b"A"), 0x30C0);
113 }
114
115 #[test]
116 fn a_file_ending_in_its_crc_checks_to_zero() {
117 let mut bytes = b"any bytes at all".to_vec();
118 let c = crc(&bytes);
119 bytes.extend_from_slice(&c.to_le_bytes());
120 assert_eq!(crc(&bytes), 0);
121 }
122
123 #[test]
124 fn updates_compose() {
125 let mut c = Crc::new();
126 c.update(b"1234");
127 c.update(b"56789");
128 assert_eq!(c.value(), crc(b"123456789"));
129 }
130}