mqute_codec/protocol/
qos.rs

1//! # Quality of Service (QoS)
2//!
3//! This module provides an enum to represent the Quality of Service (QoS) levels
4//! in the MQTT protocol and utilities for converting between QoS levels and their
5//! corresponding numeric values.
6//!
7//! The `QoS` enum represents the three levels of Quality of Service in MQTT:
8//! - `AtMostOnce`: QoS level 0 (Fire and Forget)
9//! - `AtLeastOnce`: QoS level 1 (Acknowledged Delivery)
10//! - `ExactlyOnce`: QoS level 2 (Assured Delivery)
11
12use crate::Error;
13
14/// Represents the Quality of Service (QoS) levels in MQTT.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
16pub enum QoS {
17    /// QoS level 0: At most once delivery (Fire and Forget).
18    ///
19    /// The message is delivered according to the best efforts of the underlying network.
20    /// No acknowledgment is sent, and the message is not stored or re-transmitted.
21    AtMostOnce = 0,
22    /// QoS level 1: At least once delivery (Acknowledged Delivery).
23    ///
24    /// The message is assured to arrive but may arrive more than once.
25    AtLeastOnce = 1,
26    /// QoS level 2: Exactly once delivery (Assured Delivery).
27    ///
28    /// The message is assured to arrive exactly once.
29    ExactlyOnce = 2,
30}
31
32impl TryFrom<u8> for QoS {
33    type Error = Error;
34
35    /// Attempts to convert a numeric value into a `QoS` enum.
36    ///
37    /// # Errors
38    /// Returns an `Error::InvalidQos` if the value is not a valid QoS level.
39    ///
40    /// # Examples
41    ///
42    /// ```rust
43    /// use mqute_codec::protocol::QoS;
44    /// use mqute_codec::Error;
45    ///
46    /// let qos = QoS::try_from(1).unwrap();
47    /// assert_eq!(qos, QoS::AtLeastOnce);
48    ///
49    /// let result = QoS::try_from(3);
50    /// assert!(result.is_err());
51    /// ```
52    fn try_from(value: u8) -> Result<Self, Self::Error> {
53        match value {
54            0 => Ok(QoS::AtMostOnce),
55            1 => Ok(QoS::AtLeastOnce),
56            2 => Ok(QoS::ExactlyOnce),
57            n => Err(Error::InvalidQos(n)),
58        }
59    }
60}
61
62impl From<QoS> for u8 {
63    /// Converts the `QoS` enum into its corresponding numeric value.
64    ///
65    /// # Examples
66    ///
67    /// ```rust
68    /// use mqute_codec::protocol::QoS;
69    ///
70    /// let qos = QoS::ExactlyOnce;
71    /// let value: u8 = qos.into();
72    /// assert_eq!(value, 2);
73    /// ```
74    fn from(value: QoS) -> Self {
75        value as u8
76    }
77}