redis_serde/
encode.rs

1use redis::Value;
2use serde::{self, Serialize, ser};
3use std::fmt::{self, Display};
4use std::{error, str};
5
6pub struct Serializer;
7
8/// Error that can be produced during serialization
9#[derive(Debug)]
10pub enum Error {
11    Custom(String),
12}
13
14impl Error {}
15
16pub type Result<T> = ::std::result::Result<T, Error>;
17
18impl error::Error for Error {
19    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
20        None
21    }
22}
23
24impl fmt::Display for Error {
25    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
26        match *self {
27            Error::Custom(ref reason) => write!(f, "CustomError({})", reason),
28        }
29    }
30}
31
32impl ser::Error for Error {
33    fn custom<T: Display>(msg: T) -> Self {
34        Error::Custom(msg.to_string())
35    }
36}
37
38macro_rules! impl_num {
39    ($ty:ty, $serialize_method:ident) => {
40        #[inline]
41        fn $serialize_method(self, v: $ty) -> Result<Value> {
42            Ok(Value::BulkString(v.to_string().as_bytes().to_vec()))
43        }
44    };
45}
46
47impl serde::Serializer for Serializer {
48    type Ok = Value;
49    type Error = Error;
50
51    type SerializeSeq = SerializeVec;
52    type SerializeTuple = SerializeVec;
53    type SerializeTupleStruct = SerializeVec;
54    type SerializeTupleVariant = SerializeVec;
55    type SerializeMap = SerializeVec;
56    type SerializeStruct = SerializeVec;
57    type SerializeStructVariant = SerializeVec;
58
59    impl_num!(u8, serialize_u8);
60    impl_num!(u16, serialize_u16);
61    impl_num!(u32, serialize_u32);
62    impl_num!(u64, serialize_u64);
63
64    impl_num!(i8, serialize_i8);
65    impl_num!(i16, serialize_i16);
66    impl_num!(i32, serialize_i32);
67    impl_num!(i64, serialize_i64);
68
69    impl_num!(f32, serialize_f32);
70    impl_num!(f64, serialize_f64);
71
72    fn serialize_bool(self, v: bool) -> Result<Value> {
73        match v {
74            true => self.serialize_i32(1),
75            false => self.serialize_i32(0),
76        }
77    }
78
79    fn serialize_char(self, v: char) -> Result<Value> {
80        let mut buf = Vec::with_capacity(v.len_utf8());
81        v.encode_utf8(&mut buf);
82
83        Ok(Value::BulkString(buf))
84    }
85
86    fn serialize_str(self, v: &str) -> Result<Value> {
87        Ok(Value::BulkString(v.as_bytes().to_vec()))
88    }
89
90    fn serialize_bytes(self, v: &[u8]) -> Result<Value> {
91        Ok(Value::BulkString(v.to_vec()))
92    }
93
94    fn serialize_none(self) -> Result<Value> {
95        Ok(Value::Nil)
96    }
97
98    fn serialize_some<T>(self, v: &T) -> Result<Value>
99    where
100        T: ?Sized + Serialize,
101    {
102        v.serialize(self)
103    }
104
105    fn serialize_unit(self) -> Result<Value> {
106        Ok(Value::Nil)
107    }
108
109    fn serialize_unit_struct(self, _name: &'static str) -> Result<Value> {
110        self.serialize_unit()
111    }
112
113    fn serialize_unit_variant(
114        self,
115        _name: &'static str,
116        _variant_index: u32,
117        variant: &'static str,
118    ) -> Result<Value> {
119        self.serialize_str(variant)
120    }
121
122    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Value>
123    where
124        T: ?Sized + Serialize,
125    {
126        value.serialize(self)
127    }
128
129    fn serialize_newtype_variant<T>(
130        self,
131        _name: &'static str,
132        _variant_index: u32,
133        _variant: &'static str,
134        value: &T,
135    ) -> Result<Value>
136    where
137        T: ?Sized + Serialize,
138    {
139        value.serialize(self)
140    }
141
142    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
143        Ok(SerializeVec {
144            vec: Vec::with_capacity(len.unwrap_or(0)),
145        })
146    }
147
148    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
149        Ok(SerializeVec {
150            vec: Vec::with_capacity(len),
151        })
152    }
153
154    fn serialize_tuple_struct(
155        self,
156        _name: &'static str,
157        len: usize,
158    ) -> Result<Self::SerializeTupleStruct> {
159        Ok(SerializeVec {
160            vec: Vec::with_capacity(len),
161        })
162    }
163
164    fn serialize_tuple_variant(
165        self,
166        _name: &'static str,
167        _variant_index: u32,
168        _variant: &'static str,
169        len: usize,
170    ) -> Result<Self::SerializeTupleVariant> {
171        Ok(SerializeVec {
172            vec: Vec::with_capacity(len),
173        })
174    }
175
176    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
177        Ok(SerializeVec {
178            vec: Vec::with_capacity(len.unwrap_or(0)),
179        })
180    }
181
182    fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
183        Ok(SerializeVec {
184            vec: Vec::with_capacity(len * 2), // Make enough room for keys and values
185        })
186    }
187
188    fn serialize_struct_variant(
189        self,
190        _name: &'static str,
191        _variant_index: u32,
192        _variant: &'static str,
193        len: usize,
194    ) -> Result<Self::SerializeStructVariant> {
195        Ok(SerializeVec {
196            vec: Vec::with_capacity(len * 2), // Make enough room for keys and values
197        })
198    }
199}
200
201pub struct SerializeVec {
202    vec: Vec<Value>,
203}
204
205impl SerializeVec {
206    fn to_value(&self) -> Value {
207        let buffer = self.vec.to_owned();
208        Value::Array(buffer)
209    }
210}
211
212impl ser::SerializeSeq for SerializeVec {
213    type Ok = Value;
214    type Error = Error;
215
216    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
217    where
218        T: ?Sized + Serialize,
219    {
220        let v = value.serialize(Serializer)?;
221        self.vec.push(v);
222        Ok(())
223    }
224
225    fn end(self) -> Result<Value> {
226        Ok(self.to_value())
227    }
228}
229
230impl ser::SerializeTuple for SerializeVec {
231    type Ok = Value;
232    type Error = Error;
233
234    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
235    where
236        T: ?Sized + Serialize,
237    {
238        let v = value.serialize(Serializer)?;
239        self.vec.push(v);
240        Ok(())
241    }
242
243    fn end(self) -> Result<Value> {
244        Ok(self.to_value())
245    }
246}
247
248impl ser::SerializeTupleStruct for SerializeVec {
249    type Ok = Value;
250    type Error = Error;
251
252    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
253    where
254        T: ?Sized + Serialize,
255    {
256        let v = value.serialize(Serializer)?;
257        self.vec.push(v);
258        Ok(())
259    }
260
261    fn end(self) -> Result<Value> {
262        Ok(self.to_value())
263    }
264}
265
266impl ser::SerializeTupleVariant for SerializeVec {
267    type Ok = Value;
268    type Error = Error;
269
270    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
271    where
272        T: ?Sized + Serialize,
273    {
274        let v = value.serialize(Serializer)?;
275        self.vec.push(v);
276        Ok(())
277    }
278
279    fn end(self) -> Result<Value> {
280        Ok(self.to_value())
281    }
282}
283
284impl ser::SerializeMap for SerializeVec {
285    type Ok = Value;
286    type Error = Error;
287
288    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
289    where
290        T: ?Sized + Serialize,
291    {
292        let v = key.serialize(Serializer)?;
293        self.vec.push(v);
294        Ok(())
295    }
296
297    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
298    where
299        T: ?Sized + Serialize,
300    {
301        let v = value.serialize(Serializer)?;
302        self.vec.push(v);
303        Ok(())
304    }
305
306    fn end(self) -> Result<Value> {
307        Ok(self.to_value())
308    }
309}
310
311impl ser::SerializeStruct for SerializeVec {
312    type Ok = Value;
313    type Error = Error;
314
315    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
316    where
317        T: ?Sized + Serialize,
318    {
319        let k = Value::BulkString(key.as_bytes().to_vec());
320        let v = value.serialize(Serializer)?;
321        self.vec.push(k);
322        self.vec.push(v);
323        Ok(())
324    }
325
326    fn end(self) -> Result<Value> {
327        Ok(self.to_value())
328    }
329}
330
331impl ser::SerializeStructVariant for SerializeVec {
332    type Ok = Value;
333    type Error = Error;
334
335    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
336    where
337        T: ?Sized + Serialize,
338    {
339        let k = Value::BulkString(key.as_bytes().to_vec());
340        let v = value.serialize(Serializer)?;
341        self.vec.push(k);
342        self.vec.push(v);
343        Ok(())
344    }
345
346    fn end(self) -> Result<Value> {
347        Ok(self.to_value())
348    }
349}