hebo_codec/v3/
ping_request.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,
7    PacketType, VarIntError,
8};
9
10/// The `PingRequest` packet is sent to the Server from a Client. It is used to:
11/// 1. Notify the Server that this Client is still alive.
12/// 2. To check if the Server is alive.
13/// 3. To check the network connection is ok.
14///
15/// This packet does not contain variable header or payload.
16#[allow(clippy::module_name_repetitions)]
17#[derive(Clone, Debug, Default, PartialEq, Eq)]
18pub struct PingRequestPacket();
19
20impl PingRequestPacket {
21    #[must_use]
22    pub const fn new() -> Self {
23        Self()
24    }
25}
26
27impl EncodePacket for PingRequestPacket {
28    fn encode(&self, v: &mut Vec<u8>) -> Result<usize, EncodeError> {
29        // Payload is empty
30        let fixed_header = FixedHeader::new(PacketType::PingRequest, 0)?;
31        fixed_header.encode(v)
32    }
33}
34
35impl DecodePacket for PingRequestPacket {
36    fn decode(ba: &mut ByteArray) -> Result<Self, DecodeError> {
37        let fixed_header = FixedHeader::decode(ba)?;
38        if fixed_header.packet_type() != PacketType::PingRequest {
39            Err(DecodeError::InvalidPacketType)
40        } else if fixed_header.remaining_length() != 0 {
41            Err(DecodeError::InvalidRemainingLength)
42        } else {
43            Ok(Self())
44        }
45    }
46}
47
48impl Packet for PingRequestPacket {
49    fn packet_type(&self) -> PacketType {
50        PacketType::PingRequest
51    }
52
53    fn bytes(&self) -> Result<usize, VarIntError> {
54        let fixed_header = FixedHeader::new(PacketType::PingRequest, 0)?;
55        Ok(fixed_header.bytes())
56    }
57}