mqute_codec/protocol/v4/
pubrel.rs1use super::util;
8use crate::Error;
9use crate::codec::util::decode_word;
10use crate::codec::{Decode, Encode, RawPacket};
11use crate::protocol::{FixedHeader, Flags, PacketType, QoS, traits};
12use bytes::BufMut;
13
14util::id_packet!(PubRel);
16
17impl Encode for PubRel {
18 fn encode(&self, buf: &mut bytes::BytesMut) -> Result<(), Error> {
20 let header = FixedHeader::with_flags(
21 PacketType::PubRel,
22 Flags::new(QoS::AtLeastOnce),
23 self.payload_len(),
24 );
25 header.encode(buf)?;
26
27 buf.put_u16(self.packet_id);
28 Ok(())
29 }
30
31 fn payload_len(&self) -> usize {
33 2
34 }
35}
36
37impl Decode for PubRel {
38 fn decode(mut packet: RawPacket) -> Result<Self, Error> {
40 if packet.header.packet_type() != PacketType::PubRel
41 || packet.header.flags() != Flags::new(QoS::AtLeastOnce)
42 {
43 return Err(Error::MalformedPacket);
44 }
45 let packet_id = decode_word(&mut packet.payload)?;
46 Ok(PubRel::new(packet_id))
47 }
48}
49
50impl traits::PubRel for PubRel {}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55 use crate::codec::PacketCodec;
56 use crate::codec::{Decode, Encode};
57 use bytes::BytesMut;
58 use tokio_util::codec::Decoder;
59
60 #[test]
61 fn pubrel_decode() {
62 let mut codec = PacketCodec::new(None, None);
63
64 let data = &[
65 (PacketType::PubRel as u8) << 4 | 0b0010, 0x02, 0x12, 0x34,
69 ];
70
71 let mut stream = BytesMut::new();
72
73 stream.extend_from_slice(&data[..]);
74
75 let raw_packet = codec.decode(&mut stream).unwrap().unwrap();
76 let packet = PubRel::decode(raw_packet).unwrap();
77
78 assert_eq!(packet, PubRel::new(0x1234));
79 }
80
81 #[test]
82 fn pubrel_encode() {
83 let packet = PubRel::new(0x1234);
84
85 let mut stream = BytesMut::new();
86 packet.encode(&mut stream).unwrap();
87 assert_eq!(
88 stream,
89 vec![(PacketType::PubRel as u8) << 4 | 0b0010, 0x02, 0x12, 0x34]
90 );
91 }
92}