Skip to main content

rustmod_core/
error.rs

1use core::fmt;
2
3/// Errors that can occur while encoding Modbus data into an output buffer.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5#[cfg_attr(feature = "defmt", derive(defmt::Format))]
6#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7#[non_exhaustive]
8pub enum EncodeError {
9    /// The output buffer does not have enough space.
10    BufferTooSmall,
11    /// A value exceeds the allowed range for the field.
12    ValueOutOfRange,
13    /// The data length is invalid for the operation.
14    InvalidLength,
15    /// The operation is not supported.
16    Unsupported,
17    /// A descriptive error message.
18    Message(&'static str),
19}
20
21impl fmt::Display for EncodeError {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        match self {
24            Self::BufferTooSmall => f.write_str("buffer too small"),
25            Self::ValueOutOfRange => f.write_str("value out of range"),
26            Self::InvalidLength => f.write_str("invalid length"),
27            Self::Unsupported => f.write_str("operation unsupported"),
28            Self::Message(msg) => f.write_str(msg),
29        }
30    }
31}
32
33#[cfg(feature = "std")]
34impl std::error::Error for EncodeError {}
35
36/// Errors that can occur while decoding Modbus data from an input buffer.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38#[cfg_attr(feature = "defmt", derive(defmt::Format))]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40#[non_exhaustive]
41pub enum DecodeError {
42    /// The input buffer ended before the expected data was fully read.
43    UnexpectedEof,
44    /// The function code byte is invalid (0x00 or has the exception bit set).
45    InvalidFunctionCode,
46    /// A length field does not match the actual data.
47    InvalidLength,
48    /// A field value is outside the allowed range.
49    InvalidValue,
50    /// The CRC check failed (RTU framing).
51    InvalidCrc,
52    /// The operation is not supported.
53    Unsupported,
54    /// A descriptive error message.
55    Message(&'static str),
56}
57
58impl fmt::Display for DecodeError {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        match self {
61            Self::UnexpectedEof => f.write_str("unexpected end of input"),
62            Self::InvalidFunctionCode => f.write_str("invalid function code"),
63            Self::InvalidLength => f.write_str("invalid length"),
64            Self::InvalidValue => f.write_str("invalid value"),
65            Self::InvalidCrc => f.write_str("invalid crc"),
66            Self::Unsupported => f.write_str("operation unsupported"),
67            Self::Message(msg) => f.write_str(msg),
68        }
69    }
70}
71
72#[cfg(feature = "std")]
73impl std::error::Error for DecodeError {}