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))]
7pub enum EncodeError {
8    BufferTooSmall,
9    ValueOutOfRange,
10    InvalidLength,
11    Unsupported,
12    Message(&'static str),
13}
14
15impl fmt::Display for EncodeError {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        match self {
18            Self::BufferTooSmall => f.write_str("buffer too small"),
19            Self::ValueOutOfRange => f.write_str("value out of range"),
20            Self::InvalidLength => f.write_str("invalid length"),
21            Self::Unsupported => f.write_str("operation unsupported"),
22            Self::Message(msg) => f.write_str(msg),
23        }
24    }
25}
26
27#[cfg(feature = "std")]
28impl std::error::Error for EncodeError {}
29
30/// Errors that can occur while decoding Modbus data from an input buffer.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32#[cfg_attr(feature = "defmt", derive(defmt::Format))]
33#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
34pub enum DecodeError {
35    UnexpectedEof,
36    InvalidFunctionCode,
37    InvalidLength,
38    InvalidValue,
39    InvalidCrc,
40    Unsupported,
41    Message(&'static str),
42}
43
44impl fmt::Display for DecodeError {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        match self {
47            Self::UnexpectedEof => f.write_str("unexpected end of input"),
48            Self::InvalidFunctionCode => f.write_str("invalid function code"),
49            Self::InvalidLength => f.write_str("invalid length"),
50            Self::InvalidValue => f.write_str("invalid value"),
51            Self::InvalidCrc => f.write_str("invalid crc"),
52            Self::Unsupported => f.write_str("operation unsupported"),
53            Self::Message(msg) => f.write_str(msg),
54        }
55    }
56}
57
58#[cfg(feature = "std")]
59impl std::error::Error for DecodeError {}