engine_io_parser/
packet.rs1use bytes::Bytes;
2use std::convert::TryFrom;
3use std::error;
4use std::fmt;
5
6#[derive(Debug, Clone, Copy, PartialEq)]
7pub enum PacketType {
8 Open = 0,
9 Close = 1,
10 Ping = 2,
11 Pong = 3,
12 Message = 4,
13 Upgrade = 5,
14 Noop = 6,
15}
16
17impl Into<u8> for PacketType {
18 fn into(self) -> u8 {
19 self as u8
20 }
21}
22
23impl TryFrom<u8> for PacketType {
24 type Error = ParsePacketError;
25
26 fn try_from(value: u8) -> Result<Self, Self::Error> {
27 match value {
28 0 => Ok(PacketType::Open),
29 1 => Ok(PacketType::Close),
30 2 => Ok(PacketType::Ping),
31 3 => Ok(PacketType::Pong),
32 4 => Ok(PacketType::Message),
33 5 => Ok(PacketType::Upgrade),
34 6 => Ok(PacketType::Noop),
35 _ => Err(ParsePacketError {
36 message: "Invalid packet".to_owned(),
37 }),
38 }
39 }
40}
41
42impl PacketType {
43 pub fn parse_from_u8<T>(
44 value: u8,
45 original_input: T,
46 ) -> Result<Self, nom::Err<(T, nom::error::ErrorKind)>> {
47 match PacketType::try_from(value) {
48 Ok(packet_type) => Ok(packet_type),
49 Err(_) => Err(nom::Err::Failure((
50 original_input,
51 nom::error::ErrorKind::Digit,
52 ))),
53 }
54 }
55}
56
57#[derive(Debug, Clone, PartialEq)]
64pub enum PacketData {
65 Plaintext(String),
66 Binary(Bytes),
67 Empty,
68}
69
70#[derive(Debug, Clone, PartialEq)]
71pub struct Packet {
72 pub packet_type: PacketType,
73 pub data: PacketData,
74}
75
76#[derive(Debug, Clone, PartialEq)]
77pub struct ParsePacketError {
78 pub message: String,
79}
80
81impl error::Error for ParsePacketError {}
82
83impl fmt::Display for ParsePacketError {
84 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85 write!(f, "{}", self.message)
86 }
87}
88
89impl From<&str> for PacketData {
90 fn from(val: &str) -> Self {
91 PacketData::Plaintext(val.to_owned())
92 }
93}
94
95impl From<String> for PacketData {
96 fn from(val: String) -> Self {
97 PacketData::Plaintext(val)
98 }
99}
100
101impl From<&[u8]> for PacketData {
102 fn from(val: &[u8]) -> Self {
103 PacketData::Binary(Bytes::copy_from_slice(val))
104 }
105}
106
107impl From<Vec<u8>> for PacketData {
108 fn from(val: Vec<u8>) -> Self {
109 PacketData::Binary(Bytes::copy_from_slice(&val))
110 }
111}