mqute_codec/protocol/v4/
puback.rs

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