Skip to main content

mqtt5_protocol/types/
mod.rs

1mod connect;
2mod message;
3mod publish;
4mod subscribe;
5
6pub use crate::protocol::v5::reason_codes::ReasonCode;
7pub use connect::{ConnectOptions, ConnectProperties, ConnectResult};
8pub use message::{Message, MessageProperties, WillMessage, WillProperties};
9pub use publish::{PublishOptions, PublishProperties, PublishResult};
10pub use subscribe::{RetainHandling, SubscribeOptions};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13pub enum ProtocolVersion {
14    V311,
15    #[default]
16    V5,
17}
18
19impl ProtocolVersion {
20    #[must_use]
21    pub fn as_u8(self) -> u8 {
22        match self {
23            ProtocolVersion::V311 => 4,
24            ProtocolVersion::V5 => 5,
25        }
26    }
27}
28
29impl From<ProtocolVersion> for u8 {
30    fn from(version: ProtocolVersion) -> Self {
31        version.as_u8()
32    }
33}
34
35impl TryFrom<u8> for ProtocolVersion {
36    type Error = ();
37
38    fn try_from(value: u8) -> Result<Self, Self::Error> {
39        match value {
40            4 => Ok(ProtocolVersion::V311),
41            5 => Ok(ProtocolVersion::V5),
42            _ => Err(()),
43        }
44    }
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
48pub enum QoS {
49    AtMostOnce = 0,
50    AtLeastOnce = 1,
51    ExactlyOnce = 2,
52}
53
54impl From<u8> for QoS {
55    fn from(value: u8) -> Self {
56        match value {
57            1 => QoS::AtLeastOnce,
58            2 => QoS::ExactlyOnce,
59            _ => QoS::AtMostOnce,
60        }
61    }
62}
63
64impl From<QoS> for u8 {
65    fn from(qos: QoS) -> Self {
66        qos as u8
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    #[test]
75    fn test_qos_values() {
76        assert_eq!(QoS::AtMostOnce as u8, 0);
77        assert_eq!(QoS::AtLeastOnce as u8, 1);
78        assert_eq!(QoS::ExactlyOnce as u8, 2);
79    }
80
81    #[test]
82    fn test_qos_from_u8() {
83        assert_eq!(QoS::from(0), QoS::AtMostOnce);
84        assert_eq!(QoS::from(1), QoS::AtLeastOnce);
85        assert_eq!(QoS::from(2), QoS::ExactlyOnce);
86
87        assert_eq!(QoS::from(3), QoS::AtMostOnce);
88        assert_eq!(QoS::from(255), QoS::AtMostOnce);
89    }
90
91    #[test]
92    fn test_qos_into_u8() {
93        assert_eq!(u8::from(QoS::AtMostOnce), 0);
94        assert_eq!(u8::from(QoS::AtLeastOnce), 1);
95        assert_eq!(u8::from(QoS::ExactlyOnce), 2);
96    }
97}