wsio_core/packet/
mod.rs

1use serde::{
2    Deserialize,
3    Serialize,
4};
5use serde_repr::{
6    Deserialize_repr,
7    Serialize_repr,
8};
9use serde_with::skip_serializing_none;
10
11pub mod codecs;
12
13// Enums
14#[repr(u8)]
15#[derive(Clone, Debug, Deserialize_repr, Serialize_repr)]
16pub enum WsIoPacketType {
17    Auth = 0,
18    Disconnect = 1,
19    Event = 2,
20    Init = 3,
21    Ready = 4,
22}
23
24// Structs
25#[cfg(any(
26    feature = "packet-codec-bincode",
27    feature = "packet-codec-msgpack",
28    feature = "packet-codec-postcard"
29))]
30#[derive(Deserialize)]
31struct InnerPacket(Option<Vec<u8>>, Option<String>, WsIoPacketType);
32
33#[cfg(any(
34    feature = "packet-codec-bincode",
35    feature = "packet-codec-msgpack",
36    feature = "packet-codec-postcard"
37))]
38#[derive(Serialize)]
39struct InnerPacketRef<'a>(&'a Option<Vec<u8>>, &'a Option<String>, &'a WsIoPacketType);
40
41#[skip_serializing_none]
42#[derive(Clone, Debug, Deserialize, Serialize)]
43pub struct WsIoPacket {
44    #[serde(rename = "d")]
45    pub data: Option<Vec<u8>>,
46
47    #[serde(rename = "k")]
48    pub key: Option<String>,
49
50    #[serde(rename = "t")]
51    pub r#type: WsIoPacketType,
52}
53
54impl WsIoPacket {
55    #[inline]
56    pub fn new(r#type: WsIoPacketType, key: Option<&str>, data: Option<Vec<u8>>) -> Self {
57        Self {
58            data,
59            key: key.map(|k| k.to_string()),
60            r#type,
61        }
62    }
63
64    // Public methods
65    #[inline]
66    pub fn new_auth(data: Option<Vec<u8>>) -> Self {
67        Self::new(WsIoPacketType::Auth, None, data)
68    }
69
70    #[inline]
71    pub fn new_disconnect() -> Self {
72        Self::new(WsIoPacketType::Disconnect, None, None)
73    }
74
75    #[inline]
76    pub fn new_event(event: &str, data: Option<Vec<u8>>) -> Self {
77        Self::new(WsIoPacketType::Event, Some(event), data)
78    }
79
80    #[inline]
81    pub fn new_init(data: Vec<u8>) -> Self {
82        Self::new(WsIoPacketType::Init, None, Some(data))
83    }
84
85    #[inline]
86    pub fn new_ready() -> Self {
87        Self::new(WsIoPacketType::Ready, None, None)
88    }
89}