symqtt-codec 0.1.0

MQTT 3.1.1/5.0 packet codec — role-neutral, runtime-free
Documentation
//! MQTT fixed header parsing [MQTT-2.2]

use crate::{DecodeError, varint};

/// MQTT control packet type [MQTT-2.2.1, Table 2.1]
#[allow(missing_docs)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum PacketType {
    Connect = 1,
    ConnAck = 2,
    Publish = 3,
    PubAck = 4,
    PubRec = 5,
    PubRel = 6,
    PubComp = 7,
    Subscribe = 8,
    SubAck = 9,
    Unsubscribe = 10,
    UnsubAck = 11,
    PingReq = 12,
    PingResp = 13,
    Disconnect = 14,
    Auth = 15,
}

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

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            1 => Ok(Self::Connect),
            2 => Ok(Self::ConnAck),
            3 => Ok(Self::Publish),
            4 => Ok(Self::PubAck),
            5 => Ok(Self::PubRec),
            6 => Ok(Self::PubRel),
            7 => Ok(Self::PubComp),
            8 => Ok(Self::Subscribe),
            9 => Ok(Self::SubAck),
            10 => Ok(Self::Unsubscribe),
            11 => Ok(Self::UnsubAck),
            12 => Ok(Self::PingReq),
            13 => Ok(Self::PingResp),
            14 => Ok(Self::Disconnect),
            15 => Ok(Self::Auth),
            _ => Err(DecodeError::InvalidPacketType { value }),
        }
    }
}

/// Packet boundary information carried from framing into packet decoding
///
/// ```text
/// Bit    7  6  5  4    3  2  1  0
///       [Packet Type ] [  Flags  ]    ← byte 1
///       [  Remaining Length (1–4 bytes, variable-length encoding)  ]
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FixedHeader {
    /// Control packet type (upper 4 bits of byte 1)
    pub packet_type: PacketType,
    /// Type-specific flags (lower 4 bits of byte 1)
    pub flags: u8,
    /// Number of bytes remaining after the fixed header
    pub remaining_len: u32,
}

