mbrtu 0.1.2

no_std, no_alloc parser and encoder for Modbus RTU PDUs
Documentation
//! Read Coils (function code 1): reads a contiguous block of single-bit
//! coil (discrete output) values from a device.
//!
//! A coil response only carries a byte count, not a bit count: the last
//! byte's unused high bits (when the coil count isn't a multiple of 8)
//! are padding whose value the spec leaves unspecified, and telling them
//! apart from real coil data requires knowing the request's `quantity` -
//! information this PDU alone doesn't carry. [`ReadCoilsResponse::get`]
//! is bounded by the full byte-aligned bit count for that reason; callers
//! who need the exact requested count should track it themselves
//! alongside the matching [`ReadCoilsRequest`].

use crate::error::MessageError;

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

/// Largest number of coils a single response can carry, per the Modbus
/// spec (also exactly what the 256-byte RTU ADU limit allows: 252 bytes
/// of PDU data, minus 1 byte for the byte count, times 8 bits/byte).
pub const MAX_COILS: usize = 2000;
/// Bytes needed to hold [`MAX_COILS`] packed bits, one bit per coil.
pub const MAX_COIL_BYTES: usize = MAX_COILS.div_ceil(8);

/// A Read Coils request: which coils to read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReadCoilsRequest {
    /// Address of the first coil to read.
    pub starting_address: u16,
    /// Number of coils to read (1-2000).
    pub quantity: u16,
}

impl ReadCoilsRequest {
    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_COILS {
            return Err(MessageError::TooManyItems {
                max: MAX_COILS,
                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 Coils response: the coil values read, packed one bit per coil
/// (LSB of the first byte is the first requested coil), byte-aligned.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReadCoilsResponse {
    /// Number of valid bytes at the start of `bits`.
    pub byte_count: u8,
    /// Packed coil bits (see [`ReadCoilsResponse::get`]).
    pub bits: [u8; MAX_COIL_BYTES],
}

impl ReadCoilsResponse {
    /// Reads the coil at `index` (`0` is the first requested coil).
    /// Returns `None` if `index` falls outside the byte-aligned data this
    /// response actually carries (see the module docs on why that may
    /// include a few undefined padding bits beyond the real request).
    #[must_use]
    pub fn get(&self, index: usize) -> Option<bool> {
        if index >= usize::from(self.byte_count) * 8 {
            return None;
        }
        Some(self.bits[index / 8] & (1 << (index % 8)) != 0)
    }

    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(),
            });
        }
        if usize::from(*byte_count) > MAX_COIL_BYTES {
            return Err(MessageError::TooManyItems {
                max: MAX_COIL_BYTES,
                got: usize::from(*byte_count),
            });
        }

        let mut bits = [0u8; MAX_COIL_BYTES];
        bits[..usize::from(*byte_count)].copy_from_slice(&rest[..usize::from(*byte_count)]);
        Ok(Self {
            byte_count: *byte_count,
            bits,
        })
    }

    pub(crate) fn encode(&self, buf: &mut [u8]) -> Result<usize, MessageError> {
        if usize::from(self.byte_count) > MAX_COIL_BYTES {
            return Err(MessageError::TooManyItems {
                max: MAX_COIL_BYTES,
                got: usize::from(self.byte_count),
            });
        }
        let total = 1 + usize::from(self.byte_count);
        let Some(dest) = buf.get_mut(..total) else {
            return Err(MessageError::BufferFull);
        };
        dest[0] = self.byte_count;
        dest[1..].copy_from_slice(&self.bits[..usize::from(self.byte_count)]);
        Ok(total)
    }
}

// `byte_count` is a public field, independent of `bits`' fixed size, so
// encode's own bounds check (not just decode's) needs to hold for every
// possible byte_count, not just the ones a real decode would ever
// produce - this is exactly the bounds check whose absence used to panic
// while slicing `bits` past its length.
#[cfg(kani)]
mod kani_proofs {
    use super::{MAX_COIL_BYTES, ReadCoilsResponse};

