w5500_mqtt/
fixed_header.rs

1use crate::{
2    data::{decode_variable_byte_integer, DeserError},
3    CtrlPkt,
4};
5
6#[derive(Debug)]
7pub(crate) struct FixedHeader {
8    pub ctrl_pkt: CtrlPkt,
9    #[allow(dead_code)]
10    pub flags: u8,
11    // truncated from u32 to u16
12    // server should never send packets over u16 because we set the maximum size
13    // after connection
14    // additionally the socket buffers only have 32k physical memory
15    pub remaining_len: u16,
16    // length of the header in bytes
17    pub len: u8,
18}
19
20impl FixedHeader {
21    pub fn deser(buf: &[u8]) -> Result<Self, DeserError> {
22        let byte0: u8 = *buf.first().ok_or(DeserError::Fragment)?;
23        let ctrl_pkt: CtrlPkt = match byte0 >> 4 {
24            x if x == (CtrlPkt::RESERVED as u8) => CtrlPkt::RESERVED,
25            x if x == (CtrlPkt::CONNECT as u8) => CtrlPkt::CONNECT,
26            x if x == (CtrlPkt::CONNACK as u8) => CtrlPkt::CONNACK,
27            x if x == (CtrlPkt::PUBLISH as u8) => CtrlPkt::PUBLISH,
28            x if x == (CtrlPkt::PUBACK as u8) => CtrlPkt::PUBACK,
29            x if x == (CtrlPkt::PUBREC as u8) => CtrlPkt::PUBREC,
30            x if x == (CtrlPkt::PUBREL as u8) => CtrlPkt::PUBREL,
31            x if x == (CtrlPkt::PUBCOMP as u8) => CtrlPkt::PUBCOMP,
32            x if x == (CtrlPkt::SUBSCRIBE as u8) => CtrlPkt::SUBSCRIBE,
33            x if x == (CtrlPkt::SUBACK as u8) => CtrlPkt::SUBACK,
34            x if x == (CtrlPkt::UNSUBSCRIBE as u8) => CtrlPkt::UNSUBSCRIBE,
35            x if x == (CtrlPkt::UNSUBACK as u8) => CtrlPkt::UNSUBACK,
36            x if x == (CtrlPkt::PINGREQ as u8) => CtrlPkt::PINGREQ,
37            x if x == (CtrlPkt::PINGRESP as u8) => CtrlPkt::PINGRESP,
38            x if x == (CtrlPkt::DISCONNECT as u8) => CtrlPkt::DISCONNECT,
39            x if x == (CtrlPkt::AUTH as u8) => CtrlPkt::AUTH,
40            _ => unreachable!(),
41        };
42
43        let (remaining_len, integer_len): (u32, u8) = decode_variable_byte_integer(&buf[1..])?;
44
45        Ok(FixedHeader {
46            ctrl_pkt,
47            flags: byte0 & 0xF,
48            remaining_len: remaining_len.try_into().map_err(|_| DeserError::Decode)?,
49            len: integer_len + 1,
50        })
51    }
52}