/// Inspect the fixed header without consuming `buf`
///
/// Answers only "which packet is this and how many bytes are still missing".
/// Whether the flags are legal is decided by each packet's own decoder, since
/// that knowledge belongs with the packet type.
///
/// # Returns
///
/// `Ok(None)` when more bytes are needed, otherwise
/// `Ok(Some((header, header_len)))` where `header_len` is 1 (the type/flags byte)
/// plus the byte count of the remaining length field
///
/// # Errors
///
/// Returns [`DecodeError::InvalidPacketType`] if the packet type nibble is 0,
/// which is reserved [MQTT-2.2.1]
///
/// Returns [`DecodeError::MalformedRemainingLength`] if the fourth byte of the
/// remaining length field still has the continuation bit set
pub fn peek(buf: &[u8]) -> Result<Option<(FixedHeader, usize)>, DecodeError> {
    let Some((&byte1, varint_buf)) = buf.split_first() else {
        return Ok(None);
    };

    // Byte 1 packs the packet type into bits 7-4 and type-specific flags into bits 3-0
    let packet_type = PacketType::try_from(byte1 >> 4)?;
    let flags = byte1 & 0x0F;

    let Some((remaining_len, varint_len)) = varint::peek(varint_buf)? else {
        return Ok(None);
    };

    Ok(Some((
        FixedHeader {
            packet_type,
            flags,
            remaining_len,
        },
        1 + varint_len,
    )))
}

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

    #[test]
    fn packet_type_all_valid() {
        let expected = [
            (1, PacketType::Connect),
            (2, PacketType::ConnAck),
            (3, PacketType::Publish),
            (4, PacketType::PubAck),
            (5, PacketType::PubRec),
            (6, PacketType::PubRel),
            (7, PacketType::PubComp),
            (8, PacketType::Subscribe),
            (9, PacketType::SubAck),
            (10, PacketType::Unsubscribe),
            (11, PacketType::UnsubAck),
            (12, PacketType::PingReq),
            (13, PacketType::PingResp),
            (14, PacketType::Disconnect),
            (15, PacketType::Auth),
        ];
        for (val, pt) in expected {
            assert_eq!(PacketType::try_from(val), Ok(pt));
        }
    }

    #[test]
    fn packet_type_zero_reserved() {
        assert_eq!(
            PacketType::try_from(0u8),
            Err(DecodeError::InvalidPacketType { value: 0 })
        );
    }

    #[test]
    fn packet_type_16_invalid() {
        assert_eq!(
            PacketType::try_from(16u8),
            Err(DecodeError::InvalidPacketType { value: 16 })
        );
    }

    #[test]
    fn packet_type_255_invalid() {
        assert_eq!(
            PacketType::try_from(255u8),
            Err(DecodeError::InvalidPacketType { value: 255 })
        );
    }

    #[test]
    fn peek_empty_buffer() {
        assert_eq!(peek(&[]), Ok(None));
    }

    #[test]
    fn peek_only_type_byte_no_varint() {
        // CONNECT type byte, but no remaining length bytes
        assert_eq!(peek(&[0x10]), Ok(None));
    }

    #[test]
    fn peek_connect_zero_body() {
        let result = peek(&[0x10, 0x00]).unwrap().unwrap();
        assert_eq!(result.0.packet_type, PacketType::Connect);
        assert_eq!(result.0.flags, 0x00);
        assert_eq!(result.0.remaining_len, 0);
        assert_eq!(result.1, 2); // header_len = 1 + 1
    }

    #[test]
    fn peek_publish_with_flags() {
        // Type=Publish(3), flags=0x03 (QoS1 + retain) → byte1 = 0x33
        let result = peek(&[0x33, 0x05]).unwrap().unwrap();
        assert_eq!(result.0.packet_type, PacketType::Publish);
        assert_eq!(result.0.flags, 0x03);
        assert_eq!(result.0.remaining_len, 5);
        assert_eq!(result.1, 2);
    }

    #[test]
    fn peek_large_remaining_len() {
        // Publish, flags=0, remaining_len=268435455 (4-byte varint)
        let result = peek(&[0x30, 0xFF, 0xFF, 0xFF, 0x7F]).unwrap().unwrap();
        assert_eq!(result.0.remaining_len, 268_435_455);
        assert_eq!(result.1, 5); // 1 + 4
    }

    #[test]
    fn peek_type_zero_invalid() {
        assert_eq!(peek(&[0x00, 0x00]), Err(DecodeError::InvalidPacketType { value: 0 }));
    }

    #[test]
    fn peek_varint_incomplete() {
        // CONNECT + continuation bit but no second byte
        assert_eq!(peek(&[0x10, 0x80]), Ok(None));
    }

    #[test]
    fn peek_varint_malformed() {
        assert_eq!(
            peek(&[0x10, 0x80, 0x80, 0x80, 0x80]),
            Err(DecodeError::MalformedRemainingLength)
        );
    }

    #[test]
    fn peek_subscribe_flags() {
        // Subscribe type(8) + flags 0x02 → byte1=0x82, remaining=10
        let result = peek(&[0x82, 0x0A]).unwrap().unwrap();
        assert_eq!(result.0.packet_type, PacketType::Subscribe);
        assert_eq!(result.0.flags, 0x02);
        assert_eq!(result.0.remaining_len, 10);
    }

    #[test]
    fn peek_two_byte_varint_header_len() {
        // Publish, remaining_len=128 → varint [0x80, 0x01], header_len = 1+2 = 3
        let result = peek(&[0x30, 0x80, 0x01]).unwrap().unwrap();
        assert_eq!(result.0.remaining_len, 128);
        assert_eq!(result.1, 3);
    }
}