1use std::convert::TryFrom;
12use std::convert::TryInto;
13
14#[derive(Clone, Debug, PartialEq)]
16pub struct PingPacket {
17 pub id: u64,
22}
23
24#[derive(Clone, Debug, PartialEq)]
26pub struct PongPacket {
27 pub id: u64,
31
32 pub version: u32,
34
35 pub users: u32,
37
38 pub max_users: u32,
40
41 pub bandwidth: u32,
43}
44
45#[derive(Clone, Debug, PartialEq)]
47pub enum ParsePingError {
48 InvalidSize,
50 InvalidHeader,
52}
53
54impl TryFrom<&[u8]> for PingPacket {
55 type Error = ParsePingError;
56 fn try_from(buf: &[u8]) -> Result<Self, Self::Error> {
57 match <[u8; 12]>::try_from(buf) {
58 Ok(array) => {
59 if array[0..4] != [0, 0, 0, 0] {
60 Err(ParsePingError::InvalidHeader)
61 } else {
62 Ok(Self {
63 id: u64::from_be_bytes(array[4..12].try_into().unwrap()),
64 })
65 }
66 }
67 Err(_) => Err(ParsePingError::InvalidSize),
68 }
69 }
70}
71
72impl From<PingPacket> for [u8; 12] {
73 fn from(packet: PingPacket) -> Self {
74 let id = packet.id.to_be_bytes();
75 [
77 0, 0, 0, 0, id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7],
78 ]
79 }
80}
81
82#[derive(Clone, Debug, PartialEq)]
84pub enum ParsePongError {
85 InvalidSize,
87}
88
89impl TryFrom<&[u8]> for PongPacket {
90 type Error = ParsePongError;
91 fn try_from(buf: &[u8]) -> Result<Self, Self::Error> {
92 match <[u8; 24]>::try_from(buf) {
93 Ok(array) => Ok(Self {
94 version: u32::from_be_bytes(array[0..4].try_into().unwrap()),
95 id: u64::from_be_bytes(array[4..12].try_into().unwrap()),
96 users: u32::from_be_bytes(array[12..16].try_into().unwrap()),
97 max_users: u32::from_be_bytes(array[16..20].try_into().unwrap()),
98 bandwidth: u32::from_be_bytes(array[20..24].try_into().unwrap()),
99 }),
100 Err(_) => Err(ParsePongError::InvalidSize),
101 }
102 }
103}
104
105impl From<PongPacket> for [u8; 24] {
106 fn from(packet: PongPacket) -> Self {
107 let version = packet.version.to_be_bytes();
108 let id = packet.id.to_be_bytes();
109 let users = packet.users.to_be_bytes();
110 let max_users = packet.max_users.to_be_bytes();
111 let bandwidth = packet.bandwidth.to_be_bytes();
112 [
114 version[0],
115 version[1],
116 version[2],
117 version[3],
118 id[0],
119 id[1],
120 id[2],
121 id[3],
122 id[4],
123 id[5],
124 id[6],
125 id[7],
126 users[0],
127 users[1],
128 users[2],
129 users[3],
130 max_users[0],
131 max_users[1],
132 max_users[2],
133 max_users[3],
134 bandwidth[0],
135 bandwidth[1],
136 bandwidth[2],
137 bandwidth[3],
138 ]
139 }
140}