pub fn crc16(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) ^ 0xA001;
} else {
crc >>= 1;
}
}
}
crc
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn matches_the_standard_check_value() {
assert_eq!(crc16(b"123456789"), 0x4B37);
}
#[test]
fn matches_a_known_read_request_frame() {
assert_eq!(crc16(&[0x01, 0x03, 0x00, 0x00, 0x00, 0x02]), 0x0BC4);
}
#[test]
fn matches_the_spec_read_request_frame() {
assert_eq!(crc16(&[0x11, 0x03, 0x00, 0x6B, 0x00, 0x03]), 0x8776);
}
#[test]
fn an_empty_slice_is_the_initial_value() {
assert_eq!(crc16(&[]), 0xFFFF);
}
}