mqute_codec/protocol/v4/
pubrec.rs

1//! # PubRec Packet V4
2//!
3//! This module defines the `PubRec` packet, which is used in the MQTT protocol to acknowledge
4//! the receipt of a `Publish` packet with QoS level 2. The `PubRec` packet contains a packet ID
5//! to match it with the corresponding `Publish` packet.
6
7use super::util;
8use crate::protocol::{PacketType, traits};
9
10// Defines the `PubRec` packet for MQTT V4
11util::id_packet!(PubRec);
12
13// Implement the `Decode` trait for `PubRec`.
14util::id_packet_decode_impl!(PubRec, PacketType::PubRec);
15
16// Implement the `Encode` trait for `PubRec`.
17util::id_packet_encode_impl!(PubRec, PacketType::PubRec);
18
19impl traits::PubRec for PubRec {}
20
21#[cfg(test)]
22mod tests {
23    use super::*;
24    use crate::codec::PacketCodec;
25    use crate::codec::{Decode, Encode};
26    use bytes::BytesMut;
27    use tokio_util::codec::Decoder;
28
29    #[test]
30    fn pubrec_decode() {
31        let mut codec = PacketCodec::new(None, None);
32
33        let data = &[
34            (PacketType::PubRec as u8) << 4, // Packet type
35            0x02,                            // Remaining len
36            0x12,                            // Packet ID
37            0x34,
38        ];
39
40        let mut stream = BytesMut::new();
41
42        stream.extend_from_slice(&data[..]);
43
44        let raw_packet = codec.decode(&mut stream).unwrap().unwrap();
45        let packet = PubRec::decode(raw_packet).unwrap();
46
47        assert_eq!(packet, PubRec::new(0x1234));
48    }
49
50    #[test]
51    fn pubrec_encode() {
52        let packet = PubRec::new(0x1234);
53
54        let mut stream = BytesMut::new();
55        packet.encode(&mut stream).unwrap();
56        assert_eq!(
57            stream,
58            vec![(PacketType::PubRec as u8) << 4, 0x02, 0x12, 0x34]
59        );
60    }
61}