simulcrypt 0.1.0

DVB SimulCrypt (ETSI TS 103 197) head-end protocol: ECMG client, EMMG server, control words
Documentation
/// One TLV (tag-length-value) variable of a `SimulCrypt` message payload.
#[derive(Clone, Debug)]
pub struct Tlv {
    /// Variable tag - its meaning depends on the protocol (ECMG/EMMG) and the message type.
    pub tag: u16,
    /// Raw variable value.
    pub value: Vec<u8>,
}

impl Tlv {
    /// Interprets the value as `u8` if it is exactly one byte.
    #[must_use]
    pub fn as_u8(&self) -> Option<u8> {
        let [value] = self.value[..] else {
            return None;
        };
        Some(value)
    }

    /// Interprets the value as `u16` (big-endian) if it is exactly two bytes.
    #[must_use]
    pub fn as_u16(&self) -> Option<u16> {
        Some(u16::from_be_bytes(self.value[..].try_into().ok()?))
    }

    /// Interprets the value as `u32` (big-endian) if it is exactly four bytes.
    #[must_use]
    pub fn as_u32(&self) -> Option<u32> {
        Some(u32::from_be_bytes(self.value[..].try_into().ok()?))
    }
}

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

    fn tlv(value: &[u8]) -> Tlv {
        Tlv {
            tag: 0,
            value: value.to_vec(),
        }
    }

    #[test]
    fn integers_need_the_exact_length() {
        assert_eq!(tlv(&[1]).as_u8(), Some(1));
        assert_eq!(tlv(&[1, 2]).as_u16(), Some(0x0102));
        assert_eq!(tlv(&[1, 2, 3, 4]).as_u32(), Some(0x0102_0304));

        for value in [&[][..], &[1, 2, 3], &[1, 2, 3, 4, 5]] {
            assert_eq!(tlv(value).as_u8(), None);
            assert_eq!(tlv(value).as_u16(), None);
            assert_eq!(tlv(value).as_u32(), None);
        }
    }
}