simple_pub_sub_message/lib.rs
1pub mod error;
2pub mod header;
3pub mod message;
4pub mod pkt;
5pub use pkt::PktType;
6
7pub mod constants {
8
9 /// supported versions for the pub-sub header format/protocol.
10 pub const SUPPORTED_VERSIONS: [[u8; 2]; 1] = [[0x00, 0x01]];
11
12 /// default version for the pub-sub header format/protocol.
13 pub const DEFAULT_VERSION: [u8; 2] = [0x00, 0x01];
14
15 /// the header length
16 pub const HEADER_LEN: usize = 8;
17
18 /// Packet Type Publish
19 pub const PUBLISH: u8 = 0x02;
20 /// Packet Type Subscribe
21 pub const SUBSCRIBE: u8 = 0x03;
22 /// Packet Type Unsubscribe
23 pub const UNSUBSCRIBE: u8 = 0x04;
24 /// Packet Type Query
25 pub const QUERY: u8 = 0x05;
26 /// Packet Type Publish Acknowledgement
27 pub const PUBLISHACK: u8 = 0x0B;
28 /// Packet Type Subscribe Acknowledgement
29 pub const SUBSCRIBEACK: u8 = 0x0C;
30 /// Packet Type Unsubscribe Acknowledgement
31 pub const UNSUBSCRIBEACK: u8 = 0x0D;
32 /// Packet Type Query Response
33 pub const QUERYRESP: u8 = 0x0E;
34}
35
36#[cfg(test)]
37mod tests {
38 use log::info;
39
40 use crate::header::Header;
41
42 // use super::*;
43
44 #[test]
45 fn header_parse_pass() {
46 // The test header is
47 // Header { header: 15, version: [0, 1], pkt_type: PUBLISH, topic_length: 3, message_length: 12, padding: 0 }
48 assert!(Header::try_from(vec![
49 15, // `HEADER_BYTE`
50 0, 1, // `VERSION_BYTE_0`, `VERSION_BYTE_1`
51 2, // `PktType`
52 3, // `TOPIC_LENGTH_BYTE`
53 0, 12, // `MESSAGE_LENGTH_BYTE_0`, `MESSAGE_LENGTH_BYTE_1`
54 0, // `PADDING_BYTE`
55 ])
56 .is_ok());
57 }
58
59 #[test]
60 fn header_parse_fail() {
61 // The test header is
62 // Header { header: 16, version: [0, 1], pkt_type: PUBLISH, topic_length: 3, message_length: 12, padding: 0 }
63 assert!(Header::try_from(vec![
64 16, // `HEADER_BYTE`
65 0, 1, // `VERSION_BYTE_0`, `VERSION_BYTE_1`
66 2, // `PktType`
67 3, // `TOPIC_LENGTH_BYTE`
68 0, 12, // `MESSAGE_LENGTH_BYTE_0`, `MESSAGE_LENGTH_BYTE_1`
69 0, // `PADDING_BYTE`
70 ])
71 .is_err());
72 }
73
74 #[test]
75 fn message_parse_pass() {
76 use crate::message::Msg;
77
78 let buf = [
79 15, 0, 1, 2, 3, 0, 12, 0, 97, 98, 99, 116, 101, 115, 116, 32, 109, 101, 115, 115, 97,
80 103, 101,
81 ];
82 let msg = Msg::try_from(buf.as_ref());
83 info!("{:?}", msg);
84 assert!(msg.is_ok());
85 info!("{:?}", msg.unwrap());
86 }
87
88 #[test]
89 fn message_parse_fail() {
90 use crate::message::Msg;
91 env_logger::init();
92 let buf = [
93 15, 0, 1, 2, 3, 0, 12, 0, 97, 98, 99, 116, 101, 115, 116, 32, 109, 101, 115, 115, 97,
94 103,
95 ];
96 let msg = Msg::try_from(buf.as_ref());
97 assert!(msg.is_err());
98 }
99}