symqtt-codec 0.1.0

MQTT 3.1.1/5.0 packet codec — role-neutral, runtime-free
Documentation
//! MQTT v5.0 packet encoding and decoding [MQTTv5-3]

mod auth;
mod connect;
mod disconnect;
mod ping;
mod publish;
mod reason_code;
mod subscribe;

pub(crate) mod property;

pub use auth::{Auth, AuthProperties, AuthStatus};
use bytes::{Buf, BufMut, BytesMut};
pub use connect::{ConnAck, ConnAckProperties, Connect, ConnectProperties, Will, WillProperties};
pub use disconnect::{Disconnect, DisconnectProperties};
pub use ping::{PingReq, PingResp};
pub use property::PropertyId;
pub use publish::{
    PubAck, PubAckProperties, PubComp, PubCompProperties, PubRec, PubRecProperties, PubRel, PubRelProperties, Publish,
    PublishProperties,
};
pub use reason_code::ReasonCode;
pub use subscribe::{
    RetainHandling, SubAck, SubAckProperties, Subscribe, SubscribeFilter, SubscribeProperties, UnsubAck,
    UnsubAckProperties, Unsubscribe, UnsubscribeProperties,
};

use crate::{DecodeError, EncodeError, MAX_REMAINING_LEN, PacketType, fixed_header, varint};

/// A fully-decoded MQTT v5.0 control packet
#[allow(missing_docs)]
#[derive(Debug, Clone, PartialEq)]
pub enum Packet {
    Connect(Connect),
    ConnAck(ConnAck),
    Publish(Publish),
    PubAck(PubAck),
    PubRec(PubRec),
    PubRel(PubRel),
    PubComp(PubComp),
    Subscribe(Subscribe),
    SubAck(SubAck),
    Unsubscribe(Unsubscribe),
    UnsubAck(UnsubAck),
    PingReq(PingReq),
    PingResp(PingResp),
    Disconnect(Disconnect),
    Auth(Auth),
}

