const INITIAL: u16 = 0xFFFF;
#[allow(
clippy::cast_possible_truncation,
reason = "intentionally takes only the low byte of crc, matching pymavlink's `accum & 0xFF`"
)]
fn accumulate_byte(crc: u16, byte: u8) -> u16 {
let mut tmp = byte ^ (crc as u8);
tmp ^= tmp << 4;
let tmp = u16::from(tmp);
(crc >> 8) ^ (tmp << 8) ^ (tmp << 3) ^ (tmp >> 4)
}
#[must_use]
pub fn checksum(header_and_payload: &[u8], crc_extra: u8) -> u16 {
let mut crc = INITIAL;
for &byte in header_and_payload {
crc = accumulate_byte(crc, byte);
}
accumulate_byte(crc, crc_extra)
}
#[cfg(kani)]
mod kani_proofs {
use super::checksum;
#[kani::proof]
fn checksum_never_panics() {
let data: [u8; 16] = kani::any();
let crc_extra: u8 = kani::any();
let _ = checksum(&data, crc_extra);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn matches_pymavlink_on_an_arbitrary_buffer() {
let mut crc = INITIAL;
for b in [1u8, 2, 3, 4, 5] {
crc = accumulate_byte(crc, b);
}
assert_eq!(crc, 0xdd13);
}
#[test]
fn matches_a_real_captured_heartbeat_frame() {
#[rustfmt::skip]
let header_and_payload: [u8; 18] = [
0x09, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x51, 0x04, 0x03, ];
assert_eq!(checksum(&header_and_payload, 50), 0x1ee7);
}
}