Skip to main content

symqtt_codec/
fixed_header.rs

1//! MQTT fixed header parsing [MQTT-2.2]
2
3use crate::{DecodeError, varint};
4
5/// MQTT control packet type [MQTT-2.2.1, Table 2.1]
6#[allow(missing_docs)]
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8#[repr(u8)]
9pub enum PacketType {
10    Connect = 1,
11    ConnAck = 2,
12    Publish = 3,
13    PubAck = 4,
14    PubRec = 5,
15    PubRel = 6,
16    PubComp = 7,
17    Subscribe = 8,
18    SubAck = 9,
19    Unsubscribe = 10,
20    UnsubAck = 11,
21    PingReq = 12,
22    PingResp = 13,
23    Disconnect = 14,
24    Auth = 15,
25}
26
27impl TryFrom<u8> for PacketType {
28    type Error = DecodeError;
29
30    fn try_from(value: u8) -> Result<Self, Self::Error> {
31        match value {
32            1 => Ok(Self::Connect),
33            2 => Ok(Self::ConnAck),
34            3 => Ok(Self::Publish),
35            4 => Ok(Self::PubAck),
36            5 => Ok(Self::PubRec),
37            6 => Ok(Self::PubRel),
38            7 => Ok(Self::PubComp),
39            8 => Ok(Self::Subscribe),
40            9 => Ok(Self::SubAck),
41            10 => Ok(Self::Unsubscribe),
42            11 => Ok(Self::UnsubAck),
43            12 => Ok(Self::PingReq),
44            13 => Ok(Self::PingResp),
45            14 => Ok(Self::Disconnect),
46            15 => Ok(Self::Auth),
47            _ => Err(DecodeError::InvalidPacketType { value }),
48        }
49    }
50}
51
52/// Packet boundary information carried from framing into packet decoding
53///
54/// ```text
55/// Bit    7  6  5  4    3  2  1  0
56///       [Packet Type ] [  Flags  ]    ← byte 1
57///       [  Remaining Length (1–4 bytes, variable-length encoding)  ]
58/// ```
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub struct FixedHeader {
61    /// Control packet type (upper 4 bits of byte 1)
62    pub packet_type: PacketType,
63    /// Type-specific flags (lower 4 bits of byte 1)
64    pub flags: u8,
65    /// Number of bytes remaining after the fixed header
66    pub remaining_len: u32,
67}
68
69/// Inspect the fixed header without consuming `buf`
70///
71/// Answers only "which packet is this and how many bytes are still missing".
72/// Whether the flags are legal is decided by each packet's own decoder, since
73/// that knowledge belongs with the packet type.
74///
75/// # Returns
76///
77/// `Ok(None)` when more bytes are needed, otherwise
78/// `Ok(Some((header, header_len)))` where `header_len` is 1 (the type/flags byte)
79/// plus the byte count of the remaining length field
80///
81/// # Errors
82///
83/// Returns [`DecodeError::InvalidPacketType`] if the packet type nibble is 0,
84/// which is reserved [MQTT-2.2.1]
85///
86/// Returns [`DecodeError::MalformedRemainingLength`] if the fourth byte of the
87/// remaining length field still has the continuation bit set
88pub fn peek(buf: &[u8]) -> Result<Option<(FixedHeader, usize)>, DecodeError> {
89    let Some((&byte1, varint_buf)) = buf.split_first() else {
90        return Ok(None);
91    };
92
93    // Byte 1 packs the packet type into bits 7-4 and type-specific flags into bits 3-0
94    let packet_type = PacketType::try_from(byte1 >> 4)?;
95    let flags = byte1 & 0x0F;
96
97    let Some((remaining_len, varint_len)) = varint::peek(varint_buf)? else {
98        return Ok(None);
99    };
100
101    Ok(Some((
102        FixedHeader {
103            packet_type,
104            flags,
105            remaining_len,
106        },
107        1 + varint_len,
108    )))
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114    use crate::DecodeError;
115
116    #[test]
117    fn packet_type_all_valid() {
118        let expected = [
119            (1, PacketType::Connect),
120            (2, PacketType::ConnAck),
121            (3, PacketType::Publish),
122            (4, PacketType::PubAck),
123            (5, PacketType::PubRec),
124            (6, PacketType::PubRel),
125            (7, PacketType::PubComp),
126            (8, PacketType::Subscribe),
127            (9, PacketType::SubAck),
128            (10, PacketType::Unsubscribe),
129            (11, PacketType::UnsubAck),
130            (12, PacketType::PingReq),
131            (13, PacketType::PingResp),
132            (14, PacketType::Disconnect),
133            (15, PacketType::Auth),
134        ];
135        for (val, pt) in expected {
136            assert_eq!(PacketType::try_from(val), Ok(pt));
137        }
138    }
139
140    #[test]
141    fn packet_type_zero_reserved() {
142        assert_eq!(
143            PacketType::try_from(0u8),
144            Err(DecodeError::InvalidPacketType { value: 0 })
145        );
146    }
147
148    #[test]
149    fn packet_type_16_invalid() {
150        assert_eq!(
151            PacketType::try_from(16u8),
152            Err(DecodeError::InvalidPacketType { value: 16 })
153        );
154    }
155
156    #[test]
157    fn packet_type_255_invalid() {
158        assert_eq!(
159            PacketType::try_from(255u8),
160            Err(DecodeError::InvalidPacketType { value: 255 })
161        );
162    }
163
164    #[test]
165    fn peek_empty_buffer() {
166        assert_eq!(peek(&[]), Ok(None));
167    }
168
169    #[test]
170    fn peek_only_type_byte_no_varint() {
171        // CONNECT type byte, but no remaining length bytes
172        assert_eq!(peek(&[0x10]), Ok(None));
173    }
174
175    #[test]
176    fn peek_connect_zero_body() {
177        let result = peek(&[0x10, 0x00]).unwrap().unwrap();
178        assert_eq!(result.0.packet_type, PacketType::Connect);
179        assert_eq!(result.0.flags, 0x00);
180        assert_eq!(result.0.remaining_len, 0);
181        assert_eq!(result.1, 2); // header_len = 1 + 1
182    }
183
184    #[test]
185    fn peek_publish_with_flags() {
186        // Type=Publish(3), flags=0x03 (QoS1 + retain) → byte1 = 0x33
187        let result = peek(&[0x33, 0x05]).unwrap().unwrap();
188        assert_eq!(result.0.packet_type, PacketType::Publish);
189        assert_eq!(result.0.flags, 0x03);
190        assert_eq!(result.0.remaining_len, 5);
191        assert_eq!(result.1, 2);
192    }
193
194    #[test]
195    fn peek_large_remaining_len() {
196        // Publish, flags=0, remaining_len=268435455 (4-byte varint)
197        let result = peek(&[0x30, 0xFF, 0xFF, 0xFF, 0x7F]).unwrap().unwrap();
198        assert_eq!(result.0.remaining_len, 268_435_455);
199        assert_eq!(result.1, 5); // 1 + 4
200    }
201
202    #[test]
203    fn peek_type_zero_invalid() {
204        assert_eq!(peek(&[0x00, 0x00]), Err(DecodeError::InvalidPacketType { value: 0 }));
205    }
206
207    #[test]
208    fn peek_varint_incomplete() {
209        // CONNECT + continuation bit but no second byte
210        assert_eq!(peek(&[0x10, 0x80]), Ok(None));
211    }
212
213    #[test]
214    fn peek_varint_malformed() {
215        assert_eq!(
216            peek(&[0x10, 0x80, 0x80, 0x80, 0x80]),
217            Err(DecodeError::MalformedRemainingLength)
218        );
219    }
220
221    #[test]
222    fn peek_subscribe_flags() {
223        // Subscribe type(8) + flags 0x02 → byte1=0x82, remaining=10
224        let result = peek(&[0x82, 0x0A]).unwrap().unwrap();
225        assert_eq!(result.0.packet_type, PacketType::Subscribe);
226        assert_eq!(result.0.flags, 0x02);
227        assert_eq!(result.0.remaining_len, 10);
228    }
229
230    #[test]
231    fn peek_two_byte_varint_header_len() {
232        // Publish, remaining_len=128 → varint [0x80, 0x01], header_len = 1+2 = 3
233        let result = peek(&[0x30, 0x80, 0x01]).unwrap().unwrap();
234        assert_eq!(result.0.remaining_len, 128);
235        assert_eq!(result.1, 3);
236    }
237}