mqute_codec/protocol/version.rs
1//! # MQTT Protocol Version
2//!
3//! This module provides an enum to represent the MQTT protocol versions and utilities
4//! for converting between protocol versions and their corresponding numeric values.
5//!
6//! The `Protocol` enum represents the supported MQTT protocol versions:
7//! - `V3`: MQTT v3.1 (also known as MQIsdp)
8//! - `V4`: MQTT v3.1.1
9//! - `V5`: MQTT v5.0
10//!
11//! The enum also provides methods to convert between protocol versions and their
12//! numeric representations, as well as to retrieve the protocol name.
13
14use crate::Error;
15
16/// Represents the MQTT protocol version.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum Protocol {
19 /// MQTT v3.1
20 V3,
21 /// MQTT v3.1.1
22 V4,
23 /// MQTT v5.0
24 V5,
25}
26
27impl From<Protocol> for u8 {
28 /// Converts the `Protocol` enum into its corresponding numeric value.
29 ///
30 /// # Examples
31 ///
32 /// ```rust
33 /// use mqute_codec::protocol::Protocol;
34 ///
35 /// let protocol = Protocol::V5;
36 /// let value: u8 = protocol.into();
37 /// assert_eq!(value, 0x05);
38 /// ```
39 fn from(value: Protocol) -> Self {
40 match value {
41 Protocol::V3 => 0x03,
42 Protocol::V4 => 0x04,
43 Protocol::V5 => 0x05,
44 }
45 }
46}
47
48impl TryFrom<u8> for Protocol {
49 type Error = Error;
50
51 /// Attempts to convert a numeric value into a `Protocol` enum.
52 ///
53 /// # Errors
54 /// Returns an `Error::InvalidProtocolLevel` if the value is not a valid protocol version.
55 ///
56 /// # Examples
57 ///
58 /// ```rust
59 /// use mqute_codec::protocol::Protocol;
60 /// use mqute_codec::Error;
61 ///
62 /// let protocol = Protocol::try_from(0x04).unwrap();
63 /// assert_eq!(protocol, Protocol::V4);
64 ///
65 /// let result = Protocol::try_from(0x06);
66 /// assert!(result.is_err());
67 /// ```
68 fn try_from(value: u8) -> Result<Self, Self::Error> {
69 match value {
70 0x03 => Ok(Protocol::V3),
71 0x04 => Ok(Protocol::V4),
72 0x05 => Ok(Protocol::V5),
73 _ => Err(Error::InvalidProtocolLevel(value)),
74 }
75 }
76}
77
78impl Protocol {
79 /// Returns the protocol name as a static string.
80 ///
81 /// - For `Protocol::V3`, the name is `"MQIsdp"`.
82 /// - For `Protocol::V4` and `Protocol::V5`, the name is `"MQTT"`.
83 ///
84 /// # Examples
85 ///
86 /// ```rust
87 /// use mqute_codec::protocol::Protocol;
88 ///
89 /// let protocol = Protocol::V3;
90 /// assert_eq!(protocol.name(), "MQIsdp");
91 ///
92 /// let protocol = Protocol::V5;
93 /// assert_eq!(protocol.name(), "MQTT");
94 /// ```
95 pub fn name(self) -> &'static str {
96 match self {
97 Protocol::V3 => "MQIsdp",
98 // Same for V4 and V5
99 _ => "MQTT",
100 }
101 }
102}