symqtt-codec 0.1.0

MQTT 3.1.1/5.0 packet codec — role-neutral, runtime-free
Documentation
//! PINGREQ and PINGRESP packet encoding/decoding [MQTT-3.12, MQTT-3.13]
//!
//! ```text
//! PINGREQ [MQTT-3.12]:
//!
//!   Fixed Header:
//!     Byte 1: 0xC0 (type=12, flags=0b0000)
//!     Byte 2: 0x00 (remaining length, always 0)
//!
//!   No variable header, no payload.
//!
//! PINGRESP [MQTT-3.13]:
//!
//!   Fixed Header:
//!     Byte 1: 0xD0 (type=13, flags=0b0000)
//!     Byte 2: 0x00 (remaining length, always 0)
//!
//!   No variable header, no payload.
//! ```

use bytes::{Bytes, BytesMut};

use crate::{DecodeError, EncodeError, PacketType};

/// PINGREQ packet — client keep-alive probe [MQTT-3.12]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PingReq;

impl PingReq {
    /// Fixed header flags are always 0b0000 [MQTT-2.2.2, Table 2.2]
    const FLAGS: u8 = 0b0000;

    pub(super) fn flags(&self) -> u8 {
        Self::FLAGS
    }

    pub(super) fn encoded_body_len(&self) -> usize {
        0
    }

    pub(super) fn encode_body(&self, _buf: &mut BytesMut) -> Result<(), EncodeError> {
        Ok(())
    }

    pub(super) fn decode_body(header_flags: u8, buf: Bytes) -> Result<Self, DecodeError> {
        if header_flags != Self::FLAGS {
            return Err(DecodeError::InvalidFlags {
                packet_type: PacketType::PingReq,
                flags: header_flags,
            });
        }
        // PINGREQ has no variable header and no payload, so any byte here is dead
        // weight the protocol gives no meaning to
        if !buf.is_empty() {
            return Err(DecodeError::TrailingBytes { count: buf.len() });
        }
        Ok(Self)
    }
}

/// PINGRESP packet — broker's reply to a PINGREQ [MQTT-3.13]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PingResp;

impl PingResp {
    /// Fixed header flags are always 0b0000 [MQTT-2.2.2, Table 2.2]
    const FLAGS: u8 = 0b0000;

    pub(super) fn flags(&self) -> u8 {
        Self::FLAGS
    }

    pub(super) fn encoded_body_len(&self) -> usize {
        0
    }

    pub(super) fn encode_body(&self, _buf: &mut BytesMut) -> Result<(), EncodeError> {
        Ok(())
    }

    pub(super) fn decode_body(header_flags: u8, buf: Bytes) -> Result<Self, DecodeError> {
        if header_flags != Self::FLAGS {
            return Err(DecodeError::InvalidFlags {
                packet_type: PacketType::PingResp,
                flags: header_flags,
            });
        }
        if !buf.is_empty() {
            return Err(DecodeError::TrailingBytes { count: buf.len() });
        }
        Ok(Self)
    }
}

#[cfg(test)]
mod tests {
    use bytes::{Bytes, BytesMut};

    use super::*;
    use crate::v3::Packet;
    use crate::{DecodeError, PacketType};

    #[test]
    fn pingreq_encode() {
        let mut buf = BytesMut::new();
        Packet::PingReq(PingReq).encode(&mut buf).unwrap();
        assert_eq!(&buf[..], &[0xC0, 0x00]);
    }

    #[test]
    fn pingreq_decode() {
        let mut buf = BytesMut::from(&[0xC0u8, 0x00][..]);
        let pkt = Packet::decode(&mut buf).unwrap().unwrap();
        assert_eq!(pkt, Packet::PingReq(PingReq));
        assert!(buf.is_empty());
    }

    #[test]
    fn pingreq_roundtrip() {
        let mut buf = BytesMut::new();
        Packet::PingReq(PingReq).encode(&mut buf).unwrap();
        let pkt = Packet::decode(&mut buf).unwrap().unwrap();
        assert_eq!(pkt, Packet::PingReq(PingReq));
    }

    #[test]
    fn pingreq_invalid_flags() {
        assert_eq!(
            PingReq::decode_body(0x01, Bytes::new()),
            Err(DecodeError::InvalidFlags {
                packet_type: PacketType::PingReq,
                flags: 0x01,
            })
        );
    }

    #[test]
    fn pingreq_trailing_bytes() {
        let buf = Bytes::from_static(&[0xFF]);
        assert_eq!(
            PingReq::decode_body(0x00, buf),
            Err(DecodeError::TrailingBytes { count: 1 })
        );
    }

    #[test]
    fn pingresp_encode() {
        let mut buf = BytesMut::new();
        Packet::PingResp(PingResp).encode(&mut buf).unwrap();
        assert_eq!(&buf[..], &[0xD0, 0x00]);
    }

    #[test]
    fn pingresp_decode() {
        let mut buf = BytesMut::from(&[0xD0u8, 0x00][..]);
        let pkt = Packet::decode(&mut buf).unwrap().unwrap();
        assert_eq!(pkt, Packet::PingResp(PingResp));
    }

    #[test]
    fn pingresp_invalid_flags() {
        assert_eq!(
            PingResp::decode_body(0x01, Bytes::new()),
            Err(DecodeError::InvalidFlags {
                packet_type: PacketType::PingResp,
                flags: 0x01,
            })
        );
    }

    #[test]
    fn pingresp_trailing_bytes() {
        let buf = Bytes::from_static(&[0xFF]);
        assert_eq!(
            PingResp::decode_body(0x00, buf),
            Err(DecodeError::TrailingBytes { count: 1 })
        );
    }
}