sml-kit 0.1.0

SML (Smart Message Language) for Rust: German smart meter readout with a sans-I/O, no_std, allocation-free core
Documentation
use core::fmt;

use crate::tl::Kind;

/// Result type of this crate.
pub type Result<T> = core::result::Result<T, Error>;

/// Everything that can go wrong between the meter's bytes and a typed reading.
///
/// Every variant is a property of the input, never of this crate's state: a decoder
/// that returns an error can be fed the next byte.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Error {
    /// The input ended in the middle of a value.
    UnexpectedEnd,
    /// A type-length field is malformed (an unknown type, a continuation byte with type
    /// bits set, or a length shorter than its own TL bytes).
    InvalidTl(u8),
    /// A value of one type was found where another was required.
    UnexpectedType {
        /// The type the grammar requires here.
        expected: Kind,
        /// The type on the wire.
        found: Kind,
    },
    /// A list has a different number of elements than the grammar requires.
    ListLength {
        /// Elements the grammar requires.
        expected: usize,
        /// Elements on the wire.
        found: usize,
    },
    /// A length is out of range for its type (an integer of 0 or more than 8 bytes, a
    /// boolean that is not 1 byte, a TL field of more than 4 bytes).
    InvalidLength,
    /// An unsigned value does not fit the field it was read into.
    ValueOutOfRange,
    /// Lists are nested deeper than the decoder allows.
    DepthLimit,
    /// The end-of-message byte (`0x00`) is missing after the message CRC.
    MissingEndOfMessage,
    /// An object name is not the six bytes of an OBIS code.
    ObisLength(usize),
    /// A choice (`SML_Time`, `SML_Value`) uses a tag this crate does not know.
    UnknownChoice {
        /// The choice type, e.g. `"SML_Time"`.
        what: &'static str,
        /// The tag on the wire.
        choice: u64,
    },
    /// The message CRC does not match its bytes.
    MessageCrc {
        /// CRC computed over the message.
        computed: u16,
        /// CRC field on the wire.
        found: u16,
    },
    /// The transport CRC does not match the frame.
    FrameCrc {
        /// CRC computed over the frame.
        computed: u16,
        /// CRC on the wire.
        found: u16,
    },
    /// The end sequence announces more padding than the frame has, or a padding byte is
    /// not zero.
    InvalidPadding,
    /// An escape sequence is followed by a command this crate does not know.
    InvalidEscape([u8; 4]),
    /// A new start sequence arrived before the current frame ended. The decoder has
    /// already begun the new frame; the old one is lost.
    UnexpectedStart,
    /// A frame does not fit the buffer the caller gave the decoder.
    BufferFull,
    /// The output buffer is too small for what is being written.
    OutputTooSmall,
    /// The frame holds no `GetListResponse`, so there are no readings in it.
    NoReadings,
    /// Text is not an OBIS code (`A-B:C.D.E*F`, `A-B:C.D.E` or `C.D.E`).
    ObisSyntax,
    /// An [`SmlFile`](crate::SmlFile) does not open first and close last, or has more
    /// than 256 messages.
    InvalidFile,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnexpectedEnd => f.write_str("input ended in the middle of a value"),
            Self::InvalidTl(b) => write!(f, "malformed type-length byte 0x{b:02x}"),
            Self::UnexpectedType { expected, found } => {
                write!(f, "expected {expected:?}, found {found:?}")
            }
            Self::ListLength { expected, found } => {
                write!(f, "expected a list of {expected}, found {found} elements")
            }
            Self::InvalidLength => f.write_str("length out of range for its type"),
            Self::ValueOutOfRange => f.write_str("value does not fit its field"),
            Self::DepthLimit => f.write_str("lists nested too deeply"),
            Self::MissingEndOfMessage => f.write_str("end-of-message byte missing"),
            Self::ObisLength(n) => write!(f, "object name has {n} bytes, an OBIS code has 6"),
            Self::UnknownChoice { what, choice } => write!(f, "unknown {what} choice {choice}"),
            Self::MessageCrc { computed, found } => {
                write!(f, "message CRC 0x{found:04x} does not match computed 0x{computed:04x}")
            }
            Self::FrameCrc { computed, found } => {
                write!(f, "frame CRC 0x{found:04x} does not match computed 0x{computed:04x}")
            }
            Self::InvalidPadding => f.write_str("invalid padding in the end sequence"),
            Self::InvalidEscape(c) => write!(f, "unknown escape command {c:02x?}"),
            Self::UnexpectedStart => f.write_str("new start sequence inside a frame"),
            Self::BufferFull => f.write_str("frame larger than the decoder buffer"),
            Self::OutputTooSmall => f.write_str("output buffer too small"),
            Self::NoReadings => f.write_str("the frame holds no GetListResponse"),
            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)"),
            Self::InvalidFile => {
                f.write_str("an SML file opens first, closes last and has at most 256 messages")
            }
        }
    }
}

/// The core error trait: available without `std` (stable since Rust 1.81).
impl core::error::Error for Error {}

#[cfg(test)]
mod tests {
    extern crate std;
    use super::*;
    use std::string::ToString;

    #[test]
    fn errors_say_what_is_wrong() {
        assert_eq!(
            Error::FrameCrc { computed: 0x1234, found: 0xabcd }.to_string(),
            "frame CRC 0xabcd does not match computed 0x1234"
        );
        assert_eq!(
            Error::UnknownChoice { what: "SML_Time", choice: 9 }.to_string(),
            "unknown SML_Time choice 9"
        );
        assert_eq!(Error::NoReadings.to_string(), "the frame holds no GetListResponse");
        assert_eq!(
            Error::InvalidFile.to_string(),
            "an SML file opens first, closes last and has at most 256 messages"
        );
        let as_trait: &dyn core::error::Error = &Error::DepthLimit;
        assert_eq!(as_trait.to_string(), "lists nested too deeply");
    }
}