symqtt-codec 0.1.0

MQTT 3.1.1/5.0 packet codec — role-neutral, runtime-free
Documentation
//! DISCONNECT packet encoding/decoding [MQTTv5-3.14]
//!
//! ```text
//! DISCONNECT [MQTTv5-3.14]:
//!
//!   Fixed Header:
//!     Byte 1: 0xE0 (type=14, flags=0b0000)
//!     Byte 2..N: Remaining Length
//!
//!   Variable Header:
//!     Disconnect Reason Code: 1 byte (may be omitted if 0x00 and no properties)
//!     Properties Length:      variable-length integer
//!     Properties:
//!       0x11 Session Expiry Interval (4 bytes)
//!       0x1F Reason String (UTF-8)
//!       0x26 User Property (UTF-8 pair, repeatable)
//!       0x1C Server Reference (UTF-8)
//!
//!   No payload.
//! ```

use bytes::{Buf, Bytes, BytesMut};

use super::property::{self, PROP_ID_LEN, PropertyId, properties_encoded_len, write_properties_len};
use super::reason_code::ReasonCode;
use crate::{DecodeError, EncodeError, PacketType, primitives};

/// DISCONNECT properties [MQTTv5-3.14.2.2]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DisconnectProperties {
    /// Session expiry interval override [MQTTv5-3.14.2.2.2]
    pub session_expiry_interval: Option<u32>,
    /// Human-readable reason string [MQTTv5-3.14.2.2.3]
    pub reason_string: Option<String>,
    /// User properties [MQTTv5-3.14.2.2.4]
    pub user_properties: Vec<(String, String)>,
    /// Server reference for redirection [MQTTv5-3.14.2.2.5]
    pub server_reference: Option<String>,
}

impl DisconnectProperties {
    fn encoded_len(&self) -> usize {
        let mut len = 0;
        if self.session_expiry_interval.is_some() {
            len += PROP_ID_LEN + PropertyId::SESSION_EXPIRY_INTERVAL_LEN;
        }
        if let Some(ref s) = self.reason_string {
            len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
        }
        for (k, v) in &self.user_properties {
            len += PROP_ID_LEN + primitives::string_pair_encoded_len(k.len(), v.len());
        }
        if let Some(ref s) = self.server_reference {
            len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
        }
        len
    }

    fn encode(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
        let props_len = self.encoded_len();
        write_properties_len(props_len, buf);

        if let Some(v) = self.session_expiry_interval {
            primitives::write_u8(PropertyId::SessionExpiryInterval as u8, buf);
            primitives::write_u32(v, buf);
        }
        if let Some(ref s) = self.reason_string {
            primitives::write_u8(PropertyId::ReasonString as u8, buf);
            primitives::write_string(s, buf)?;
        }
        for (k, v) in &self.user_properties {
            primitives::write_u8(PropertyId::UserProperty as u8, buf);
            primitives::write_string_pair(k, v, buf)?;
        }
        if let Some(ref s) = self.server_reference {
            primitives::write_u8(PropertyId::ServerReference as u8, buf);
            primitives::write_string(s, buf)?;
        }
        Ok(())
    }

    fn decode(mut buf: Bytes) -> Result<Self, DecodeError> {
        let mut props = Self::default();
        while buf.has_remaining() {
            let id_byte = primitives::read_u8(&mut buf)?;
            let id = PropertyId::try_from(id_byte).map_err(|_| DecodeError::InvalidProperty {
                packet_type: PacketType::Disconnect,
                id: id_byte,
            })?;
            match id {
                PropertyId::SessionExpiryInterval => {
                    if props.session_expiry_interval.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.session_expiry_interval = Some(primitives::read_u32(&mut buf)?);
                }
                PropertyId::ReasonString => {
                    if props.reason_string.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.reason_string = Some(primitives::read_string(&mut buf)?);
                }
                PropertyId::UserProperty => {
                    props.user_properties.push(primitives::read_string_pair(&mut buf)?);
                }
                PropertyId::ServerReference => {
                    if props.server_reference.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.server_reference = Some(primitives::read_string(&mut buf)?);
                }
                _ => {
                    return Err(DecodeError::InvalidProperty {
                        packet_type: PacketType::Disconnect,
                        id: id_byte,
                    });
                }
            }
        }
        Ok(props)
    }
}

