mqttrs2/lib.rs
1//! `mqttrs` is a codec for the MQTT protocol.
2//!
3//! The API aims to be straightforward and composable, usable with plain `std` or with a framework
4//! like [tokio]. The decoded packet is help in a [Packet] struct, and the encoded bytes in a
5//! [bytes::BytesMut] struct. Convert between the two using [encode()] and [decode()]. Almost all
6//! struct fields can be accessed directly, to create or read packets.
7//!
8//! It currently targets [MQTT 3.1], with [MQTT 5] support planned.
9//!
10//! ```
11//! use mqttrs2::*;
12//! use bytes::BytesMut;
13//!
14//! // Allocate buffer.
15//! let mut buf = [0u8; 1024];
16//!
17//! // Encode an MQTT Connect packet.
18//! let pkt = Packet::Connect(Connect { protocol: Protocol::MQTT311,
19//! keep_alive: 30,
20//! client_id: "doc_client",
21//! clean_session: true,
22//! last_will: None,
23//! username: None,
24//! password: None });
25//! let len = encode_slice(&pkt, &mut buf).unwrap();
26//! assert_eq!(&buf[14..len], b"doc_client");
27//! let mut encoded = buf.clone();
28//!
29//! // Decode one packet. The buffer will advance to the next packet.
30//! assert_eq!(Ok(Some(pkt)), decode_slice(&mut buf));
31//!
32//! // Example decode failures.
33//! let mut incomplete = encoded.split_at(10).0;
34//! assert_eq!(Ok(None), decode_slice(&mut incomplete));
35//! let mut garbage = BytesMut::from(&[0u8,0,0,0] as &[u8]);
36//! assert_eq!(Err(Error::InvalidHeader), decode_slice(&mut garbage));
37//! ```
38//!
39//! [MQTT 3.1]: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html
40//! [MQTT 5]: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html
41//! [tokio]: https://tokio.rs/
42//! [Packet]: enum.Packet.html
43//! [encode_slice()]: fn.encode_slice.html
44//! [decode_slice()]: fn.decode_slice.html
45//! [bytes::BytesMut]: https://docs.rs/bytes/1.0.0/bytes/struct.BytesMut.html
46
47#![cfg_attr(not(test), no_std)]
48
49#[cfg(feature = "std")]
50extern crate std;
51
52mod connect;
53mod decoder;
54mod encoder;
55mod packet;
56mod publish;
57mod subscribe;
58mod utils;
59
60// Proptest does not currently support borrowed data in strategies:
61// https://github.com/AltSysrq/proptest/issues/9
62//
63// #[cfg(test)]
64// mod codec_test;
65#[cfg(test)]
66mod decoder_test;
67#[cfg(test)]
68mod encoder_test;
69
70pub use crate::{
71 connect::{Connack, Connect, ConnectReturnCode, LastWill, Protocol},
72 decoder::{clone_packet, decode_slice, decode_slice_with_len},
73 encoder::encode_slice,
74 packet::{Packet, PacketType},
75 publish::Publish,
76 subscribe::{Suback, Subscribe, SubscribeReturnCodes, SubscribeTopic, Unsubscribe},
77 utils::{Error, Pid, QoS, QosPid},
78};