const fn table() -> [u16; 256] {
let mut t = [0u16; 256];
let mut i = 0usize;
while i < 256 {
#[allow(clippy::cast_possible_truncation)] let mut crc = (i as u16) << 8;
let mut bit = 0;
while bit < 8 {
crc = if crc & 0x8000 != 0 { (crc << 1) ^ 0x3D65 } else { crc << 1 };
bit += 1;
}
#[allow(clippy::indexing_slicing)] {
t[i] = crc;
}
i += 1;
}
t
}
static TABLE: [u16; 256] = table();
pub fn crc16(bytes: &[u8]) -> u16 {
let mut crc = 0u16;
for &b in bytes {
let [high, _] = crc.to_be_bytes();
let idx = usize::from(high ^ b);
crc = (crc << 8) ^ TABLE.get(idx).copied().unwrap_or(0);
}
crc ^ 0xFFFF
}
pub fn crc16_x25(bytes: &[u8]) -> u16 {
let mut crc = 0xFFFFu16;
for &b in bytes {
crc ^= u16::from(b);
for _ in 0..8 {
crc = if crc & 1 != 0 { (crc >> 1) ^ 0x8408 } else { crc >> 1 };
}
}
!crc
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn standard_check_value() {
assert_eq!(crc16(b"123456789"), 0xC2B7);
assert_eq!(crc16_x25(b"123456789"), 0x906E);
}
}