mbrtu 0.1.2

no_std, no_alloc parser and encoder for Modbus RTU PDUs
Documentation
//! Error types for every layer of the decode/encode pipeline.

use core::fmt;

/// Errors from parsing a raw Modbus RTU frame.
///
/// Modbus RTU has no length field or preamble byte: a receiver normally
/// finds frame boundaries by timing (3.5 character times of silence), not
/// by anything encoded in the bytes themselves. [`crate::frame::Frame::parse`]
/// therefore treats its whole input slice as exactly one frame - there's
/// no partial-buffer or resync case to report here, only "too short to be
/// a frame at all" and "the trailing CRC doesn't match."
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameError {
    /// A buffer was shorter than needed: for [`crate::frame::Frame::parse`],
    /// smaller than the smallest possible frame (address + function code +
    /// 2-byte CRC, 4 bytes); for [`crate::frame::encode`], too small to
    /// hold the frame being written.
    TooShort {
        /// Bytes required.
        needed: usize,
        /// Bytes actually available in the buffer.
        got: usize,
    },
    /// The trailing 16-bit CRC did not match the one computed over the
    /// rest of the frame.
    ChecksumMismatch,
    /// A frame parsed with [`crate::frame::Frame::parse_response`] had the
    /// broadcast address (`0`). Modbus RTU never sends a response to a
    /// broadcast request, so this indicates a transport bug, not a
    /// scenario a compliant device produces.
    BroadcastResponse,
}

impl fmt::Display for FrameError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TooShort { needed, got } => {
                write!(f, "frame needs at least {needed} bytes, buffer has {got}")
            }
            Self::ChecksumMismatch => write!(f, "CRC-16 checksum mismatch"),
            Self::BroadcastResponse => write!(f, "response frame had the broadcast address (0)"),
        }
    }
}

impl core::error::Error for FrameError {}

/// Errors from decoding/encoding a typed PDU from/to a frame's data.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageError {
    /// The function code didn't match any PDU this crate decodes for the
    /// requested direction (request or response).
    UnknownFunctionCode(u8),
    /// The data was shorter than the function code's fixed-size fields
    /// require.
    UnexpectedEof,
    /// The destination buffer has no room for more encoded output.
    BufferFull,
    /// A read response's declared byte count didn't match the data
    /// actually available to hold that many bytes.
    ByteCountMismatch {
        /// Byte count declared in the response.
        declared: u8,
        /// Bytes actually available after the byte count field.
        available: usize,
    },
    /// A request or response asked for more registers/coils than this
    /// crate's fixed-size buffers hold, or than the Modbus spec allows in
    /// a single PDU.
    TooManyItems {
        /// Maximum items this crate/the spec supports for the field in
        /// question.
        max: usize,
        /// Items actually requested/present.
        got: usize,
    },
}

impl fmt::Display for MessageError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownFunctionCode(fc) => {
                write!(f, "unknown/undecoded function code: {fc:#04x}")
            }
            Self::UnexpectedEof => write!(f, "unexpected end of PDU data"),
            Self::BufferFull => write!(f, "output buffer is full"),
            Self::ByteCountMismatch {
                declared,
                available,
            } => {
                write!(
                    f,
                    "declared byte count {declared} but only {available} bytes available"
                )
            }
            Self::TooManyItems { max, got } => {
                write!(f, "{got} items exceeds the maximum of {max}")
            }
        }
    }
}

impl core::error::Error for MessageError {}

/// Top-level error type composing every layer, for `?`-based error
/// propagation across the frame and message layers.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MbrtuError {
    /// Error in the frame layer (length, CRC).
    Frame(FrameError),
    /// Error in the message layer.
    Message(MessageError),
}

impl fmt::Display for MbrtuError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Frame(e) => write!(f, "{e}"),
            Self::Message(e) => write!(f, "{e}"),
        }
    }
}

impl core::error::Error for MbrtuError {}

impl From<FrameError> for MbrtuError {
    fn from(e: FrameError) -> Self {
        Self::Frame(e)
    }
}

impl From<MessageError> for MbrtuError {
    fn from(e: MessageError) -> Self {
        Self::Message(e)
    }
}