embedded_mqtt/
qos.rs

1use core::{
2    fmt,
3    convert::{TryFrom, From},
4    result::Result,
5};
6
7#[derive(Copy, Clone, PartialEq, Eq, Debug)]
8pub enum QoS {
9    AtMostOnce,
10    AtLeastOnce,
11    ExactlyOnce,
12}
13
14#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15pub enum Error {
16    BadPattern,
17}
18
19impl TryFrom<u8> for QoS {
20    type Error = Error;
21    
22    fn try_from(byte: u8) -> Result<QoS, Error> {
23        let qos = match byte & 0b11 {
24            0b00 => QoS::AtMostOnce,
25            0b01 => QoS::AtLeastOnce,
26            0b10 => QoS::ExactlyOnce,
27            _ => return Err(Error::BadPattern),
28        };
29
30        Ok(qos)
31    }
32}
33
34impl From<QoS> for u8 {
35    fn from(qos: QoS) -> u8 {
36        match qos {
37            QoS::AtMostOnce  => 0b00,
38            QoS::AtLeastOnce => 0b01,
39            QoS::ExactlyOnce => 0b10,
40        }
41    }
42}
43
44impl Error {
45    fn desc(&self) -> &'static str {
46        match *self {
47            Error::BadPattern => "invalid QoS bit pattern",
48        }
49    }
50}
51
52impl fmt::Display for Error {
53    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54        f.write_str(self.desc())
55    }
56}
57
58#[cfg(feature = "std")]
59impl ::std::error::Error for Error {
60    fn description(&self) -> &str {
61        self.desc()
62    }
63}