Skip to main content

sml_kit/
error.rs

1use core::fmt;
2
3use crate::tl::Kind;
4
5/// Result type of this crate.
6pub type Result<T> = core::result::Result<T, Error>;
7
8/// Everything that can go wrong between the meter's bytes and a typed reading.
9///
10/// Every variant is a property of the input, never of this crate's state: a decoder
11/// that returns an error can be fed the next byte.
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum Error {
15    /// The input ended in the middle of a value.
16    UnexpectedEnd,
17    /// A type-length field is malformed (an unknown type, a continuation byte with type
18    /// bits set, or a length shorter than its own TL bytes).
19    InvalidTl(u8),
20    /// A value of one type was found where another was required.
21    UnexpectedType {
22        /// The type the grammar requires here.
23        expected: Kind,
24        /// The type on the wire.
25        found: Kind,
26    },
27    /// A list has a different number of elements than the grammar requires.
28    ListLength {
29        /// Elements the grammar requires.
30        expected: usize,
31        /// Elements on the wire.
32        found: usize,
33    },
34    /// A length is out of range for its type (an integer of 0 or more than 8 bytes, a
35    /// boolean that is not 1 byte, a TL field of more than 4 bytes).
36    InvalidLength,
37    /// An unsigned value does not fit the field it was read into.
38    ValueOutOfRange,
39    /// Lists are nested deeper than the decoder allows.
40    DepthLimit,
41    /// The end-of-message byte (`0x00`) is missing after the message CRC.
42    MissingEndOfMessage,
43    /// An object name is not the six bytes of an OBIS code.
44    ObisLength(usize),
45    /// A choice (`SML_Time`, `SML_Value`) uses a tag this crate does not know.
46    UnknownChoice {
47        /// The choice type, e.g. `"SML_Time"`.
48        what: &'static str,
49        /// The tag on the wire.
50        choice: u64,
51    },
52    /// The message CRC does not match its bytes.
53    MessageCrc {
54        /// CRC computed over the message.
55        computed: u16,
56        /// CRC field on the wire.
57        found: u16,
58    },
59    /// The transport CRC does not match the frame.
60    FrameCrc {
61        /// CRC computed over the frame.
62        computed: u16,
63        /// CRC on the wire.
64        found: u16,
65    },
66    /// The end sequence announces more padding than the frame has, or a padding byte is
67    /// not zero.
68    InvalidPadding,
69    /// An escape sequence is followed by a command this crate does not know.
70    InvalidEscape([u8; 4]),
71    /// A new start sequence arrived before the current frame ended. The decoder has
72    /// already begun the new frame; the old one is lost.
73    UnexpectedStart,
74    /// A frame does not fit the buffer the caller gave the decoder.
75    BufferFull,
76    /// The output buffer is too small for what is being written.
77    OutputTooSmall,
78    /// The frame holds no `GetListResponse`, so there are no readings in it.
79    NoReadings,
80    /// Text is not an OBIS code (`A-B:C.D.E*F`, `A-B:C.D.E` or `C.D.E`).
81    ObisSyntax,
82    /// An [`SmlFile`](crate::SmlFile) does not open first and close last, or has more
83    /// than 256 messages.
84    InvalidFile,
85}
86
87impl fmt::Display for Error {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        match self {
90            Self::UnexpectedEnd => f.write_str("input ended in the middle of a value"),
91            Self::InvalidTl(b) => write!(f, "malformed type-length byte 0x{b:02x}"),
92            Self::UnexpectedType { expected, found } => {
93                write!(f, "expected {expected:?}, found {found:?}")
94            }
95            Self::ListLength { expected, found } => {
96                write!(f, "expected a list of {expected}, found {found} elements")
97            }
98            Self::InvalidLength => f.write_str("length out of range for its type"),
99            Self::ValueOutOfRange => f.write_str("value does not fit its field"),
100            Self::DepthLimit => f.write_str("lists nested too deeply"),
101            Self::MissingEndOfMessage => f.write_str("end-of-message byte missing"),
102            Self::ObisLength(n) => write!(f, "object name has {n} bytes, an OBIS code has 6"),
103            Self::UnknownChoice { what, choice } => write!(f, "unknown {what} choice {choice}"),
104            Self::MessageCrc { computed, found } => {
105                write!(f, "message CRC 0x{found:04x} does not match computed 0x{computed:04x}")
106            }
107            Self::FrameCrc { computed, found } => {
108                write!(f, "frame CRC 0x{found:04x} does not match computed 0x{computed:04x}")
109            }
110            Self::InvalidPadding => f.write_str("invalid padding in the end sequence"),
111            Self::InvalidEscape(c) => write!(f, "unknown escape command {c:02x?}"),
112            Self::UnexpectedStart => f.write_str("new start sequence inside a frame"),
113            Self::BufferFull => f.write_str("frame larger than the decoder buffer"),
114            Self::OutputTooSmall => f.write_str("output buffer too small"),
115            Self::NoReadings => f.write_str("the frame holds no GetListResponse"),
116            Self::ObisSyntax => f.write_str("not an OBIS code (expected A-B:C.D.E*F, A-B:C.D.E or C.D.E)"),
117            Self::InvalidFile => {
118                f.write_str("an SML file opens first, closes last and has at most 256 messages")
119            }
120        }
121    }
122}
123
124/// The core error trait: available without `std` (stable since Rust 1.81).
125impl core::error::Error for Error {}
126
127#[cfg(test)]
128mod tests {
129    extern crate std;
130    use super::*;
131    use std::string::ToString;
132
133    #[test]
134    fn errors_say_what_is_wrong() {
135        assert_eq!(
136            Error::FrameCrc { computed: 0x1234, found: 0xabcd }.to_string(),
137            "frame CRC 0xabcd does not match computed 0x1234"
138        );
139        assert_eq!(
140            Error::UnknownChoice { what: "SML_Time", choice: 9 }.to_string(),
141            "unknown SML_Time choice 9"
142        );
143        assert_eq!(Error::NoReadings.to_string(), "the frame holds no GetListResponse");
144        assert_eq!(
145            Error::InvalidFile.to_string(),
146            "an SML file opens first, closes last and has at most 256 messages"
147        );
148        let as_trait: &dyn core::error::Error = &Error::DepthLimit;
149        assert_eq!(as_trait.to_string(), "lists nested too deeply");
150    }
151}