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