gmqtt 0.1.1

A no_std, no_alloc MQTTv5 packet parsing library for embedded devices
Documentation
use core::convert::{TryFrom, TryInto};

use heapless::Vec;

use crate::{utils::*, MqttError, Pid};

use super::{property, PropertyType};

/// The UNSUBACK packet is sent by the Server to the Client to confirm receipt of an UNSUBSCRIBE packet.
///
/// [MQTT5 SPECIFICATION](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901187)
#[derive(Debug, Clone, PartialEq)]
pub struct UnsubAck<'a> {
    /// Packet Identifier from the UNSUBSCRIBE Packet that is being acknowledged
    pub pid: Pid,

    /// The Payload contains a list of Reason Codes.
    /// Each Reason Code corresponds to a Topic Filter in the UNSUBSCRIBE packet being acknowledged.
    /// The order of Reason Codes in the UNSUBACK packet MUST match the order of Topic Filters in the UNSUBSCRIBE packet
    pub reason_codes: Vec<UnsubAckReasonCode, 32>,
    pub properties: Option<UnsubAckProperties<'a>>,
}

impl<'a> UnsubAck<'a> {
    pub fn new(pid: Pid) -> Self {
        UnsubAck {
            pid,
            reason_codes: heapless::Vec::<UnsubAckReasonCode, 32>::new(),
            properties: None,
        }
    }

    pub fn read(buf: &'a [u8], offset: &mut usize) -> Result<Self, MqttError> {
        let pid = Pid::read(buf, offset)?;

        let properties = UnsubAckProperties::read(buf, offset)?;

        // move offset to reason code field
        *offset += 1;

        let mut reason_codes = heapless::Vec::<UnsubAckReasonCode, 32>::new();

        for byte in &buf[*offset..] {
            let reason_code: UnsubAckReasonCode = TryInto::<UnsubAckReasonCode>::try_into(*byte)?;
            reason_codes
                .push(reason_code)
                .map_err(|_| MqttError::TooManySubscribeReasonCodes)?;
        }

        let suback = UnsubAck {
            pid,
            reason_codes,
            properties,
        };

        Ok(suback)
    }

    pub fn write(&self, buf: &mut [u8], offset: &mut usize) -> Result<usize, MqttError> {
        check_remaining(buf, offset, self.len() + 1)?;

        // UnsubAck (0xB0);
        let header: u8 = 0xB0;
        write_u8(buf, offset, header);

        let write_len = write_length(buf, offset, self.len())? + 1;
        self.pid.write(buf, offset);

        match &self.properties {
            Some(properties) => properties.write(buf, offset)?,
            None => write_u8(buf, offset, 0),
        }

        for rc in &self.reason_codes {
            write_u8(buf, offset, *rc as u8);
        }

        Ok(write_len)
    }

    fn len(&self) -> usize {
        let mut len = 2 + self.reason_codes.len();

        match &self.properties {
            Some(properties) => {
                let properties_len = properties.len();
                let properties_len_len = len_len(properties_len);
                len += properties_len_len + properties_len;
            }
            None => {
                // just 1 byte representing 0 len
                len += 1;
            }
        }

        len
    }
}

/// [MQTT5 SPECIFICATION](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901190)
#[derive(Debug, Clone, PartialEq, Default)]
pub struct UnsubAckProperties<'a> {
    /// `31 (0x1F)` Byte, Identifier of the Reason String.
    ///
    /// Followed by the UTF-8 Encoded String representing the reason associated with this response.
    pub reason_string: Option<&'a str>,

    /// `38 (0x26)` Byte, Identifier of the User Property.
    ///
    /// Followed by UTF-8 String Pair.
    pub user_properties: Vec<(&'a str, &'a str), 32>,
}

impl<'a> UnsubAckProperties<'a> {
    pub fn read(buf: &'a [u8], offset: &mut usize) -> Result<Option<Self>, MqttError> {
        let mut properties = Self::default();

        let properties_len = buf[*offset];

        if properties_len == 0 {
            return Ok(None);
        }

        let mut cursor: usize = 1;

        while cursor < properties_len.into() {
            let mut prop_offset = *offset + cursor;
            let prop = buf[prop_offset];

            prop_offset += 1;
            cursor += 1;
            match property(prop)? {
                PropertyType::ReasonString => {
                    let reason = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + reason.len();
                    properties.reason_string = Some(reason);
                }

                PropertyType::UserProperty => {
                    let key = read_str(buf, &mut prop_offset)?;
                    let value = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + key.len() + 2 + value.len();
                    properties
                        .user_properties
                        .push((key, value))
                        .map_err(|_| MqttError::TooManyUserProperties)?;
                }

                prop => return Err(MqttError::InvalidPropertyType(prop)),
            }
        }

        *offset += properties.len();
        Ok(Some(properties))
    }

