mbrtu 0.1.2

no_std, no_alloc parser and encoder for Modbus RTU PDUs
Documentation
//! Read Holding Registers (function code 3): the most common Modbus
//! operation, reading a contiguous block of 16-bit holding registers from
//! a device.

use crate::error::MessageError;

/// This message's function code.
pub const FUNCTION_CODE: u8 = 0x03;

/// Largest number of registers a single response can carry: the 256-byte
/// Modbus RTU ADU limit leaves 252 bytes of PDU data, of which 1 byte is
/// the byte count, leaving 251 bytes for register data - rounded down to
/// 125 whole registers, exactly the limit the Modbus spec itself states.
pub const MAX_REGISTERS: usize = 125;

/// A Read Holding Registers request: which registers to read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReadHoldingRegistersRequest {
    /// Address of the first register to read.
    pub starting_address: u16,
    /// Number of registers to read (1-125).
    pub quantity: u16,
}

impl ReadHoldingRegistersRequest {
    pub(crate) fn decode(data: &[u8]) -> Result<Self, MessageError> {
        let [a1, a0, q1, q0, ..] = data else {
            return Err(MessageError::UnexpectedEof);
        };
        let quantity = u16::from_be_bytes([*q1, *q0]);
        if usize::from(quantity) > MAX_REGISTERS {
            return Err(MessageError::TooManyItems {
                max: MAX_REGISTERS,
                got: usize::from(quantity),
            });
        }
        Ok(Self {
            starting_address: u16::from_be_bytes([*a1, *a0]),
            quantity,
        })
    }

    pub(crate) fn encode(self, buf: &mut [u8]) -> Result<usize, MessageError> {
        let [d0, d1, d2, d3, ..] = buf else {
            return Err(MessageError::BufferFull);
        };
        [*d0, *d1] = self.starting_address.to_be_bytes();
        [*d2, *d3] = self.quantity.to_be_bytes();
        Ok(4)
    }
}

/// A Read Holding Registers response: the register values read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReadHoldingRegistersResponse {
    /// Number of valid entries at the start of `registers`.
    pub count: u8,
    /// Register values, indexed in request order (only the first `count`
    /// entries are meaningful; the rest are unused padding).
    pub registers: [u16; MAX_REGISTERS],
}

impl ReadHoldingRegistersResponse {
    pub(crate) fn decode(data: &[u8]) -> Result<Self, MessageError> {
        let [byte_count, rest @ ..] = data else {
            return Err(MessageError::UnexpectedEof);
        };
        if usize::from(*byte_count) > rest.len() {
            return Err(MessageError::ByteCountMismatch {
                declared: *byte_count,
                available: rest.len(),
            });
        }
        let count = byte_count / 2;
        if usize::from(count) > MAX_REGISTERS {
            return Err(MessageError::TooManyItems {
                max: MAX_REGISTERS,
                got: usize::from(count),
            });
        }

        let mut registers = [0u16; MAX_REGISTERS];
        for (i, reg) in registers.iter_mut().take(usize::from(count)).enumerate() {
            *reg = u16::from_be_bytes([rest[2 * i], rest[2 * i + 1]]);
        }
        Ok(Self { count, registers })
    }

    pub(crate) fn encode(self, buf: &mut [u8]) -> Result<usize, MessageError> {
        if usize::from(self.count) > MAX_REGISTERS {
            return Err(MessageError::TooManyItems {
                max: MAX_REGISTERS,
                got: usize::from(self.count),
            });
        }
        let byte_count = usize::from(self.count) * 2;
        let total = 1 + byte_count;
        let Some(dest) = buf.get_mut(..total) else {
            return Err(MessageError::BufferFull);
        };
        #[allow(
            clippy::cast_possible_truncation,
            reason = "checked above: count <= MAX_REGISTERS (125), so count * 2 <= 250, always fits in u8"
        )]
        {
            dest[0] = byte_count as u8;
        }
        for (i, reg) in self
            .registers
            .iter()
            .take(usize::from(self.count))
            .enumerate()
        {
            dest[1 + 2 * i..3 + 2 * i].copy_from_slice(&reg.to_be_bytes());
        }
        Ok(total)
    }
}

