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