const POLY: u16 = 0xA001;
#[must_use]
pub fn checksum(data: &[u8]) -> u16 {
let mut crc: u16 = 0xFFFF;
for &byte in data {
crc ^= u16::from(byte);
for _ in 0..8 {
if crc & 1 != 0 {
crc = (crc >> 1) ^ POLY;
} else {
crc >>= 1;
}
}
}
crc
}
#[cfg(kani)]
mod kani_proofs {
use super::checksum;
#[kani::proof]
#[kani::unwind(17)]
fn checksum_never_panics() {
let data: [u8; 16] = kani::any();
let _ = checksum(&data);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn matches_pymodbus_on_a_read_holding_registers_request() {
let data = [0x11, 0x03, 0x00, 0x6B, 0x00, 0x03];
assert_eq!(checksum(&data), 0x8776);
}
#[test]
fn matches_pymodbus_on_a_read_coils_response() {
let data = [0x11, 0x01, 0x05, 0xCD, 0x6B, 0x05, 0x01, 0x00];
assert_eq!(checksum(&data), 0x3BB0);
}
#[test]
fn matches_pymodbus_on_an_exception_response() {
let data = [0x11, 0x83, 0x02];
assert_eq!(checksum(&data), 0x34C1);
}
}