/// DISCONNECT packet [MQTTv5-3.14]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Disconnect {
    /// Disconnect reason code [MQTTv5-3.14.2.1]
    pub reason_code: ReasonCode,
    /// Properties [MQTTv5-3.14.2.2]
    pub properties: DisconnectProperties,
}

impl Disconnect {
    const FLAGS: u8 = 0b0000;

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

    pub(super) fn encoded_body_len(&self) -> usize {
        let props_body_len = self.properties.encoded_len();
        if self.reason_code as u8 == 0x00 && props_body_len == 0 {
            return 0;
        }
        1 + properties_encoded_len(props_body_len)
    }

    pub(super) fn encode_body(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
        let props_body_len = self.properties.encoded_len();
        if self.reason_code as u8 == 0x00 && props_body_len == 0 {
            return Ok(());
        }
        primitives::write_u8(self.reason_code as u8, buf);
        if props_body_len > 0 {
            self.properties.encode(buf)?;
        } else {
            write_properties_len(0, buf);
        }
        Ok(())
    }

    pub(super) fn decode_body(header_flags: u8, mut buf: Bytes) -> Result<Self, DecodeError> {
        if header_flags != Self::FLAGS {
            return Err(DecodeError::InvalidFlags {
                packet_type: PacketType::Disconnect,
                flags: header_flags,
            });
        }
        if buf.is_empty() {
            return Ok(Self {
                reason_code: ReasonCode::Success,
                properties: DisconnectProperties::default(),
            });
        }
        let reason_byte = primitives::read_u8(&mut buf)?;
        let reason_code = ReasonCode::try_from(reason_byte)?;
        let properties = if buf.has_remaining() {
            let props_buf = property::read_properties_bytes(&mut buf)?;
            DisconnectProperties::decode(props_buf)?
        } else {
            DisconnectProperties::default()
        };
        if !buf.is_empty() {
            return Err(DecodeError::TrailingBytes { count: buf.len() });
        }
        Ok(Self {
            reason_code,
            properties,
        })
    }
}

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

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

    fn roundtrip(packet: Packet) -> Packet {
        let mut buf = BytesMut::new();
        packet.encode(&mut buf).unwrap();
        Packet::decode(&mut buf).unwrap().unwrap()
    }

    #[test]
    fn disconnect_abbreviated_normal() {
        // reason=Success, no props → body=0 bytes
        let pkt = Packet::Disconnect(Disconnect {
            reason_code: ReasonCode::Success,
            properties: DisconnectProperties::default(),
        });
        let mut buf = BytesMut::new();
        pkt.encode(&mut buf).unwrap();
        assert_eq!(&buf[..], &[0xE0, 0x00]); // 0 body
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn disconnect_non_success_no_properties() {
        let pkt = Packet::Disconnect(Disconnect {
            reason_code: ReasonCode::DisconnectWithWill,
            properties: DisconnectProperties::default(),
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn disconnect_full_properties() {
        let pkt = Packet::Disconnect(Disconnect {
            reason_code: ReasonCode::ServerShuttingDown,
            properties: DisconnectProperties {
                session_expiry_interval: Some(0),
                reason_string: Some("shutting down".to_owned()),
                user_properties: vec![("k".to_owned(), "v".to_owned())],
                server_reference: Some("other:1883".to_owned()),
            },
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

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

    #[test]
    fn disconnect_empty_body_decodes_as_success() {
        let result = Disconnect::decode_body(0x00, Bytes::new()).unwrap();
        assert_eq!(result.reason_code, ReasonCode::Success);
        assert_eq!(result.properties, DisconnectProperties::default());
    }
}