mbrtu 0.1.2

no_std, no_alloc parser and encoder for Modbus RTU PDUs
Documentation
//! Modbus RTU's CRC-16 (poly `0xA001`, the reflected form of `0x8005`,
//! init `0xFFFF`), computed over the address, function code, and data of
//! a frame. Cross-checked against `pymodbus`'s own `compute_CRC`.

const POLY: u16 = 0xA001;

/// Computes the CRC-16 checksum over `data` (for a full frame, the
/// address byte through the end of the PDU data, everything except the
/// trailing 2-byte CRC itself).
///
/// The result is a 16-bit register value; on the wire, Modbus RTU
/// transmits its low byte first and its high byte second (see
/// [`crate::frame::encode`]).
#[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
}

// A nested loop over a &[u8] parameter does not get an automatically
// inferred concrete unwind bound from CBMC, even when the call site
// happens to pass a fixed-size array - the outer loop needs an explicit
// bound regardless of caller. The inner `0..8` loop is a fixed literal
// range and needs no bound of its own.
#[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() {
        // pymodbus's FramerRTU.compute_CRC over the classic Modbus spec
        // example: unit 0x11, function 0x03 (Read Holding Registers),
        // starting address 0x006B, quantity 3.
        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);
    }
}