aboutsummaryrefslogtreecommitdiff
path: root/embedded-mqtt/src/qos.rs
blob: 0d464b42ed00a410c5fb40a3ed06e50f25be40af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#[derive(Debug)]
pub struct InvalidQos(u8);

impl core::fmt::Display for InvalidQos {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "invalid QoS value: '{}'", self.0)
    }
}

impl core::error::Error for InvalidQos {}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Qos {
    #[default]
    AtMostOnce,
    AtLeastOnce,
    ExactlyOnce,
}

impl core::fmt::Display for Qos {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(match self {
            Qos::AtMostOnce => "QoS::AtMostOnce",
            Qos::AtLeastOnce => "Qos::AtLeastOnce",
            Qos::ExactlyOnce => "Qos::ExactlyOnce",
        })
    }
}

impl Qos {
    pub fn to_u8(&self) -> u8 {
        match self {
            Qos::AtMostOnce => 0,
            Qos::AtLeastOnce => 1,
            Qos::ExactlyOnce => 2,
        }
    }

    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0 => Some(Self::AtMostOnce),
            1 => Some(Self::AtLeastOnce),
            2 => Some(Self::ExactlyOnce),
            _ => None,
        }
    }
}

impl TryFrom<u8> for Qos {
    type Error = InvalidQos;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match Self::from_u8(value) {
            Some(v) => Ok(v),
            None => Err(InvalidQos(value)),
        }
    }
}

impl From<Qos> for u8 {
    fn from(value: Qos) -> Self {
        value.to_u8()
    }
}