Skip to main content

knx_core/
error.rs

1use core::fmt;
2
3/// Why this crate refused.
4///
5/// Each variant names a class of refusal and carries only what the caller can
6/// act on: a static reason for the classes with several causes, the 2 counts
7/// for a short read, and the code itself for one this crate does not speak.
8/// Nothing here carries owned data, so the type is as usable without `std` as
9/// with it.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum KnxError {
12    /// Text or parts that do not name an address: a level past the bits it
13    /// has, a missing part, a part that is not a number, or more parts than
14    /// the form takes. The reason states which.
15    InvalidAddress(&'static str),
16    /// Input ended before the structure being read does. The read is refused
17    /// rather than completed from whatever is there.
18    BufferTooShort {
19        /// How many octets the read needs, counted from the start of the
20        /// input it was given.
21        needed: usize,
22        /// How many octets that input actually holds.
23        actual: usize,
24    },
25    /// A frame that is present but not one this crate can read: a length or
26    /// version octet disagreeing with what it precedes, a field code outside
27    /// what is modeled, or a telegram whose service and payload contradict
28    /// each other. The reason states which.
29    InvalidFrame(&'static str),
30    /// A well-formed KNXnet/IP service code that is outside the set this
31    /// crate speaks. The code that arrived is carried, because the refusal is
32    /// about this crate's scope rather than about the frame being malformed.
33    UnsupportedServiceType(u16),
34}
35
36impl fmt::Display for KnxError {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match self {
39            Self::InvalidAddress(reason) => write!(f, "invalid address: {reason}"),
40            Self::BufferTooShort { needed, actual } => {
41                write!(f, "buffer too short: needed {needed} bytes, got {actual}")
42            }
43            Self::InvalidFrame(reason) => write!(f, "invalid frame: {reason}"),
44            Self::UnsupportedServiceType(service_type) => {
45                write!(f, "unsupported service type: 0x{service_type:04x}")
46            }
47        }
48    }
49}
50
51#[cfg(feature = "std")]
52impl std::error::Error for KnxError {}
53
54/// The result every fallible entry point in this crate answers with:
55/// [`KnxError`] is the only error any of them raises.
56pub type Result<T> = core::result::Result<T, KnxError>;