    pub fn write(&self, buf: &mut [u8], offset: &mut usize) -> Result<(), MqttError> {
        write_length(buf, offset, self.len())?;
        if let Some(reason_string) = self.reason_string {
            write_u8(buf, offset, PropertyType::ReasonString as u8);
            write_bytes_with_len(buf, offset, reason_string.as_bytes());
        }

        for (key, value) in self.user_properties.iter() {
            write_u8(buf, offset, PropertyType::UserProperty as u8);
            write_bytes_with_len(buf, offset, key.as_bytes());
            write_bytes_with_len(buf, offset, value.as_bytes());
        }

        Ok(())
    }

    fn len(&self) -> usize {
        let mut len = 0;

        if let Some(reason) = &self.reason_string {
            len += 1 + 2 + reason.len();
        }

        for (key, value) in self.user_properties.iter() {
            len += 1 + 2 + key.len() + 2 + value.len();
        }

        len
    }
}

/// [MQTT5 SPECIFICATION](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901194)
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum UnsubAckReasonCode {
    /// The subscription is deleted.
    Success = 0,

    /// No matching Topic Filter is being used by the Client.
    NoSubscriptionExisted = 17,

    /// The unsubscribe could not be completed and the Server either does not wish to reveal the reason or none of the other Reason Codes apply.
    UnspecifiedError = 128,

    /// The UNSUBSCRIBE is valid but the Server does not accept it.
    ImplementationSpecificError = 131,

    /// The Client is not authorized to unsubscribe.
    NotAuthorized = 135,

    /// The Topic Filter is correctly formed but is not allowed for this Client.
    TopicFilterInvalid = 143,

    /// The specified Packet Identifier is already in use.
    PacketIdentifierInUse = 145,
}

impl TryFrom<u8> for UnsubAckReasonCode {
    type Error = MqttError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        let v = match value {
            0 => UnsubAckReasonCode::Success,
            17 => UnsubAckReasonCode::NoSubscriptionExisted,
            128 => UnsubAckReasonCode::UnspecifiedError,
            131 => UnsubAckReasonCode::ImplementationSpecificError,
            135 => UnsubAckReasonCode::NotAuthorized,
            143 => UnsubAckReasonCode::TopicFilterInvalid,
            145 => UnsubAckReasonCode::PacketIdentifierInUse,
            code => return Err(MqttError::InvalidReasonCode(code)),
        };

        Ok(v)
    }
}

#[cfg(test)]
mod tests {
    use super::{UnsubAck, UnsubAckProperties, UnsubAckReasonCode};
    use crate::Pid;

    fn sample<'a>() -> UnsubAck<'a> {
        let properties = UnsubAckProperties {
            reason_string: Some("test"),
            user_properties: heapless::Vec::<_, 32>::from_slice(&[("test", "test")]).unwrap(),
        };

        UnsubAck {
            pid: Pid::new(10),
            reason_codes: heapless::Vec::<_, 32>::from_slice(&[
                UnsubAckReasonCode::NotAuthorized,
                UnsubAckReasonCode::TopicFilterInvalid,
            ])
            .unwrap(),
            properties: Some(properties),
        }
    }

    fn sample_bytes() -> Vec<u8> {
        vec![
            0xb0, // packet type
            0x19, // remaining len
            0x00, 0x0a, // pkid
            0x14, // properties len
            0x1f, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // reason string
            0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
            0x74, // user properties
            0x87, 0x8f, // reasons
        ]
    }

    #[test]
    fn unsuback_decode() {
        let bytes = &sample_bytes()[2..];
        let expected = sample();
        let actual = UnsubAck::read(bytes, &mut 0).unwrap();
        assert_eq!(expected, actual);
    }

    #[test]
    fn unsuback_encode() {
        let expected = sample_bytes();
        let mut buf = [0u8; 27];
        sample().write(&mut buf, &mut 0).unwrap();

        assert_eq!(expected.as_slice(), buf);
    }

    fn sample2<'a>() -> UnsubAck<'a> {
        UnsubAck {
            pid: Pid::new(10),
            reason_codes: heapless::Vec::<_, 32>::from_slice(&[
                UnsubAckReasonCode::NotAuthorized,
                UnsubAckReasonCode::TopicFilterInvalid,
            ])
            .unwrap(),
            properties: None,
        }
    }

    fn sample_bytes2() -> Vec<u8> {
        vec![
            0xb0, // packet type
            0x05, // remaining len
            0x00, 0x0a, // pkid
            0x00, // properties len
            0x87, 0x8f, // reasons
        ]
    }

    #[test]
    fn unsuback_decode2() {
        let bytes = &sample_bytes2()[2..];
        let expected = sample2();
        let actual = UnsubAck::read(bytes, &mut 0).unwrap();
        assert_eq!(expected, actual);
    }

    #[test]
    fn unsuback_encode2() {
        let expected = sample_bytes2();
        let mut buf = [0u8; 7];
        sample2().write(&mut buf, &mut 0).unwrap();

        assert_eq!(expected.as_slice(), buf);
    }
}