symqtt-codec 0.1.0

MQTT 3.1.1/5.0 packet codec — role-neutral, runtime-free
Documentation
//! MQTT 3.1.1 / 5.0 packet codec
//!
//! Role-neutral encoder/decoder for client and server packets. No async runtime.
//! Framing is in [`v3::Packet::decode`] / [`v5::Packet::decode`]: a partial packet
//! returns `Ok(None)` and consumes nothing.
//!
//! # Modules
//!
//! - [`v3`] — MQTT 3.1.1 packets
//! - [`v5`] — MQTT 5.0 packets, properties, reason codes
//!
//! # Example
//!
//! ```
//! use bytes::BytesMut;
//! use symqtt_codec::v3::{Packet, Subscribe, SubscribeFilter};
//! use symqtt_codec::QoS;
//!
//! let mut wire = BytesMut::new();
//! Packet::Subscribe(Subscribe {
//!     pkid: 1,
//!     filters: vec![SubscribeFilter { topic: "a/b".to_owned(), qos: QoS::AtLeastOnce }],
//! })
//! .encode(&mut wire)?;
//!
//! // Framing lives in decode: a partial packet yields Ok(None) and consumes nothing
//! let packet = Packet::decode(&mut wire)?.expect("a whole packet");
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

#![cfg_attr(docsrs, feature(doc_cfg))]

pub(crate) mod error;
pub(crate) mod fixed_header;
pub(crate) mod primitives;
pub(crate) mod varint;

pub mod v3;
pub mod v5;

pub use error::{DecodeError, EncodeError};
pub use fixed_header::PacketType;

/// Largest remaining length the four-byte variable-length integer can express [MQTT-2.2.3]
pub const MAX_REMAINING_LEN: usize = 268_435_455;

/// MQTT Quality of Service level [MQTT-4.3]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum QoS {
    /// QoS 0 — at most once delivery
    AtMostOnce = 0,
    /// QoS 1 — at least once delivery
    AtLeastOnce = 1,
    /// QoS 2 — exactly once delivery
    ExactlyOnce = 2,
}

impl TryFrom<u8> for QoS {
    type Error = DecodeError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(Self::AtMostOnce),
            1 => Ok(Self::AtLeastOnce),
            2 => Ok(Self::ExactlyOnce),
            _ => Err(DecodeError::ProtocolError {
                reason: "invalid QoS value",
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn qos_from_0() {
        assert_eq!(QoS::try_from(0u8), Ok(QoS::AtMostOnce));
    }

    #[test]
    fn qos_from_1() {
        assert_eq!(QoS::try_from(1u8), Ok(QoS::AtLeastOnce));
    }

    #[test]
    fn qos_from_2() {
        assert_eq!(QoS::try_from(2u8), Ok(QoS::ExactlyOnce));
    }

    #[test]
    fn qos_from_3_invalid() {
        assert_eq!(
            QoS::try_from(3u8),
            Err(DecodeError::ProtocolError {
                reason: "invalid QoS value"
            })
        );
    }

    #[test]
    fn qos_from_255_invalid() {
        assert!(QoS::try_from(255u8).is_err());
    }
}