mqute_codec/protocol/
packet.rs

1//! # MQTT Packet Type
2//!
3//! This module provides an enum to represent the types of MQTT packets and utilities
4//! for converting between packet types and their corresponding numeric values.
5//!
6//! The `PacketType` enum represents the types of MQTT packets as defined by the MQTT protocol.
7//! Each packet type corresponds to a specific numeric value, which is used in the fixed header
8//! of MQTT packets.
9
10use crate::Error;
11
12/// Represents the type of MQTT packet.
13///
14/// Each packet type corresponds to a specific numeric value, as defined by the MQTT protocol.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum PacketType {
17    /// Client request to connect to the server.
18    Connect = 1,
19    /// Connect acknowledgment.
20    ConnAck,
21    /// Publish message.
22    Publish,
23    /// Publish acknowledgment.
24    PubAck,
25    /// Publish received (assured delivery part 1).
26    PubRec,
27    /// Publish release (assured delivery part 2).
28    PubRel,
29    /// Publish complete (assured delivery part 3).
30    PubComp,
31    /// Client subscribe request.
32    Subscribe,
33    /// Subscribe acknowledgment.
34    SubAck,
35    /// Unsubscribe request.
36    Unsubscribe,
37    /// Unsubscribe acknowledgment.
38    UnsubAck,
39    /// PING request.
40    PingReq,
41    /// PING response.
42    PingResp,
43    /// Client is disconnecting.
44    Disconnect,
45    /// Authentication exchange.
46    Auth,
47}
48
49impl TryFrom<u8> for PacketType {
50    type Error = Error;
51
52    /// Attempts to convert a numeric value into a `PacketType` enum.
53    ///
54    /// # Errors
55    /// Returns an `Error::InvalidPacketType` if the value is not a valid packet type.
56    ///
57    /// # Examples
58    ///
59    /// ```rust
60    /// use mqute_codec::protocol::PacketType;
61    /// use mqute_codec::Error;
62    ///
63    /// let packet_type = PacketType::try_from(3).unwrap();
64    /// assert_eq!(packet_type, PacketType::Publish);
65    ///
66    /// let result = PacketType::try_from(16);
67    /// assert!(result.is_err());
68    /// ```
69    fn try_from(value: u8) -> Result<Self, Self::Error> {
70        let packet_type = match value {
71            1 => PacketType::Connect,
72            2 => PacketType::ConnAck,
73            3 => PacketType::Publish,
74            4 => PacketType::PubAck,
75            5 => PacketType::PubRec,
76            6 => PacketType::PubRel,
77            7 => PacketType::PubComp,
78            8 => PacketType::Subscribe,
79            9 => PacketType::SubAck,
80            10 => PacketType::Unsubscribe,
81            11 => PacketType::UnsubAck,
82            12 => PacketType::PingReq,
83            13 => PacketType::PingResp,
84            14 => PacketType::Disconnect,
85            15 => PacketType::Auth,
86            _ => return Err(Error::InvalidPacketType(value)),
87        };
88
89        Ok(packet_type)
90    }
91}