mqtt_codec_kit/common/
packet.rs1use std::{
2 error::Error,
3 io::{self, Read, Write},
4};
5
6use super::Encodable;
7
8pub trait EncodablePacket {
13 type Output: Encodable;
14 fn fixed_header(&self) -> &Self::Output;
16
17 fn encode_packet<W: Write>(&self, _writer: &mut W) -> io::Result<()> {
19 Ok(())
20 }
21
22 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 fn decode_packet<R: Read>(reader: &mut R, fixed_header: Self::F) -> Result<Self, Self::Error>;
46}