Skip to main content

socketio_next/protocol/
payload.rs

1use bytes::Bytes;
2use serde::Serialize;
3use serde::de::DeserializeOwned;
4use serde_json::Value;
5
6/// The arguments of an event or an ack.
7///
8/// socket.io sends a list of arguments; each is JSON or binary. Received arguments arrive as:
9/// - [`Payload::Text`]: JSON only (the common case),
10/// - [`Payload::Binary`]: exactly one binary argument,
11/// - [`Payload::Mixed`]: binary data anywhere else (several buffers, a buffer next to JSON
12///   arguments, a buffer inside an object).
13///
14/// Build one with `From` (a [`Value`], a `Vec<Value>`, a string, bytes) or with
15/// [`Payload::serialize`] for any `Serialize` type; read one with [`Payload::arg`] /
16/// [`Payload::deserialize`].
17#[derive(Debug, PartialEq, Eq, Clone)]
18#[non_exhaustive]
19pub enum Payload {
20    /// One binary argument.
21    Binary(Bytes),
22    /// JSON arguments.
23    Text(Vec<Value>),
24    /// Arguments with binary data anywhere in them: each `{"_placeholder":true,"num":n}` in
25    /// `args` stands for `attachments[n]` (socket.io-parser binary encoding). Build placeholders
26    /// with [`Payload::placeholder`].
27    Mixed {
28        /// The JSON arguments, placeholders included.
29        args: Vec<Value>,
30        /// The binary attachments the placeholders refer to.
31        attachments: Vec<Bytes>,
32    },
33}
34
35impl Default for Payload {
36    fn default() -> Self {
37        Payload::Text(Vec::new())
38    }
39}
40
41impl Payload {
42    /// The placeholder for `attachments[num]` in [`Payload::Mixed`].
43    pub fn placeholder(num: usize) -> Value {
44        crate::protocol::socketio::placeholder(num)
45    }
46
47    /// No arguments (`socket.emit("ping")`).
48    pub fn empty() -> Self {
49        Payload::default()
50    }
51
52    /// One argument from any `Serialize` value.
53    pub fn serialize<T: Serialize + ?Sized>(value: &T) -> serde_json::Result<Self> {
54        Ok(Payload::Text(vec![serde_json::to_value(value)?]))
55    }
56
57    /// The JSON arguments (placeholders included for [`Payload::Mixed`]; empty for
58    /// [`Payload::Binary`]).
59    pub fn args(&self) -> &[Value] {
60        match self {
61            Payload::Text(args) | Payload::Mixed { args, .. } => args,
62            Payload::Binary(_) => &[],
63        }
64    }
65
66    /// The binary data: the one buffer of [`Payload::Binary`], the attachments of
67    /// [`Payload::Mixed`].
68    pub fn binary(&self) -> &[Bytes] {
69        match self {
70            Payload::Binary(bytes) => std::slice::from_ref(bytes),
71            Payload::Mixed { attachments, .. } => attachments,
72            Payload::Text(_) => &[],
73        }
74    }
75
76    /// Number of arguments.
77    pub fn len(&self) -> usize {
78        match self {
79            Payload::Binary(_) => 1,
80            Payload::Text(args) | Payload::Mixed { args, .. } => args.len(),
81        }
82    }
83
84    /// No arguments at all.
85    pub fn is_empty(&self) -> bool {
86        self.len() == 0
87    }
88
89    /// Argument `index` as `T` (`null` when it is missing, so `Option<T>` reads optional ones).
90    pub fn arg<T: DeserializeOwned>(&self, index: usize) -> serde_json::Result<T> {
91        T::deserialize(self.args().get(index).unwrap_or(&Value::Null))
92    }
93
94    /// All arguments as `T`: a tuple `(A, B)`, a `Vec<_>`, or a struct with one field per
95    /// argument position.
96    pub fn deserialize<T: DeserializeOwned>(&self) -> serde_json::Result<T> {
97        T::deserialize(Value::Array(self.args().to_vec()))
98    }
99}
100
101impl From<&str> for Payload {
102    /// One string argument.
103    fn from(string: &str) -> Self {
104        Payload::Text(vec![Value::String(string.to_owned())])
105    }
106}
107
108impl From<String> for Payload {
109    /// One string argument (never parsed as JSON).
110    fn from(string: String) -> Self {
111        Payload::Text(vec![Value::String(string)])
112    }
113}
114
115impl From<Vec<Value>> for Payload {
116    /// One argument per value.
117    fn from(values: Vec<Value>) -> Self {
118        Payload::Text(values)
119    }
120}
121
122impl From<Value> for Payload {
123    /// One argument.
124    fn from(value: Value) -> Self {
125        Payload::Text(vec![value])
126    }
127}
128
129impl From<()> for Payload {
130    /// No arguments.
131    fn from(_: ()) -> Self {
132        Payload::default()
133    }
134}
135
136macro_rules! from_scalar {
137    ($($t:ty),*) => {$(
138        impl From<$t> for Payload {
139            /// One JSON argument.
140            fn from(value: $t) -> Self {
141                Payload::Text(vec![Value::from(value)])
142            }
143        }
144    )*};
145}
146from_scalar!(bool, i8, i16, i32, i64, u8, u16, u32, u64, f32, f64);
147
148impl From<Vec<u8>> for Payload {
149    /// One binary argument.
150    fn from(val: Vec<u8>) -> Self {
151        Payload::Binary(Bytes::from(val))
152    }
153}
154
155impl From<&'static [u8]> for Payload {
156    /// One binary argument.
157    fn from(val: &'static [u8]) -> Self {
158        Payload::Binary(Bytes::from_static(val))
159    }
160}
161
162impl From<Bytes> for Payload {
163    /// One binary argument.
164    fn from(bytes: Bytes) -> Self {
165        Payload::Binary(bytes)
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use serde_json::json;
172
173    use super::*;
174
175    #[test]
176    fn strings_are_never_parsed_as_json() {
177        assert_eq!(
178            Payload::from("{\"a\":1}"),
179            Payload::Text(vec![json!("{\"a\":1}")])
180        );
181        assert_eq!(
182            Payload::from(String::from("foo ™")),
183            Payload::Text(vec![json!("foo ™")])
184        );
185    }
186
187    #[test]
188    fn conversions() {
189        assert_eq!(
190            Payload::from(json!({"a": 1})),
191            Payload::Text(vec![json!({"a": 1})])
192        );
193        assert_eq!(Payload::from(vec![json!(1), json!("x")]).len(), 2);
194        assert_eq!(Payload::from(()), Payload::empty());
195        assert!(Payload::empty().is_empty());
196        assert_eq!(
197            Payload::from(vec![1u8, 2]),
198            Payload::Binary(Bytes::from_static(&[1, 2]))
199        );
200        assert_eq!(
201            Payload::from(&[1u8][..]).binary(),
202            &[Bytes::from_static(&[1])]
203        );
204        assert_eq!(
205            Payload::serialize(&("x", 2)).unwrap(),
206            Payload::Text(vec![json!(["x", 2])])
207        );
208    }
209
210    #[test]
211    fn typed_reads() {
212        #[derive(serde::Deserialize, PartialEq, Debug)]
213        struct Data {
214            id: u32,
215        }
216        let payload = Payload::from(vec![json!({"id": 7}), json!("err")]);
217        assert_eq!(payload.arg::<Data>(0).unwrap(), Data { id: 7 });
218        assert_eq!(
219            payload.arg::<Option<String>>(1).unwrap().as_deref(),
220            Some("err")
221        );
222        assert_eq!(payload.arg::<Option<String>>(2).unwrap(), None);
223        let (data, err): (Data, String) = payload.deserialize().unwrap();
224        assert_eq!((data.id, err.as_str()), (7, "err"));
225        assert!(payload.arg::<u32>(1).is_err());
226    }
227}