mqute_codec/codec/
encode.rs

1//! # Encoding Traits
2//!
3//! This module provides the `Encode` and `Encoded` traits, which define a common interface
4//! for encoding MQTT packets into a buffer and calculating their encoded length.
5//!
6//! - `Encode`: A trait for encoding MQTT packets into a buffer.
7//! - `Encoded`: A trait for calculating the total encoded length of an MQTT packet,
8//!   including the fixed header and payload.
9
10use crate::protocol::util;
11use crate::Error;
12use bytes::BytesMut;
13
14/// A trait for encoding MQTT packets into a buffer.
15///
16/// Types that implement this trait can be serialized into a `BytesMut` buffer for
17/// transmission over the network.
18pub trait Encode {
19    /// Encodes the packet into the provided buffer.
20    ///
21    /// # Examples
22    ///
23    /// ```rust
24    /// use mqute_codec::codec::{Encode, Encoded};
25    /// use bytes::BytesMut;
26    /// use mqute_codec::Error;
27    ///
28    /// struct Packet {
29    ///     payload: Vec<u8>,
30    /// }
31    ///
32    /// impl Encode for Packet {
33    ///     fn encode(&self, buf: &mut BytesMut) -> Result<(), Error> {
34    ///         buf.extend_from_slice(&self.payload);
35    ///         Ok(())
36    ///     }
37    ///
38    ///     fn payload_len(&self) -> usize {
39    ///         self.payload.len()
40    ///     }
41    /// }
42    ///
43    /// let packet = Packet { payload: vec![0x30, 0x00] };
44    /// let mut buffer = BytesMut::new();
45    /// packet.encode(&mut buffer).unwrap();
46    /// assert_eq!(buffer.to_vec(), vec![0x30, 0x00]);
47    /// ```
48    fn encode(&self, buf: &mut BytesMut) -> Result<(), Error>;
49
50    /// Returns the length of the payload in bytes.
51    ///
52    /// # Examples
53    ///
54    /// ```rust
55    /// use mqute_codec::codec::{Encode, Encoded};
56    /// use bytes::BytesMut;
57    /// use mqute_codec::Error;
58    ///
59    /// struct Packet {
60    ///     payload: Vec<u8>,
61    /// }
62    ///
63    /// impl Encode for Packet {
64    ///     fn encode(&self, buf: &mut BytesMut) -> Result<(), Error> {
65    ///         buf.extend_from_slice(&self.payload);
66    ///         Ok(())
67    ///     }
68    ///
69    ///     fn payload_len(&self) -> usize {
70    ///         self.payload.len()
71    ///     }
72    /// }
73    ///
74    /// let packet = Packet { payload: vec![0x00, 0x01] };
75    /// assert_eq!(packet.payload_len(), 2);
76    /// ```
77    fn payload_len(&self) -> usize;
78}
79
80/// A trait for calculating the total encoded length of an MQTT packet.
81///
82/// This trait is automatically implemented for all types that implement `Encode`.
83///
84/// # Examples
85///
86/// ```rust
87/// use mqute_codec::codec::{Encode, Encoded};
88/// use bytes::BytesMut;
89/// use mqute_codec::Error;
90///
91/// struct Packet {
92///     payload: Vec<u8>,
93/// }
94///
95/// impl Encode for Packet {
96///     fn encode(&self, buf: &mut BytesMut) -> Result<(), Error> {
97///         buf.extend_from_slice(&self.payload);
98///         Ok(())
99///     }
100///
101///     fn payload_len(&self) -> usize {
102///         self.payload.len()
103///     }
104/// }
105///
106/// let packet = Packet { payload: vec![0x00, 0x01] };
107/// assert_eq!(packet.encoded_len(), 4); // 1 byte for control byte, 1 byte for remaining length, 2 bytes for payload
108/// ```
109pub trait Encoded: Encode {
110    /// Calculates the total encoded length of the packet.
111    ///
112    /// The total length includes:
113    /// - 1 byte for the control byte.
114    /// - Variable bytes for the remaining length (encoded as a variable byte integer).
115    /// - The length of the payload.
116    fn encoded_len(&self) -> usize;
117}
118
119impl<T> Encoded for T
120where
121    T: Encode,
122{
123    fn encoded_len(&self) -> usize {
124        let len = self.payload_len();
125        1 + util::len_bytes(len) + len
126    }
127}