symqtt-codec 0.1.0

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

mod connect;
mod ping;
mod publish;
mod subscribe;

use bytes::{Buf, BufMut, BytesMut};
pub use connect::{ConnAck, Connect, ConnectReturnCode, Disconnect, Will};
pub use ping::{PingReq, PingResp};
pub use publish::{PubAck, PubComp, PubRec, PubRel, Publish};
pub use subscribe::{SubAck, Subscribe, SubscribeFilter, SubscribeReturnCode, UnsubAck, Unsubscribe};

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

/// A fully-decoded MQTT v3.1.1 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),
}

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 [MQTT-1.5.3]
    ///
    /// 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)
            }),
        };

        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 [MQTT-4.8]
    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 => Err(DecodeError::ProtocolError {
                reason: "AUTH is not supported in MQTT v3.1.1",
            }),
        }
        .map(Some)
    }
}

/// 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 [MQTT-2.2.3]
    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)
}