// `count` is a public field, independent of `registers`' fixed size, so
// encode's own bounds check (not just decode's) needs to hold for every
// possible count, not just the ones a real decode would ever produce.
// The loop over `.take(usize::from(self.count))` needs an explicit
// #[kani::unwind] bound the same way crc.rs's loop does - CBMC does not
// infer one on its own for a loop whose bound comes from a runtime value.
#[cfg(kani)]
mod kani_proofs {
    use super::{MAX_REGISTERS, ReadHoldingRegistersResponse};

    #[kani::proof]
    #[kani::unwind(126)]
    fn encode_never_panics() {
        let count: u8 = kani::any();
        let registers = [0u16; MAX_REGISTERS];
        let msg = ReadHoldingRegistersResponse { count, registers };
        let mut buf = [0u8; 1 + MAX_REGISTERS * 2];
        let _ = msg.encode(&mut buf);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn decodes_a_reference_request() {
        // Cross-checked against pymodbus (the classic Modbus spec
        // example).
        let data = [0x00, 0x6B, 0x00, 0x03];
        let req = ReadHoldingRegistersRequest::decode(&data).unwrap();
        assert_eq!(req.starting_address, 0x006B);
        assert_eq!(req.quantity, 3);
    }

    #[test]
    fn rejects_a_request_quantity_over_the_spec_maximum() {
        // 126 registers: one past MAX_REGISTERS (125), the limit the
        // Modbus spec itself states for this function code.
        let data = [0x00, 0x00, 0x00, 0x7E];
        assert_eq!(
            ReadHoldingRegistersRequest::decode(&data),
            Err(MessageError::TooManyItems {
                max: MAX_REGISTERS,
                got: 126
            })
        );
    }

    #[test]
    fn decodes_a_reference_response() {
        let data = [0x06, 0x02, 0x2B, 0x00, 0x00, 0x00, 0x64];
        let resp = ReadHoldingRegistersResponse::decode(&data).unwrap();
        assert_eq!(resp.count, 3);
        assert_eq!(&resp.registers[..3], &[0x022B, 0x0000, 0x0064]);
    }

    #[test]
    fn rejects_a_byte_count_longer_than_the_data() {
        let data = [0x04, 0x00, 0x01];
        assert_eq!(
            ReadHoldingRegistersResponse::decode(&data),
            Err(MessageError::ByteCountMismatch {
                declared: 4,
                available: 2
            })
        );
    }

    #[test]
    fn round_trips_a_request() {
        let original = ReadHoldingRegistersRequest {
            starting_address: 0x0100,
            quantity: 10,
        };
        let mut buf = [0u8; 4];
        let n = original.encode(&mut buf).unwrap();
        assert_eq!(
            ReadHoldingRegistersRequest::decode(&buf[..n]).unwrap(),
            original
        );
    }

    #[test]
    fn round_trips_a_response() {
        let mut registers = [0u16; MAX_REGISTERS];
        registers[0] = 0x1234;
        registers[1] = 0xABCD;
        let original = ReadHoldingRegistersResponse {
            count: 2,
            registers,
        };
        let mut buf = [0u8; 1 + MAX_REGISTERS * 2];
        let n = original.encode(&mut buf).unwrap();
        let decoded = ReadHoldingRegistersResponse::decode(&buf[..n]).unwrap();
        assert_eq!(decoded.count, 2);
        assert_eq!(&decoded.registers[..2], &registers[..2]);
    }

    // `count` is a public field, so nothing stops a caller from
    // constructing a response whose declared count exceeds MAX_REGISTERS
    // even though `registers` only ever backs that many entries - decode
    // already rejects this on the way in, but encode used to trust count
    // unconditionally, silently truncating `count * 2` as it cast to u8
    // and writing a byte_count that didn't match the frame's real length.
    #[test]
    fn encode_rejects_a_count_wider_than_the_backing_array() {
        let bad = ReadHoldingRegistersResponse {
            count: 200,
            registers: [0xAAAAu16; MAX_REGISTERS],
        };
        let mut buf = [0u8; 1000];
        assert_eq!(
            bad.encode(&mut buf),
            Err(MessageError::TooManyItems {
                max: MAX_REGISTERS,
                got: 200
            })
        );
    }
}