    #[kani::proof]
    fn encode_never_panics() {
        let byte_count: u8 = kani::any();
        let bits = [0u8; MAX_COIL_BYTES];
        let msg = ReadCoilsResponse { byte_count, bits };
        let mut buf = [0u8; 1 + MAX_COIL_BYTES];
        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): starting address 0x0013, quantity 0x0025 (37 coils).
        let data = [0x00, 0x13, 0x00, 0x25];
        let req = ReadCoilsRequest::decode(&data).unwrap();
        assert_eq!(req.starting_address, 0x0013);
        assert_eq!(req.quantity, 0x0025);
    }

    #[test]
    fn rejects_a_request_quantity_over_the_spec_maximum() {
        // 2001 coils: one past MAX_COILS (2000), the limit the Modbus
        // spec itself states for this function code.
        let data = [0x00, 0x00, 0x07, 0xD1];
        assert_eq!(
            ReadCoilsRequest::decode(&data),
            Err(MessageError::TooManyItems {
                max: MAX_COILS,
                got: 2001
            })
        );
    }

    #[test]
    fn decodes_a_reference_response() {
        let data = [0x05, 0xCD, 0x6B, 0x05, 0x01, 0x00];
        let resp = ReadCoilsResponse::decode(&data).unwrap();
        assert_eq!(resp.byte_count, 5);
        // 0xCD = 1100_1101 -> LSB-first: coil0=1,1=0,2=1,3=1,4=0,5=0,6=1,7=1
        assert_eq!(resp.get(0), Some(true));
        assert_eq!(resp.get(1), Some(false));
        assert_eq!(resp.get(2), Some(true));
        assert_eq!(resp.get(3), Some(true));
        assert_eq!(resp.get(4), Some(false));
        assert_eq!(resp.get(5), Some(false));
        assert_eq!(resp.get(6), Some(true));
        assert_eq!(resp.get(7), Some(true));
        // byte index 3 (0x01) covers coils 24-31 and only has bit 0 set -> coil 24
        assert_eq!(resp.get(24), Some(true));
        assert_eq!(resp.get(25), Some(false));
        assert_eq!(resp.get(40), None); // beyond byte_count*8 = 40
    }

    #[test]
    fn rejects_a_byte_count_longer_than_the_data() {
        let data = [0x05, 0xCD];
        assert_eq!(
            ReadCoilsResponse::decode(&data),
            Err(MessageError::ByteCountMismatch {
                declared: 5,
                available: 1
            })
        );
    }

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

    #[test]
    fn round_trips_a_response() {
        let mut bits = [0u8; MAX_COIL_BYTES];
        bits[0] = 0xCD;
        bits[1] = 0x6B;
        let original = ReadCoilsResponse {
            byte_count: 2,
            bits,
        };
        let mut buf = [0u8; 1 + MAX_COIL_BYTES];
        let n = original.encode(&mut buf).unwrap();
        let decoded = ReadCoilsResponse::decode(&buf[..n]).unwrap();
        assert_eq!(decoded, original);
    }

    // `byte_count` is a public field, so nothing stops a caller from
    // constructing a `ReadCoilsResponse` whose declared byte_count exceeds
    // what `bits` (a fixed-size array) can actually back - decode already
    // rejects this on the way in, but encode used to trust byte_count
    // unconditionally and panic while slicing `bits` past its length.
    #[test]
    fn encode_rejects_a_byte_count_wider_than_the_backing_array() {
        let bad = ReadCoilsResponse {
            byte_count: 255,
            bits: [0u8; MAX_COIL_BYTES],
        };
        let mut buf = [0u8; 1000];
        assert_eq!(
            bad.encode(&mut buf),
            Err(MessageError::TooManyItems {
                max: MAX_COIL_BYTES,
                got: 255
            })
        );
    }
}