serde_resp/
ser.rs

1use serde::{ser, Serialize};
2
3use crate::{Error, RESPType, Result};
4use serde::ser::SerializeSeq;
5use std::io::Write;
6use std::result;
7
8/// Serializer for RESP format
9pub struct Serializer<W: Write> {
10    writer: W,
11}
12
13/// Serialize to string.
14///
15/// Please do not use this method with [RESPType::BulkString](RESPType::BulkString) that contains non-UTF8 data.
16///
17/// # Errors
18/// Please refer to [Error](Error)
19pub fn to_string<T>(value: &T) -> Result<String>
20where
21    T: Serialize,
22{
23    let mut buf: Vec<u8> = Vec::new();
24    to_writer(value, &mut buf)?;
25    Ok(String::from_utf8(buf)?)
26}
27
28/// Serialize to writer with `Write` trait.
29///
30/// # Errors
31/// Please refer to [Error](Error)
32pub fn to_writer<T, W>(value: &T, writer: &mut W) -> Result<()>
33where
34    T: Serialize,
35    W: Write,
36{
37    let mut serializer = Serializer { writer };
38    value.serialize(&mut serializer)?;
39    Ok(())
40}
41
42impl<'a, W> ser::Serializer for &'a mut Serializer<W>
43where
44    W: Write,
45{
46    type Ok = ();
47    type Error = Error;
48    type SerializeSeq = Self;
49    type SerializeTuple = Self;
50    type SerializeTupleStruct = Self;
51    type SerializeTupleVariant = Self;
52    type SerializeMap = Self;
53    type SerializeStruct = Self;
54    type SerializeStructVariant = Self;
55
56    fn serialize_bool(self, _v: bool) -> Result<()> {
57        unimplemented!()
58    }
59
60    fn serialize_i8(self, _v: i8) -> Result<()> {
61        unimplemented!()
62    }
63
64    fn serialize_i16(self, _v: i16) -> Result<()> {
65        unimplemented!()
66    }
67
68    fn serialize_i32(self, _v: i32) -> Result<()> {
69        unimplemented!()
70    }
71
72    fn serialize_i64(self, v: i64) -> Result<()> {
73        self.writer.write_all(b":")?;
74        itoa::write(&mut self.writer, v)?;
75        self.writer.write_all(b"\r\n")?;
76        Ok(())
77    }
78
79    fn serialize_u8(self, _v: u8) -> Result<()> {
80        unimplemented!()
81    }
82
83    fn serialize_u16(self, _v: u16) -> Result<()> {
84        unimplemented!()
85    }
86
87    fn serialize_u32(self, _v: u32) -> Result<()> {
88        unimplemented!()
89    }
90
91    fn serialize_u64(self, _v: u64) -> Result<()> {
92        unimplemented!()
93    }
94
95    fn serialize_f32(self, _v: f32) -> Result<()> {
96        unimplemented!()
97    }
98
99    fn serialize_f64(self, _v: f64) -> Result<()> {
100        unimplemented!()
101    }
102
103    // Serialize a char as a single-character string.
104    fn serialize_char(self, v: char) -> Result<()> {
105        self.serialize_str(&v.to_string())
106    }
107
108    // Used by `RESPType::SimpleString` and `RESPType::Error`. Do not use directly!
109    fn serialize_str(self, v: &str) -> Result<()> {
110        self.writer.write_all(v.as_bytes())?;
111        self.writer.write_all(b"\r\n")?;
112        Ok(())
113    }
114
115    // Bulk string (Not null)
116    fn serialize_bytes(self, v: &[u8]) -> Result<()> {
117        self.writer.write_all(b"$")?;
118        itoa::write(&mut self.writer, v.len() as u64)?;
119        self.writer.write_all(b"\r\n")?;
120        self.writer.write_all(v)?;
121        self.writer.write_all(b"\r\n")?;
122        Ok(())
123    }
124
125    // RESPType::BulkString::Null
126    fn serialize_none(self) -> Result<()> {
127        self.writer.write_all(b"$-1\r\n")?;
128        Ok(())
129    }
130
131    fn serialize_some<T>(self, _value: &T) -> Result<()>
132    where
133        T: ?Sized + Serialize,
134    {
135        unimplemented!()
136    }
137
138    // RESPType::Array::Null
139    fn serialize_unit(self) -> Result<()> {
140        self.writer.write_all(b"*-1\r\n")?;
141        Ok(())
142    }
143
144    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
145        unimplemented!()
146    }
147
148    fn serialize_unit_variant(
149        self,
150        _name: &'static str,
151        _variant_index: u32,
152        _variant: &'static str,
153    ) -> Result<()> {
154        unimplemented!()
155    }
156
157    fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<()>
158    where
159        T: ?Sized + Serialize,
160    {
161        unimplemented!()
162    }
163
164    fn serialize_newtype_variant<T>(
165        self,
166        _name: &'static str,
167        _variant_index: u32,
168        _variant: &'static str,
169        _value: &T,
170    ) -> Result<()>
171    where
172        T: ?Sized + Serialize,
173    {
174        unimplemented!()
175    }
176
177    // Write beginning of array
178    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
179        match len {
180            None => unimplemented!(),
181            Some(len) => {
182                self.writer.write_all(b"*")?;
183                itoa::write(&mut self.writer, len as u64)?;
184                self.writer.write_all(b"\r\n")?;
185            }
186        }
187        Ok(self)
188    }
189
190    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
191        unimplemented!()
192    }
193
194    fn serialize_tuple_struct(
195        self,
196        _name: &'static str,
197        _len: usize,
198    ) -> Result<Self::SerializeTupleStruct> {
199        unimplemented!()
200    }
201
202    fn serialize_tuple_variant(
203        self,
204        _name: &'static str,
205        _variant_index: u32,
206        _variant: &'static str,
207        _len: usize,
208    ) -> Result<Self::SerializeTupleVariant> {
209        unimplemented!()
210    }
211
212    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
213        unimplemented!()
214    }
215
216    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
217        unimplemented!()
218    }
219
220    fn serialize_struct_variant(
221        self,
222        _name: &'static str,
223        _variant_index: u32,
224        _variant: &'static str,
225        _len: usize,
226    ) -> Result<Self::SerializeStructVariant> {
227        unimplemented!()
228    }
229}
230
231// The following impls deal with the serialization of compound types like
232// sequences. Serialization of such types is begun by a Serializer
233// method and followed by zero or more calls to serialize individual elements of
234// the compound type and one call to end the compound type.
235//
236// This impl is SerializeSeq so these methods are called after `serialize_seq`
237// is called on the Serializer.
238impl<'a, W> ser::SerializeSeq for &'a mut Serializer<W>
239where
240    W: Write,
241{
242    type Ok = ();
243    type Error = Error;
244
245    // Serialize a single element of the sequence.
246    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
247    where
248        T: ?Sized + Serialize,
249    {
250        value.serialize(&mut **self)
251    }
252
253    // Close the sequence.
254    fn end(self) -> Result<()> {
255        Ok(())
256    }
257}
258
259impl<'a, W> ser::SerializeTuple for &'a mut Serializer<W>
260where
261    W: Write,
262{
263    type Ok = ();
264    type Error = Error;
265
266    fn serialize_element<T>(&mut self, _value: &T) -> Result<()>
267    where
268        T: ?Sized + Serialize,
269    {
270        unimplemented!()
271    }
272
273    fn end(self) -> Result<()> {
274        unimplemented!()
275    }
276}
277
278impl<'a, W> ser::SerializeTupleStruct for &'a mut Serializer<W>
279where
280    W: Write,
281{
282    type Ok = ();
283    type Error = Error;
284
285    fn serialize_field<T>(&mut self, _value: &T) -> Result<()>
286    where
287        T: ?Sized + Serialize,
288    {
289        unimplemented!()
290    }
291
292    fn end(self) -> Result<()> {
293        unimplemented!()
294    }
295}
296
297impl<'a, W> ser::SerializeTupleVariant for &'a mut Serializer<W>
298where
299    W: Write,
300{
301    type Ok = ();
302    type Error = Error;
303
304    fn serialize_field<T>(&mut self, _value: &T) -> Result<()>
305    where
306        T: ?Sized + Serialize,
307    {
308        unimplemented!()
309    }
310
311    fn end(self) -> Result<()> {
312        unimplemented!()
313    }
314}
315
316impl<'a, W> ser::SerializeMap for &'a mut Serializer<W>
317where
318    W: Write,
319{
320    type Ok = ();
321    type Error = Error;
322    fn serialize_key<T>(&mut self, _key: &T) -> Result<()>
323    where
324        T: ?Sized + Serialize,
325    {
326        unimplemented!()
327    }
328    fn serialize_value<T>(&mut self, _value: &T) -> Result<()>
329    where
330        T: ?Sized + Serialize,
331    {
332        unimplemented!()
333    }
334    fn end(self) -> Result<()> {
335        unimplemented!()
336    }
337}
338
339impl<'a, W> ser::SerializeStruct for &'a mut Serializer<W>
340where
341    W: Write,
342{
343    type Ok = ();
344    type Error = Error;
345    fn serialize_field<T>(&mut self, _key: &'static str, _value: &T) -> Result<()>
346    where
347        T: ?Sized + Serialize,
348    {
349        unimplemented!()
350    }
351    fn end(self) -> Result<()> {
352        unimplemented!()
353    }
354}
355
356impl<'a, W> ser::SerializeStructVariant for &'a mut Serializer<W>
357where
358    W: Write,
359{
360    type Ok = ();
361    type Error = Error;
362    fn serialize_field<T>(&mut self, _key: &'static str, _value: &T) -> Result<()>
363    where
364        T: ?Sized + Serialize,
365    {
366        unimplemented!()
367    }
368    fn end(self) -> Result<()> {
369        unimplemented!()
370    }
371}
372
373// Implement serialization for RESPType
374impl serde::Serialize for RESPType {
375    fn serialize<S>(
376        &self,
377        s: S,
378    ) -> result::Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>
379    where
380        S: serde::Serializer,
381    {
382        match self {
383            RESPType::SimpleString(str) => s.serialize_str(&("+".to_owned() + str)),
384            RESPType::Error(str) => s.serialize_str(&("-".to_owned() + str)),
385            RESPType::Integer(i) => s.serialize_i64(*i),
386            RESPType::BulkString(bulk_str) => match bulk_str {
387                None => s.serialize_none(),
388                Some(val) => s.serialize_bytes(val),
389            },
390            RESPType::Array(arr) => match arr {
391                None => s.serialize_unit(),
392                Some(vals) => {
393                    let mut s = s.serialize_seq(Some(vals.len()))?;
394                    for v in vals {
395                        s.serialize_element(v)?;
396                    }
397                    s.end()
398                }
399            },
400        }
401    }
402}