sml-kit 0.1.1

Read German smart meters in Rust: SML (Smart Message Language) decoder and encoder, sans-I/O, no_std, no allocator, no dependencies
Documentation
//! CRC-16/X-25, the checksum SML uses for both the transport frame and each message,
//! and CRC-16/KERMIT, the checksum some meters use instead.
//!
//! **CRC-16/X-25**: polynomial 0x1021 (reflected 0x8408), initial value 0xFFFF, input and
//! output reflected, final XOR 0xFFFF. Check value over `"123456789"`: `0x906E`.
//!
//! **Byte order on the wire.** The CRC is transmitted low byte first, as in HDLC, both in
//! the transport end sequence and in a message's `Unsigned16` CRC field.
//! Every CRC-valid frame in the public real-meter corpus agrees.
//!
//! **CRC-16/KERMIT** uses the same reflected polynomial with initial value 0 and no final
//! XOR (check value `0x2189`). Some Holley DTZ541 units compute it instead of X-25.
//! [`CrcCheck::Lenient`] accepts it; [`CrcCheck::Strict`] does not.

/// How strictly a CRC is checked.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CrcCheck {
    /// CRC-16/X-25, low byte first on the wire. The default, and what the specification
    /// and every conforming meter use.
    #[default]
    Strict,
    /// CRC-16/X-25 or CRC-16/KERMIT, each in either byte order, for meters that deviate
    /// (some Holley DTZ541 send KERMIT).
    ///
    /// Four values are accepted instead of one, so a corrupted telegram passes with a
    /// probability of 4/65536 instead of 1/65536. Use it for the meter that needs it,
    /// not as a default.
    Lenient,
    /// The CRC is not checked. For captures known to be damaged, never for billing.
    Off,
}

impl CrcCheck {
    /// Whether a CRC read from the wire as a big-endian `u16` matches.
    ///
    /// `x25` and `kermit` are the CRCs computed over the same bytes.
    pub(crate) fn accepts(self, x25: u16, kermit: u16, wire_be: u16) -> bool {
        match self {
            Self::Strict => wire_be == x25.swap_bytes(),
            Self::Lenient => [x25, x25.swap_bytes(), kermit, kermit.swap_bytes()].contains(&wire_be),
            Self::Off => true,
        }
    }
}

// A const fn cannot use `get_mut`, and both loops are bounded by the array length.
#[allow(clippy::indexing_slicing, clippy::cast_possible_truncation)]
const fn table() -> [u16; 256] {
    let mut t = [0u16; 256];
    let mut i = 0;
    while i < 256 {
        let mut crc = i as u16;
        let mut bit = 0;
        while bit < 8 {
            crc = if crc & 1 != 0 { (crc >> 1) ^ 0x8408 } else { crc >> 1 };
            bit += 1;
        }
        t[i] = crc;
        i += 1;
    }
    t
}

static TABLE: [u16; 256] = table();

/// One table step of the reflected 0x1021 polynomial, shared by X-25 and KERMIT.
fn step(crc: u16, byte: u8) -> u16 {
    let [low, _] = (crc ^ u16::from(byte)).to_le_bytes();
    // A `u8` index is always inside the 256-entry table.
    (crc >> 8) ^ TABLE.get(usize::from(low)).copied().unwrap_or(0)
}

/// An incremental CRC-16/X-25.
#[derive(Clone, Copy, Debug)]
pub struct X25(u16);

impl Default for X25 {
    fn default() -> Self {
        Self::new()
    }
}

impl X25 {
    /// A fresh CRC.
    pub const fn new() -> Self {
        Self(0xFFFF)
    }

    /// Add bytes.
    pub fn update(&mut self, bytes: &[u8]) {
        self.0 = bytes.iter().fold(self.0, |c, &b| step(c, b));
    }

    /// The CRC of everything added so far.
    pub const fn finish(self) -> u16 {
        self.0 ^ 0xFFFF
    }
}

/// An incremental CRC-16/KERMIT.
#[derive(Clone, Copy, Debug, Default)]
pub struct Kermit(u16);

impl Kermit {
    /// A fresh CRC.
    pub const fn new() -> Self {
        Self(0)
    }

    /// Add bytes.
    pub fn update(&mut self, bytes: &[u8]) {
        self.0 = bytes.iter().fold(self.0, |c, &b| step(c, b));
    }

    /// The CRC of everything added so far.
    pub const fn finish(self) -> u16 {
        self.0
    }
}

/// The CRC-16/X-25 of `bytes`.
pub fn x25(bytes: &[u8]) -> u16 {
    let mut c = X25::new();
    c.update(bytes);
    c.finish()
}

/// The CRC-16/KERMIT of `bytes`.
pub fn kermit(bytes: &[u8]) -> u16 {
    let mut c = Kermit::new();
    c.update(bytes);
    c.finish()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn standard_check_values() {
        assert_eq!(x25(b"123456789"), 0x906E);
        assert_eq!(kermit(b"123456789"), 0x2189);
    }

    #[test]
    fn incremental_equals_one_shot() {
        let mut c = X25::new();
        c.update(b"1234");
        c.update(b"56789");
        assert_eq!(c.finish(), x25(b"123456789"));
    }

    // 001-real-meter-readiness/SR-003
    #[test]
    fn strict_wants_x25_low_byte_first() {
        let (x25, k) = (0x906E, 0x2189);
        assert!(CrcCheck::Strict.accepts(x25, k, 0x6E90));
        assert!(!CrcCheck::Strict.accepts(x25, k, 0x906E));
        assert!(!CrcCheck::Strict.accepts(x25, k, 0x2189));
        assert!(!CrcCheck::Strict.accepts(x25, k, 0x8921));
        for wire in [0x6E90, 0x906E, 0x2189, 0x8921] {
            assert!(CrcCheck::Lenient.accepts(x25, k, wire));
        }
        assert!(!CrcCheck::Lenient.accepts(x25, k, 0x1234));
        assert!(CrcCheck::Off.accepts(x25, k, 0));
        assert_eq!(CrcCheck::default(), CrcCheck::Strict);
    }
}