impl Packet {
    /// Encode this packet, fixed header included, appending to `buf`
    ///
    /// Body length is computed upfront so the header can be written with the correct
    /// remaining-length varint, avoiding a post-hoc memmove.
    ///
    /// On error `buf` is restored to its original length, so a failed encode never
    /// leaves a partial packet behind for the next one to be appended to.
    ///
    /// # Errors
    ///
    /// Returns [`EncodeError::PacketTooLarge`] if the body exceeds [`MAX_REMAINING_LEN`],
    /// which the remaining length field cannot express
    ///
    /// Returns [`EncodeError::StringTooLong`] or [`EncodeError::StringContainsNull`] if a
    /// string field violates [MQTTv5-1.5.4]
    ///
    /// Returns [`EncodeError::InvalidState`] if the packet's fields form a combination the
    /// protocol forbids, such as a QoS 0 PUBLISH carrying a packet identifier
    pub fn encode(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
        let start = buf.len();

        let result = match self {
            Self::Connect(p) => encode_frame(buf, PacketType::Connect, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
            Self::ConnAck(p) => encode_frame(buf, PacketType::ConnAck, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
            Self::Publish(p) => encode_frame(buf, PacketType::Publish, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
            Self::PubAck(p) => encode_frame(buf, PacketType::PubAck, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
            Self::PubRec(p) => encode_frame(buf, PacketType::PubRec, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
            Self::PubRel(p) => encode_frame(buf, PacketType::PubRel, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
            Self::PubComp(p) => encode_frame(buf, PacketType::PubComp, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
            Self::Subscribe(p) => encode_frame(buf, PacketType::Subscribe, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
            Self::SubAck(p) => encode_frame(buf, PacketType::SubAck, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
            Self::Unsubscribe(p) => encode_frame(buf, PacketType::Unsubscribe, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
            Self::UnsubAck(p) => encode_frame(buf, PacketType::UnsubAck, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
            Self::PingReq(p) => encode_frame(buf, PacketType::PingReq, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
            Self::PingResp(p) => encode_frame(buf, PacketType::PingResp, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
            Self::Disconnect(p) => encode_frame(buf, PacketType::Disconnect, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
            Self::Auth(p) => encode_frame(buf, PacketType::Auth, p.flags(), p.encoded_body_len(), |b| {
                p.encode_body(b)
            }),
        };

        if result.is_err() {
            buf.truncate(start);
        }
        result
    }

    /// Take one complete packet off the front of `buf`, consuming its bytes on success
    ///
    /// # Returns
    ///
    /// `Ok(None)` when `buf` holds only part of a packet, in which case `buf` is left
    /// untouched and the caller should retry after reading more data
    ///
    /// # Errors
    ///
    /// Returns the matching [`DecodeError`] if the packet violates the protocol. The
    /// offending bytes have been consumed by then, and the caller must close the
    /// connection rather than keep parsing [MQTTv5-4.13]
    pub fn decode(buf: &mut BytesMut) -> Result<Option<Self>, DecodeError> {
        // Peek the fixed header without consuming bytes; returns None if incomplete
        let Some((header, header_len)) = fixed_header::peek(buf)? else {
            return Ok(None);
        };

        // Check whether the full packet body has arrived
        let body_len = header.remaining_len as usize;
        if buf.len() < header_len + body_len {
            return Ok(None);
        }

        // Consume the fixed header, then split out the body as a frozen Bytes slice
        buf.advance(header_len);
        let body = buf.split_to(body_len).freeze();
        let flags = header.flags;

        // Dispatch to the packet-specific decoder based on the type nibble
        match header.packet_type {
            PacketType::Connect => Connect::decode_body(flags, body).map(Self::Connect),
            PacketType::ConnAck => ConnAck::decode_body(flags, body).map(Self::ConnAck),
            PacketType::Publish => Publish::decode_body(flags, body).map(Self::Publish),
            PacketType::PubAck => PubAck::decode_body(flags, body).map(Self::PubAck),
            PacketType::PubRec => PubRec::decode_body(flags, body).map(Self::PubRec),
            PacketType::PubRel => PubRel::decode_body(flags, body).map(Self::PubRel),
            PacketType::PubComp => PubComp::decode_body(flags, body).map(Self::PubComp),
            PacketType::Subscribe => Subscribe::decode_body(flags, body).map(Self::Subscribe),
            PacketType::SubAck => SubAck::decode_body(flags, body).map(Self::SubAck),
            PacketType::Unsubscribe => Unsubscribe::decode_body(flags, body).map(Self::Unsubscribe),
            PacketType::UnsubAck => UnsubAck::decode_body(flags, body).map(Self::UnsubAck),
            PacketType::PingReq => PingReq::decode_body(flags, body).map(Self::PingReq),
            PacketType::PingResp => PingResp::decode_body(flags, body).map(Self::PingResp),
            PacketType::Disconnect => Disconnect::decode_body(flags, body).map(Self::Disconnect),
            PacketType::Auth => Auth::decode_body(flags, body).map(Self::Auth),
        }
        .map(Some)
    }

    /// Total encoded byte length of this packet (fixed header + body)
    pub fn encoded_len(&self) -> usize {
        let body_len = match self {
            Self::Connect(p) => p.encoded_body_len(),
            Self::ConnAck(p) => p.encoded_body_len(),
            Self::Publish(p) => p.encoded_body_len(),
            Self::PubAck(p) => p.encoded_body_len(),
            Self::PubRec(p) => p.encoded_body_len(),
            Self::PubRel(p) => p.encoded_body_len(),
            Self::PubComp(p) => p.encoded_body_len(),
            Self::Subscribe(p) => p.encoded_body_len(),
            Self::SubAck(p) => p.encoded_body_len(),
            Self::Unsubscribe(p) => p.encoded_body_len(),
            Self::UnsubAck(p) => p.encoded_body_len(),
            Self::PingReq(p) => p.encoded_body_len(),
            Self::PingResp(p) => p.encoded_body_len(),
            Self::Disconnect(p) => p.encoded_body_len(),
            Self::Auth(p) => p.encoded_body_len(),
        };
        1 + varint::len(body_len as u32) + body_len
    }
}

/// Write a fixed header (type/flags + remaining length) then invoke `write_body` to append the body
fn encode_frame(
    buf: &mut BytesMut,
    packet_type: PacketType,
    flags: u8,
    body_len: usize,
    write_body: impl FnOnce(&mut BytesMut) -> Result<(), EncodeError>,
) -> Result<(), EncodeError> {
    if body_len > MAX_REMAINING_LEN {
        return Err(EncodeError::PacketTooLarge);
    }

    // Pre-allocate exact capacity: 1 byte type/flags + varint + body
    let varint_len = varint::len(body_len as u32);
    buf.reserve(1 + varint_len + body_len);

    // Byte 1: packet type in upper nibble, type-specific flags in lower nibble
    buf.put_u8(((packet_type as u8) << 4) | flags);

    // Remaining length encoded as 1–4 byte variable-length integer [MQTTv5-2.1.4]
    let mut tmp = [0u8; varint::MAX_LEN];
    let n = varint::encode_to(body_len as u32, &mut tmp);
    buf.put_slice(&tmp[..n]);

    write_body(buf)
}