socketio_next/protocol/
payload.rs1use bytes::Bytes;
2use serde::Serialize;
3use serde::de::DeserializeOwned;
4use serde_json::Value;
5
6#[derive(Debug, PartialEq, Eq, Clone)]
18#[non_exhaustive]
19pub enum Payload {
20 Binary(Bytes),
22 Text(Vec<Value>),
24 Mixed {
28 args: Vec<Value>,
30 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 pub fn placeholder(num: usize) -> Value {
44 crate::protocol::socketio::placeholder(num)
45 }
46
47 pub fn empty() -> Self {
49 Payload::default()
50 }
51
52 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 pub fn args(&self) -> &[Value] {
60 match self {
61 Payload::Text(args) | Payload::Mixed { args, .. } => args,
62 Payload::Binary(_) => &[],
63 }
64 }
65
66 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 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 pub fn is_empty(&self) -> bool {
86 self.len() == 0
87 }
88
89 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 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 fn from(string: &str) -> Self {
104 Payload::Text(vec![Value::String(string.to_owned())])
105 }
106}
107
108impl From<String> for Payload {
109 fn from(string: String) -> Self {
111 Payload::Text(vec![Value::String(string)])
112 }
113}
114
115impl From<Vec<Value>> for Payload {
116 fn from(values: Vec<Value>) -> Self {
118 Payload::Text(values)
119 }
120}
121
122impl From<Value> for Payload {
123 fn from(value: Value) -> Self {
125 Payload::Text(vec![value])
126 }
127}
128
129impl From<()> for Payload {
130 fn from(_: ()) -> Self {
132 Payload::default()
133 }
134}
135
136macro_rules! from_scalar {
137 ($($t:ty),*) => {$(
138 impl From<$t> for Payload {
139 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 fn from(val: Vec<u8>) -> Self {
151 Payload::Binary(Bytes::from(val))
152 }
153}
154
155impl From<&'static [u8]> for Payload {
156 fn from(val: &'static [u8]) -> Self {
158 Payload::Binary(Bytes::from_static(val))
159 }
160}
161
162impl From<Bytes> for Payload {
163 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}