mqtt_codec_kit/common/
packet.rs

1use std::{
2    error::Error,
3    io::{self, Read, Write},
4};
5
6use super::Encodable;
7
8/// A trait representing a packet that can be encoded, when passed as `FooPacket` or as
9/// `&FooPacket`. Different from [`Encodable`] in that it prevents you from accidentally passing
10/// a type intended to be encoded only as a part of a packet and doesn't have a header, e.g.
11/// `Vec<u8>`.
12pub trait EncodablePacket {
13    type Output: Encodable;
14    /// Get a reference to `FixedHeader`. All MQTT packet must have a fixed header.
15    fn fixed_header(&self) -> &Self::Output;
16
17    /// Encodes packet data after fixed header, including variable headers and payload
18    fn encode_packet<W: Write>(&self, _writer: &mut W) -> io::Result<()> {
19        Ok(())
20    }
21
22    /// Length in bytes for data after fixed header, including variable headers and payload
23    fn encoded_packet_length(&self) -> u32 {
24        0
25    }
26}
27
28impl<T: EncodablePacket> Encodable for T {
29    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
30        self.fixed_header().encode(writer)?;
31        self.encode_packet(writer)
32    }
33
34    fn encoded_length(&self) -> u32 {
35        self.fixed_header().encoded_length() + self.encoded_packet_length()
36    }
37}
38
39pub trait DecodablePacket: EncodablePacket + Sized {
40    type DecodePacketError: Error + 'static;
41    type F;
42    type Error;
43
44    /// Decode packet given a `FixedHeader`
45    fn decode_packet<R: Read>(reader: &mut R, fixed_header: Self::F) -> Result<Self, Self::Error>;
46}