Skip to main content

multi_cbor/value/
ser.rs

1// Copyright 2017 Serde Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use std::collections::BTreeMap;
10
11use crate::error::Error;
12use serde::{self, Serialize};
13
14use crate::tags::Tagged;
15use crate::value::Value;
16
17impl serde::Serialize for Value {
18    #[inline]
19    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
20    where
21        S: serde::Serializer,
22    {
23        match *self {
24            Self::Integer(v) => serializer.serialize_i128(v),
25            Self::Bytes(ref v) => serializer.serialize_bytes(v),
26            Self::Text(ref v) => serializer.serialize_str(v),
27            Self::Array(ref v) => v.serialize(serializer),
28            Self::Map(ref v) => v.serialize(serializer),
29            Self::Tag(tag, ref v) => Tagged::new(Some(tag), v).serialize(serializer),
30            Self::Float(v) => serializer.serialize_f64(v),
31            Self::Bool(v) => serializer.serialize_bool(v),
32            Self::Null => serializer.serialize_unit(),
33            Self::__Hidden => unreachable!(),
34        }
35    }
36}
37
38struct Serializer;
39
40impl serde::Serializer for Serializer {
41    type Ok = Value;
42    type Error = Error;
43
44    type SerializeSeq = SerializeVec;
45    type SerializeTuple = SerializeVec;
46    type SerializeTupleStruct = SerializeVec;
47    type SerializeTupleVariant = SerializeTupleVariant;
48    type SerializeMap = SerializeMap;
49    type SerializeStruct = SerializeMap;
50    type SerializeStructVariant = SerializeStructVariant;
51
52    #[inline]
53    fn serialize_bool(self, value: bool) -> Result<Value, Error> {
54        Ok(Value::Bool(value))
55    }
56
57    #[inline]
58    fn serialize_i8(self, value: i8) -> Result<Value, Error> {
59        self.serialize_i64(i64::from(value))
60    }
61
62    #[inline]
63    fn serialize_i16(self, value: i16) -> Result<Value, Error> {
64        self.serialize_i64(i64::from(value))
65    }
66
67    #[inline]
68    fn serialize_i32(self, value: i32) -> Result<Value, Error> {
69        self.serialize_i64(i64::from(value))
70    }
71
72    #[inline]
73    fn serialize_i64(self, value: i64) -> Result<Value, Error> {
74        self.serialize_i128(i128::from(value))
75    }
76
77    fn serialize_i128(self, value: i128) -> Result<Value, Error> {
78        Ok(Value::Integer(value))
79    }
80
81    #[inline]
82    fn serialize_u8(self, value: u8) -> Result<Value, Error> {
83        self.serialize_u64(u64::from(value))
84    }
85
86    #[inline]
87    fn serialize_u16(self, value: u16) -> Result<Value, Error> {
88        self.serialize_u64(u64::from(value))
89    }
90
91    #[inline]
92    fn serialize_u32(self, value: u32) -> Result<Value, Error> {
93        self.serialize_u64(u64::from(value))
94    }
95
96    #[inline]
97    fn serialize_u64(self, value: u64) -> Result<Value, Error> {
98        Ok(Value::Integer(value.into()))
99    }
100
101    #[inline]
102    fn serialize_f32(self, value: f32) -> Result<Value, Error> {
103        self.serialize_f64(f64::from(value))
104    }
105
106    #[inline]
107    fn serialize_f64(self, value: f64) -> Result<Value, Error> {
108        Ok(Value::Float(value))
109    }
110
111    #[inline]
112    fn serialize_char(self, value: char) -> Result<Value, Error> {
113        let mut s = String::new();
114        s.push(value);
115        self.serialize_str(&s)
116    }
117
118    #[inline]
119    fn serialize_str(self, value: &str) -> Result<Value, Error> {
120        Ok(Value::Text(value.to_owned()))
121    }
122
123    fn serialize_bytes(self, value: &[u8]) -> Result<Value, Error> {
124        Ok(Value::Bytes(value.to_vec()))
125    }
126
127    #[inline]
128    fn serialize_unit(self) -> Result<Value, Error> {
129        Ok(Value::Null)
130    }
131
132    #[inline]
133    fn serialize_unit_struct(self, _name: &'static str) -> Result<Value, Error> {
134        self.serialize_unit()
135    }
136
137    #[inline]
138    fn serialize_unit_variant(
139        self,
140        _name: &'static str,
141        _variant_index: u32,
142        variant: &'static str,
143    ) -> Result<Value, Error> {
144        self.serialize_str(variant)
145    }
146
147    #[inline]
148    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Value, Error>
149    where
150        T: Serialize + ?Sized,
151    {
152        value.serialize(self)
153    }
154
155    fn serialize_newtype_variant<T>(
156        self,
157        _name: &'static str,
158        _variant_index: u32,
159        variant: &'static str,
160        value: &T,
161    ) -> Result<Value, Error>
162    where
163        T: Serialize + ?Sized,
164    {
165        let mut values = BTreeMap::new();
166        values.insert(Value::from(variant.to_owned()), to_value(value)?);
167        Ok(Value::Map(values))
168    }
169
170    #[inline]
171    fn serialize_none(self) -> Result<Value, Error> {
172        self.serialize_unit()
173    }
174
175    #[inline]
176    fn serialize_some<T>(self, value: &T) -> Result<Value, Error>
177    where
178        T: Serialize + ?Sized,
179    {
180        value.serialize(self)
181    }
182
183    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
184        Ok(SerializeVec {
185            vec: Vec::with_capacity(len.unwrap_or(0)),
186        })
187    }
188
189    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Error> {
190        self.serialize_seq(Some(len))
191    }
192
193    fn serialize_tuple_struct(
194        self,
195        _name: &'static str,
196        len: usize,
197    ) -> Result<Self::SerializeTupleStruct, Error> {
198        self.serialize_tuple(len)
199    }
200
201    fn serialize_tuple_variant(
202        self,
203        _name: &'static str,
204        _variant_index: u32,
205        variant: &'static str,
206        len: usize,
207    ) -> Result<Self::SerializeTupleVariant, Error> {
208        Ok(SerializeTupleVariant {
209            name: String::from(variant),
210            vec: Vec::with_capacity(len),
211        })
212    }
213
214    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Error> {
215        Ok(SerializeMap {
216            map: BTreeMap::new(),
217            next_key: None,
218        })
219    }
220
221    fn serialize_struct(
222        self,
223        _name: &'static str,
224        len: usize,
225    ) -> Result<Self::SerializeStruct, Error> {
226        self.serialize_map(Some(len))
227    }
228
229    fn serialize_struct_variant(
230        self,
231        _name: &'static str,
232        _variant_index: u32,
233        variant: &'static str,
234        _len: usize,
235    ) -> Result<Self::SerializeStructVariant, Error> {
236        Ok(SerializeStructVariant {
237            name: String::from(variant),
238            map: BTreeMap::new(),
239        })
240    }
241
242    #[inline]
243    fn is_human_readable(&self) -> bool {
244        false
245    }
246}
247
248pub struct SerializeVec {
249    vec: Vec<Value>,
250}
251
252pub struct SerializeTupleVariant {
253    name: String,
254    vec: Vec<Value>,
255}
256
257pub struct SerializeMap {
258    map: BTreeMap<Value, Value>,
259    next_key: Option<Value>,
260}
261
262pub struct SerializeStructVariant {
263    name: String,
264    map: BTreeMap<Value, Value>,
265}
266
267impl serde::ser::SerializeSeq for SerializeVec {
268    type Ok = Value;
269    type Error = Error;
270
271    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error>
272    where
273        T: Serialize + ?Sized,
274    {
275        self.vec.push(to_value(value)?);
276        Ok(())
277    }
278
279    fn end(self) -> Result<Value, Error> {
280        Ok(Value::Array(self.vec))
281    }
282}
283
284impl serde::ser::SerializeTuple for SerializeVec {
285    type Ok = Value;
286    type Error = Error;
287
288    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error>
289    where
290        T: Serialize + ?Sized,
291    {
292        serde::ser::SerializeSeq::serialize_element(self, value)
293    }
294
295    fn end(self) -> Result<Value, Error> {
296        serde::ser::SerializeSeq::end(self)
297    }
298}
299
300impl serde::ser::SerializeTupleStruct for SerializeVec {
301    type Ok = Value;
302    type Error = Error;
303
304    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error>
305    where
306        T: Serialize + ?Sized,
307    {
308        serde::ser::SerializeSeq::serialize_element(self, value)
309    }
310
311    fn end(self) -> Result<Value, Error> {
312        serde::ser::SerializeSeq::end(self)
313    }
314}
315
316impl serde::ser::SerializeTupleVariant for SerializeTupleVariant {
317    type Ok = Value;
318    type Error = Error;
319
320    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error>
321    where
322        T: Serialize + ?Sized,
323    {
324        self.vec.push(to_value(value)?);
325        Ok(())
326    }
327
328    fn end(self) -> Result<Value, Error> {
329        let mut object = BTreeMap::new();
330
331        object.insert(Value::from(self.name), Value::Array(self.vec));
332
333        Ok(Value::Map(object))
334    }
335}
336
337impl serde::ser::SerializeMap for SerializeMap {
338    type Ok = Value;
339    type Error = Error;
340
341    fn serialize_key<T>(&mut self, key: &T) -> Result<(), Error>
342    where
343        T: Serialize + ?Sized,
344    {
345        self.next_key = Some(to_value(key)?);
346        Ok(())
347    }
348
349    fn serialize_value<T>(&mut self, value: &T) -> Result<(), Error>
350    where
351        T: Serialize + ?Sized,
352    {
353        let key = self.next_key.take();
354        // Panic because this indicates a bug in the program rather than an
355        // expected failure.
356        let key = key.expect("serialize_value called before serialize_key");
357        self.map.insert(key, to_value(value)?);
358        Ok(())
359    }
360
361    fn end(self) -> Result<Value, Error> {
362        Ok(Value::Map(self.map))
363    }
364}
365
366impl serde::ser::SerializeStruct for SerializeMap {
367    type Ok = Value;
368    type Error = Error;
369
370    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
371    where
372        T: Serialize + ?Sized,
373    {
374        serde::ser::SerializeMap::serialize_key(self, key)?;
375        serde::ser::SerializeMap::serialize_value(self, value)
376    }
377
378    fn end(self) -> Result<Value, Error> {
379        serde::ser::SerializeMap::end(self)
380    }
381}
382
383impl serde::ser::SerializeStructVariant for SerializeStructVariant {
384    type Ok = Value;
385    type Error = Error;
386
387    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
388    where
389        T: Serialize + ?Sized,
390    {
391        self.map
392            .insert(Value::from(String::from(key)), to_value(value)?);
393        Ok(())
394    }
395
396    fn end(self) -> Result<Value, Error> {
397        let mut object = BTreeMap::new();
398
399        object.insert(Value::from(self.name), Value::Map(self.map));
400
401        Ok(Value::Map(object))
402    }
403}
404
405/// Convert a `T` into `multi_cbor::Value` which is an enum that can represent
406/// any valid CBOR data.
407///
408/// ```rust
409/// extern crate serde;
410///
411/// #[macro_use]
412/// extern crate serde_derive;
413/// extern crate multi_cbor;
414///
415/// use std::error::Error;
416///
417/// #[derive(Serialize)]
418/// struct User {
419///     fingerprint: String,
420///     location: String,
421/// }
422///
423/// fn main() {
424///     let u = User {
425///         fingerprint: "0xF9BA143B95FF6D82".to_owned(),
426///         location: "Menlo Park, CA".to_owned(),
427///     };
428///
429///     let v = multi_cbor::value::to_value(u).unwrap();
430/// }
431/// ```
432#[allow(clippy::needless_pass_by_value)]
433// Taking by value is more friendly to iterator adapters, option and result
434pub fn to_value<T>(value: T) -> Result<Value, Error>
435where
436    T: Serialize,
437{
438    value.serialize(Serializer)
439}