simple_pub_sub_message/
pkt.rs

1use crate::constants::*;
2use std::fmt::Display;
3
4/// Packet type
5#[repr(u8)]
6#[derive(Debug, Clone, PartialEq)]
7pub enum PktType {
8    /// publish
9    PUBLISH = PUBLISH,
10    /// subscribe
11    SUBSCRIBE = SUBSCRIBE,
12    /// unsubscribe
13    UNSUBSCRIBE = UNSUBSCRIBE,
14    /// query the topics
15    QUERY = QUERY,
16    /// acknowledgement to publish
17    PUBLISHACK = PUBLISHACK,
18    /// acknowledgement to subscribe
19    SUBSCRIBEACK = SUBSCRIBEACK,
20    /// acknowledgement to unsubscribe
21    UNSUBSCRIBEACK = UNSUBSCRIBEACK,
22    /// response to the query packet
23    QUERYRESP = QUERYRESP,
24}
25
26impl PktType {
27    /// returns the byte for the given type of packet
28    /// ```
29    /// use simple_pub_sub_message::pkt::PktType;
30    /// let publish_byte = PktType::PUBLISH.byte();
31    /// assert_eq!(publish_byte, simple_pub_sub_message::constants::PUBLISH);
32    ///
33    /// ```
34    pub fn byte(&self) -> u8 {
35        match self {
36            PktType::PUBLISH => PUBLISH,
37            PktType::SUBSCRIBE => SUBSCRIBE,
38            PktType::UNSUBSCRIBE => UNSUBSCRIBE,
39            PktType::QUERY => QUERY,
40            PktType::PUBLISHACK => PUBLISHACK,
41            PktType::SUBSCRIBEACK => SUBSCRIBEACK,
42            PktType::UNSUBSCRIBEACK => UNSUBSCRIBEACK,
43            PktType::QUERYRESP => QUERYRESP,
44        }
45    }
46}
47
48impl Display for PktType {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        let pkt = match self {
51            PktType::PUBLISH => "PUBLISH".to_string(),
52            PktType::SUBSCRIBE => "SUBSCRIBE".to_string(),
53            PktType::UNSUBSCRIBE => "UNSUBSCRIBE".to_string(),
54            PktType::QUERY => "QUERY".to_string(),
55            PktType::PUBLISHACK => "PUBLISH_ACK".to_string(),
56            PktType::SUBSCRIBEACK => "SUBSCRIBE_ACK".to_string(),
57            PktType::UNSUBSCRIBEACK => "UNSUBSCRIBE_ACK".to_string(),
58            PktType::QUERYRESP => "QUERY_RESP".to_string(),
59        };
60        write!(f, "{}", pkt)
61    }
62}