nex_packet/
packet.rs

1use bytes::{Bytes, BytesMut};
2
3/// Represents a generic network packet.
4pub trait Packet: Sized {
5    type Header;
6
7    /// Parse from a byte slice.
8    fn from_buf(buf: &[u8]) -> Option<Self>;
9
10    /// Parse from raw bytes. (with ownership)
11    fn from_bytes(bytes: Bytes) -> Option<Self>;
12
13    /// Serialize into raw bytes.
14    fn to_bytes(&self) -> Bytes;
15
16    /// Get the header of the packet.
17    fn header(&self) -> Bytes;
18
19    /// Get the payload of the packet.
20    fn payload(&self) -> Bytes;
21
22    /// Get the length of the header.
23    fn header_len(&self) -> usize;
24
25    /// Get the length of the payload.
26    fn payload_len(&self) -> usize;
27    /// Get the total length of the packet (header + payload).
28    fn total_len(&self) -> usize;
29    /// Convert the packet to a mutable byte buffer.
30    fn to_bytes_mut(&self) -> BytesMut {
31        let mut buf = BytesMut::with_capacity(self.total_len());
32        buf.extend_from_slice(&self.to_bytes());
33        buf
34    }
35    /// Get a mutable byte buffer for the header.
36    fn header_mut(&self) -> BytesMut {
37        let mut buf = BytesMut::with_capacity(self.header_len());
38        buf.extend_from_slice(&self.header());
39        buf
40    }
41    /// Get a mutable byte buffer for the payload.
42    fn payload_mut(&self) -> BytesMut {
43        let mut buf = BytesMut::with_capacity(self.payload_len());
44        buf.extend_from_slice(&self.payload());
45        buf
46    }
47
48    fn into_parts(self) -> (Self::Header, Bytes);
49}