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)]
53pub enum QoS {
55 AtMostOnce = 0,
61 AtLeastOnce = 1,
67 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}