Skip to main content

sz_orm_mqtt/
qos.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
4pub enum QoS {
5    #[default]
6    AtMostOnce,
7    AtLeastOnce,
8    ExactlyOnce,
9}
10
11impl QoS {
12    pub fn at_most_once() -> Self {
13        QoS::AtMostOnce
14    }
15
16    pub fn at_least_once() -> Self {
17        QoS::AtLeastOnce
18    }
19
20    pub fn exactly_once() -> Self {
21        QoS::ExactlyOnce
22    }
23
24    pub fn level(&self) -> u8 {
25        match self {
26            QoS::AtMostOnce => 0,
27            QoS::AtLeastOnce => 1,
28            QoS::ExactlyOnce => 2,
29        }
30    }
31
32    pub fn from_level(level: u8) -> Self {
33        match level {
34            1 => QoS::AtLeastOnce,
35            2 => QoS::ExactlyOnce,
36            _ => QoS::AtMostOnce,
37        }
38    }
39
40    pub fn is_at_most_once(&self) -> bool {
41        matches!(self, QoS::AtMostOnce)
42    }
43
44    pub fn is_at_least_once(&self) -> bool {
45        matches!(self, QoS::AtLeastOnce)
46    }
47
48    pub fn is_exactly_once(&self) -> bool {
49        matches!(self, QoS::ExactlyOnce)
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn test_at_most_once_factory() {
59        let qos = QoS::at_most_once();
60        assert_eq!(qos, QoS::AtMostOnce);
61        assert_eq!(qos.level(), 0);
62        assert!(qos.is_at_most_once());
63    }
64
65    #[test]
66    fn test_at_least_once_factory() {
67        let qos = QoS::at_least_once();
68        assert_eq!(qos, QoS::AtLeastOnce);
69        assert_eq!(qos.level(), 1);
70        assert!(qos.is_at_least_once());
71    }
72
73    #[test]
74    fn test_exactly_once_factory() {
75        let qos = QoS::exactly_once();
76        assert_eq!(qos, QoS::ExactlyOnce);
77        assert_eq!(qos.level(), 2);
78        assert!(qos.is_exactly_once());
79    }
80
81    #[test]
82    fn test_from_level_boundaries() {
83        assert_eq!(QoS::from_level(0), QoS::AtMostOnce);
84        assert_eq!(QoS::from_level(1), QoS::AtLeastOnce);
85        assert_eq!(QoS::from_level(2), QoS::ExactlyOnce);
86        assert_eq!(QoS::from_level(3), QoS::AtMostOnce);
87        assert_eq!(QoS::from_level(255), QoS::AtMostOnce);
88    }
89
90    #[test]
91    fn test_default_is_at_most_once() {
92        let qos: QoS = Default::default();
93        assert_eq!(qos, QoS::AtMostOnce);
94    }
95}