hebo_codec/v3/
unsubscribe_ack.rs

1// Copyright (c) 2020 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
2// Use of this source is governed by Apache-2.0 License that can be found
3// in the LICENSE file.
4
5use crate::{
6    ByteArray, DecodeError, DecodePacket, EncodeError, EncodePacket, FixedHeader, Packet, PacketId,
7    PacketType, VarIntError,
8};
9
10/// `UnsubscribeAck` packet is sent by the Server to the Client to confirm receipt of an
11/// unsubscribe packet.
12///
13/// Basic struct of packet:
14/// ```txt
15///  7                       0
16/// +-------------------------+
17/// | Fixed header            |
18/// |                         |
19/// +-------------------------+
20/// | Packet id               |
21/// |                         |
22/// +-------------------------+
23/// ```
24///
25/// Note that this packet does not contain payload message.
26#[allow(clippy::module_name_repetitions)]
27#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
28pub struct UnsubscribeAckPacket {
29    /// `packet_id` field is read from Unsubscribe packet.
30    packet_id: PacketId,
31}
32
33impl UnsubscribeAckPacket {
34    /// Create a new unsubscribe ack packet with `packet_id`.
35    #[must_use]
36    pub const fn new(packet_id: PacketId) -> Self {
37        Self { packet_id }
38    }
39
40    /// Get packet id.
41    #[must_use]
42    pub const fn packet_id(&self) -> PacketId {
43        self.packet_id
44    }
45}
46
47impl DecodePacket for UnsubscribeAckPacket {
48    fn decode(ba: &mut ByteArray) -> Result<Self, DecodeError> {
49        let fixed_header = FixedHeader::decode(ba)?;
50        if fixed_header.packet_type() != PacketType::UnsubscribeAck {
51            Err(DecodeError::InvalidPacketType)
52        } else if fixed_header.remaining_length() != PacketId::bytes() {
53            Err(DecodeError::InvalidRemainingLength)
54        } else {
55            let packet_id = PacketId::decode(ba)?;
56            Ok(Self { packet_id })
57        }
58    }
59}
60
61impl EncodePacket for UnsubscribeAckPacket {
62    fn encode(&self, buf: &mut Vec<u8>) -> Result<usize, EncodeError> {
63        let old_len = buf.len();
64
65        let fixed_header = FixedHeader::new(PacketType::UnsubscribeAck, PacketId::bytes())?;
66        fixed_header.encode(buf)?;
67        self.packet_id.encode(buf)?;
68        Ok(buf.len() - old_len)
69    }
70}
71
72impl Packet for UnsubscribeAckPacket {
73    fn packet_type(&self) -> PacketType {
74        PacketType::UnsubscribeAck
75    }
76
77    fn bytes(&self) -> Result<usize, VarIntError> {
78        let fixed_header = FixedHeader::new(PacketType::UnsubscribeAck, PacketId::bytes())?;
79        Ok(fixed_header.bytes() + PacketId::bytes())
80    }
81}