1const fn table() -> [u16; 256] {
12 let mut t = [0u16; 256];
13 let mut i = 0usize;
14 while i < 256 {
15 #[allow(clippy::cast_possible_truncation)] let mut crc = (i as u16) << 8;
17 let mut bit = 0;
18 while bit < 8 {
19 crc = if crc & 0x8000 != 0 { (crc << 1) ^ 0x3D65 } else { crc << 1 };
20 bit += 1;
21 }
22 #[allow(clippy::indexing_slicing)] {
24 t[i] = crc;
25 }
26 i += 1;
27 }
28 t
29}
30
31static TABLE: [u16; 256] = table();
32
33pub fn crc16(bytes: &[u8]) -> u16 {
35 let mut crc = 0u16;
36 for &b in bytes {
37 let [high, _] = crc.to_be_bytes();
38 let idx = usize::from(high ^ b);
39 crc = (crc << 8) ^ TABLE.get(idx).copied().unwrap_or(0);
40 }
41 crc ^ 0xFFFF
42}
43
44pub fn crc16_x25(bytes: &[u8]) -> u16 {
46 let mut crc = 0xFFFFu16;
47 for &b in bytes {
48 crc ^= u16::from(b);
49 for _ in 0..8 {
50 crc = if crc & 1 != 0 { (crc >> 1) ^ 0x8408 } else { crc >> 1 };
51 }
52 }
53 !crc
54}
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59
60 #[test]
61 fn standard_check_value() {
62 assert_eq!(crc16(b"123456789"), 0xC2B7);
63 assert_eq!(crc16_x25(b"123456789"), 0x906E);
64 }
65}