symqtt-codec 0.1.0

MQTT 3.1.1/5.0 packet codec — role-neutral, runtime-free
Documentation
//! MQTT 5.0 property identifiers and decoding utilities [MQTTv5-2.2.2]

use bytes::Bytes;

use crate::{DecodeError, varint};

/// Byte length of a property identifier (single byte) [MQTTv5-2.2.2.2]
pub const PROP_ID_LEN: usize = 1;

/// MQTT 5.0 property identifier [MQTTv5-2.2.2.2, Table 2-4]
#[allow(missing_docs)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum PropertyId {
    PayloadFormatIndicator = 0x01,
    MessageExpiryInterval = 0x02,
    ContentType = 0x03,
    ResponseTopic = 0x08,
    CorrelationData = 0x09,
    SubscriptionIdentifier = 0x0B,
    SessionExpiryInterval = 0x11,
    AssignedClientIdentifier = 0x12,
    ServerKeepAlive = 0x13,
    AuthenticationMethod = 0x15,
    AuthenticationData = 0x16,
    RequestProblemInformation = 0x17,
    WillDelayInterval = 0x18,
    RequestResponseInformation = 0x19,
    ResponseInformation = 0x1A,
    ServerReference = 0x1C,
    ReasonString = 0x1F,
    ReceiveMaximum = 0x21,
    TopicAliasMaximum = 0x22,
    TopicAlias = 0x23,
    MaximumQoS = 0x24,
    RetainAvailable = 0x25,
    UserProperty = 0x26,
    MaximumPacketSize = 0x27,
    WildcardSubscriptionAvailable = 0x28,
    SubscriptionIdentifierAvailable = 0x29,
    SharedSubscriptionAvailable = 0x2A,
}

impl TryFrom<u8> for PropertyId {
    type Error = DecodeError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0x01 => Ok(Self::PayloadFormatIndicator),
            0x02 => Ok(Self::MessageExpiryInterval),
            0x03 => Ok(Self::ContentType),
            0x08 => Ok(Self::ResponseTopic),
            0x09 => Ok(Self::CorrelationData),
            0x0B => Ok(Self::SubscriptionIdentifier),
            0x11 => Ok(Self::SessionExpiryInterval),
            0x12 => Ok(Self::AssignedClientIdentifier),
            0x13 => Ok(Self::ServerKeepAlive),
            0x15 => Ok(Self::AuthenticationMethod),
            0x16 => Ok(Self::AuthenticationData),
            0x17 => Ok(Self::RequestProblemInformation),
            0x18 => Ok(Self::WillDelayInterval),
            0x19 => Ok(Self::RequestResponseInformation),
            0x1A => Ok(Self::ResponseInformation),
            0x1C => Ok(Self::ServerReference),
            0x1F => Ok(Self::ReasonString),
            0x21 => Ok(Self::ReceiveMaximum),
            0x22 => Ok(Self::TopicAliasMaximum),
            0x23 => Ok(Self::TopicAlias),
            0x24 => Ok(Self::MaximumQoS),
            0x25 => Ok(Self::RetainAvailable),
            0x26 => Ok(Self::UserProperty),
            0x27 => Ok(Self::MaximumPacketSize),
            0x28 => Ok(Self::WildcardSubscriptionAvailable),
            0x29 => Ok(Self::SubscriptionIdentifierAvailable),
            0x2A => Ok(Self::SharedSubscriptionAvailable),
            _ => Err(DecodeError::ProtocolError {
                reason: "invalid property identifier",
            }),
        }
    }
}

impl PropertyId {
    /// Value wire size: PayloadFormatIndicator (u8)
    pub const PAYLOAD_FORMAT_INDICATOR_LEN: usize = 1;
    /// Value wire size: MessageExpiryInterval (u32)
    pub const MESSAGE_EXPIRY_INTERVAL_LEN: usize = 4;
    /// Value wire size: SessionExpiryInterval (u32)
    pub const SESSION_EXPIRY_INTERVAL_LEN: usize = 4;
    /// Value wire size: ReceiveMaximum (u16)
    pub const RECEIVE_MAXIMUM_LEN: usize = 2;
    /// Value wire size: MaximumPacketSize (u32)
    pub const MAXIMUM_PACKET_SIZE_LEN: usize = 4;
    /// Value wire size: TopicAliasMaximum (u16)
    pub const TOPIC_ALIAS_MAXIMUM_LEN: usize = 2;
    /// Value wire size: TopicAlias (u16)
    pub const TOPIC_ALIAS_LEN: usize = 2;
    /// Value wire size: RequestResponseInformation (u8)
    pub const REQUEST_RESPONSE_INFORMATION_LEN: usize = 1;
    /// Value wire size: RequestProblemInformation (u8)
    pub const REQUEST_PROBLEM_INFORMATION_LEN: usize = 1;
    /// Value wire size: MaximumQoS (u8)
    pub const MAXIMUM_QOS_LEN: usize = 1;
    /// Value wire size: RetainAvailable (u8)
    pub const RETAIN_AVAILABLE_LEN: usize = 1;
    /// Value wire size: WildcardSubscriptionAvailable (u8)
    pub const WILDCARD_SUBSCRIPTION_AVAILABLE_LEN: usize = 1;
    /// Value wire size: SubscriptionIdentifierAvailable (u8)
    pub const SUBSCRIPTION_IDENTIFIER_AVAILABLE_LEN: usize = 1;
    /// Value wire size: SharedSubscriptionAvailable (u8)
    pub const SHARED_SUBSCRIPTION_AVAILABLE_LEN: usize = 1;
    /// Value wire size: ServerKeepAlive (u16)
    pub const SERVER_KEEP_ALIVE_LEN: usize = 2;
    /// Value wire size: WillDelayInterval (u32)
    pub const WILL_DELAY_INTERVAL_LEN: usize = 4;
}

/// Read the properties section from buf, returning the raw bytes
///
/// Reads varint (properties length), then splits that many bytes off.
/// Each XxxProperties::decode receives this segment and parses property id + value pairs.
pub(crate) fn read_properties_bytes(buf: &mut Bytes) -> Result<Bytes, DecodeError> {
    // The properties length is encoded as a variable-length integer preceding the property data
    let len = varint::decode(buf)? as usize;
    if buf.len() < len {
        return Err(DecodeError::InsufficientBytes {
            needed: len - buf.len(),
        });
    }
    // Split off exactly `len` bytes as the properties payload for downstream parsing
    Ok(buf.split_to(len))
}

/// Total encoded length of a properties section = varint(body_len) + body_len
pub(crate) fn properties_encoded_len(body_len: usize) -> usize {
    varint::len(body_len as u32) + body_len
}

/// Encode properties length (varint) into buf
pub(crate) fn write_properties_len(body_len: usize, buf: &mut bytes::BytesMut) {
    let mut tmp = [0u8; 4];
    let n = varint::encode_to(body_len as u32, &mut tmp);
    buf.extend_from_slice(&tmp[..n]);
}