mqtt/
proto.rs

1use std::fmt::{self, Display, Formatter};
2use std::ops::Deref;
3
4use rand::{thread_rng, Rng};
5
6#[macro_export]
7macro_rules! const_enum {
8    ($name:ty : $repr:ty) => {
9        impl ::std::convert::From<$repr> for $name {
10            fn from(u: $repr) -> Self {
11                unsafe { ::std::mem::transmute(u) }
12            }
13        }
14
15        impl ::std::convert::Into<$repr> for $name {
16            fn into(self) -> $repr {
17                unsafe { ::std::mem::transmute(self) }
18            }
19        }
20    }
21}
22
23pub const DEFAULT_MQTT_LEVEL: u8 = 4;
24
25#[repr(u8)]
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Protocol {
28    MQTT(u8),
29}
30
31impl Protocol {
32    pub fn name(&self) -> &'static str {
33        match *self {
34            Protocol::MQTT(_) => "MQTT",
35        }
36    }
37
38    pub fn level(&self) -> u8 {
39        match *self {
40            Protocol::MQTT(level) => level,
41        }
42    }
43}
44
45impl Default for Protocol {
46    fn default() -> Self {
47        return Protocol::MQTT(DEFAULT_MQTT_LEVEL);
48    }
49}
50
51#[repr(u8)]
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53/// Quality of Service levels
54pub enum QoS {
55    /// At most once delivery
56    ///
57    /// The message is delivered according to the capabilities of the underlying network.
58    /// No response is sent by the receiver and no retry is performed by the sender.
59    /// The message arrives at the receiver either once or not at all.
60    AtMostOnce = 0,
61    /// At least once delivery
62    ///
63    /// This quality of service ensures that the message arrives at the receiver at least once.
64    /// A QoS 1 PUBLISH Packet has a Packet Identifier in its variable header
65    /// and is acknowledged by a PUBACK Packet.
66    AtLeastOnce = 1,
67    /// Exactly once delivery
68    ///
69    /// This is the highest quality of service,
70    /// for use when neither loss nor duplication of messages are acceptable.
71    /// There is an increased overhead associated with this quality of service.
72    ExactlyOnce = 2,
73}
74
75const_enum!(QoS: u8);
76
77#[derive(Debug, PartialEq, Clone, Default)]
78pub struct ClientId(String);
79
80impl ClientId {
81    pub fn new() -> ClientId {
82        Self::with_size(16)
83    }
84
85    pub fn with_size(size: usize) -> ClientId {
86        ClientId(thread_rng().gen_ascii_chars().take(size).collect())
87    }
88}
89
90impl Deref for ClientId {
91    type Target = str;
92
93    fn deref(&self) -> &Self::Target {
94        &self.0
95    }
96}
97
98impl Display for ClientId {
99    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
100        f.write_str(&self.0)
101    }
102}
103
104pub type PacketId = u16;
105
106#[derive(Debug, PartialEq, Clone)]
107pub struct Message<'a> {
108    pub topic: &'a str,
109    pub payload: &'a [u8],
110    pub qos: QoS,
111}