1use super::to_value;
2use crate::{
3 stry,
4 value::owned::{Object, Value},
5 Error, ErrorType, ObjectHasher, Result, StaticNode,
6};
7use serde_ext::ser::{
8 self, Serialize, SerializeMap as SerializeMapTrait, SerializeSeq as SerializeSeqTrait,
9};
10
11type Impossible<T> = ser::Impossible<T, Error>;
12
13impl Serialize for Value {
14 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
15 where
16 S: ser::Serializer,
17 {
18 match self {
19 Value::Static(StaticNode::Null) => serializer.serialize_unit(),
20 Value::Static(StaticNode::Bool(b)) => serializer.serialize_bool(*b),
21 #[allow(clippy::useless_conversion)] Value::Static(StaticNode::F64(f)) => serializer.serialize_f64((*f).into()),
23 Value::Static(StaticNode::U64(i)) => serializer.serialize_u64(*i),
24 #[cfg(feature = "128bit")]
25 Value::Static(StaticNode::U128(i)) => serializer.serialize_u128(*i),
26 Value::Static(StaticNode::I64(i)) => serializer.serialize_i64(*i),
27 #[cfg(feature = "128bit")]
28 Value::Static(StaticNode::I128(i)) => serializer.serialize_i128(*i),
29 Value::String(s) => serializer.serialize_str(s),
30 Value::Array(v) => {
31 let mut seq = serializer.serialize_seq(Some(v.len()))?;
32 for e in v.as_ref() {
33 seq.serialize_element(e)?;
34 }
35 seq.end()
36 }
37 Value::Object(m) => {
38 let mut map = serializer.serialize_map(Some(m.len()))?;
39 for (k, v) in m.iter() {
40 map.serialize_entry(k, v)?;
41 }
42 map.end()
43 }
44 }
45 }
46}
47
48#[derive(Default)]
49pub struct Serializer {}
50
51impl serde::Serializer for Serializer {
52 type Ok = Value;
53 type Error = Error;
54
55 type SerializeSeq = SerializeVec;
56 type SerializeTuple = SerializeVec;
57 type SerializeTupleStruct = SerializeVec;
58 type SerializeTupleVariant = SerializeTupleVariant;
59 type SerializeMap = SerializeMap;
60 type SerializeStruct = SerializeMap;
61 type SerializeStructVariant = SerializeStructVariant;
62
63 #[cfg_attr(not(feature = "no-inline"), inline)]
64 fn serialize_bool(self, value: bool) -> Result<Value> {
65 Ok(Value::Static(StaticNode::Bool(value)))
66 }
67
68 #[cfg_attr(not(feature = "no-inline"), inline)]
69 fn serialize_i8(self, value: i8) -> Result<Value> {
70 self.serialize_i64(i64::from(value))
71 }
72
73 #[cfg_attr(not(feature = "no-inline"), inline)]
74 fn serialize_i16(self, value: i16) -> Result<Value> {
75 self.serialize_i64(i64::from(value))
76 }
77
78 #[cfg_attr(not(feature = "no-inline"), inline)]
79 fn serialize_i32(self, value: i32) -> Result<Value> {
80 self.serialize_i64(i64::from(value))
81 }
82
83 fn serialize_i64(self, value: i64) -> Result<Value> {
84 Ok(Value::Static(StaticNode::I64(value)))
85 }
86
87 #[cfg(feature = "128bit")]
88 fn serialize_i128(self, value: i128) -> Result<Value> {
89 Ok(Value::Static(StaticNode::I128(value)))
90 }
91
92 #[cfg_attr(not(feature = "no-inline"), inline)]
93 fn serialize_u8(self, value: u8) -> Result<Value> {
94 self.serialize_u64(u64::from(value))
95 }
96
97 #[cfg_attr(not(feature = "no-inline"), inline)]
98 fn serialize_u16(self, value: u16) -> Result<Value> {
99 self.serialize_u64(u64::from(value))
100 }
101
102 #[cfg_attr(not(feature = "no-inline"), inline)]
103 fn serialize_u32(self, value: u32) -> Result<Value> {
104 self.serialize_u64(u64::from(value))
105 }
106
107 #[cfg_attr(not(feature = "no-inline"), inline)]
108 fn serialize_u64(self, value: u64) -> Result<Value> {
109 Ok(Value::Static(StaticNode::U64(value)))
110 }
111
112 #[cfg(feature = "128bit")]
113 fn serialize_u128(self, value: u128) -> Result<Value> {
114 Ok(Value::Static(StaticNode::U128(value)))
115 }
116
117 #[cfg_attr(not(feature = "no-inline"), inline)]
118 fn serialize_f32(self, value: f32) -> Result<Value> {
119 self.serialize_f64(f64::from(value))
120 }
121
122 #[cfg_attr(not(feature = "no-inline"), inline)]
123 fn serialize_f64(self, value: f64) -> Result<Value> {
124 Ok(Value::Static(StaticNode::from(value)))
125 }
126
127 #[cfg_attr(not(feature = "no-inline"), inline)]
128 fn serialize_char(self, value: char) -> Result<Value> {
129 let mut s = String::new();
130 s.push(value);
131 self.serialize_str(&s)
132 }
133
134 #[cfg_attr(not(feature = "no-inline"), inline)]
135 fn serialize_str(self, value: &str) -> Result<Value> {
136 Ok(Value::from(value.to_owned()))
137 }
138
139 #[cfg_attr(not(feature = "no-inline"), inline)]
140 fn serialize_bytes(self, value: &[u8]) -> Result<Value> {
141 Ok(value.iter().copied().collect())
142 }
143
144 #[cfg_attr(not(feature = "no-inline"), inline)]
145 fn serialize_unit(self) -> Result<Value> {
146 Ok(Value::Static(StaticNode::Null))
147 }
148
149 #[cfg_attr(not(feature = "no-inline"), inline)]
150 fn serialize_unit_struct(self, _name: &'static str) -> Result<Value> {
151 self.serialize_unit()
152 }
153
154 #[cfg_attr(not(feature = "no-inline"), inline)]
155 fn serialize_unit_variant(
156 self,
157 _name: &'static str,
158 _variant_index: u32,
159 variant: &'static str,
160 ) -> Result<Value> {
161 self.serialize_str(variant)
162 }
163
164 #[cfg_attr(not(feature = "no-inline"), inline)]
165 fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Value>
166 where
167 T: ?Sized + Serialize,
168 {
169 value.serialize(self)
170 }
171
172 fn serialize_newtype_variant<T>(
173 self,
174 _name: &'static str,
175 _variant_index: u32,
176 variant: &'static str,
177 value: &T,
178 ) -> Result<Value>
179 where
180 T: ?Sized + Serialize,
181 {
182 let mut values = Object::with_capacity_and_hasher(1, ObjectHasher::default());
183 values.insert_nocheck(variant.into(), stry!(to_value(value)));
184 Ok(Value::from(values))
185 }
186
187 #[cfg_attr(not(feature = "no-inline"), inline)]
188 fn serialize_none(self) -> Result<Value> {
189 self.serialize_unit()
190 }
191
192 #[cfg_attr(not(feature = "no-inline"), inline)]
193 fn serialize_some<T>(self, value: &T) -> Result<Value>
194 where
195 T: ?Sized + Serialize,
196 {
197 value.serialize(self)
198 }
199
200 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
201 Ok(SerializeVec {
202 vec: Vec::with_capacity(len.unwrap_or(0)),
203 })
204 }
205
206 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
207 self.serialize_seq(Some(len))
208 }
209
210 fn serialize_tuple_struct(
211 self,
212 _name: &'static str,
213 len: usize,
214 ) -> Result<Self::SerializeTupleStruct> {
215 self.serialize_seq(Some(len))
216 }
217
218 fn serialize_tuple_variant(
219 self,
220 _name: &'static str,
221 _variant_index: u32,
222 variant: &'static str,
223 len: usize,
224 ) -> Result<Self::SerializeTupleVariant> {
225 Ok(SerializeTupleVariant {
226 name: variant.to_owned(),
227 vec: Vec::with_capacity(len),
228 })
229 }
230
231 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
232 Ok(SerializeMap {
233 map: Object::with_capacity_and_hasher(len.unwrap_or(0), ObjectHasher::default()),
234 next_key: None,
235 })
236 }
237
238 fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
239 self.serialize_map(Some(len))
240 }
241
242 fn serialize_struct_variant(
243 self,
244 _name: &'static str,
245 _variant_index: u32,
246 variant: &'static str,
247 len: usize,
248 ) -> Result<Self::SerializeStructVariant> {
249 Ok(SerializeStructVariant {
250 name: variant.to_owned(),
251 map: Object::with_capacity_and_hasher(len, ObjectHasher::default()),
252 })
253 }
254}
255
256pub struct SerializeVec {
257 vec: Vec<Value>,
258}
259
260pub struct SerializeTupleVariant {
261 name: String,
262 vec: Vec<Value>,
263}
264
265pub struct SerializeMap {
266 map: Object,
267 next_key: Option<String>,
268}
269
270pub struct SerializeStructVariant {
271 name: String,
272 map: Object,
273}
274
275impl serde::ser::SerializeSeq for SerializeVec {
276 type Ok = Value;
277 type Error = Error;
278
279 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
280 where
281 T: ?Sized + Serialize,
282 {
283 self.vec.push(stry!(to_value(value)));
284 Ok(())
285 }
286
287 fn end(self) -> Result<Value> {
288 Ok(Value::Array(Box::new(self.vec)))
289 }
290}
291
292impl serde::ser::SerializeTuple for SerializeVec {
293 type Ok = Value;
294 type Error = Error;
295
296 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
297 where
298 T: ?Sized + Serialize,
299 {
300 serde::ser::SerializeSeq::serialize_element(self, value)
301 }
302
303 fn end(self) -> Result<Value> {
304 serde::ser::SerializeSeq::end(self)
305 }
306}
307
308impl serde::ser::SerializeTupleStruct for SerializeVec {
309 type Ok = Value;
310 type Error = Error;
311
312 fn serialize_field<T>(&mut self, value: &T) -> Result<()>
313 where
314 T: ?Sized + Serialize,
315 {
316 serde::ser::SerializeSeq::serialize_element(self, value)
317 }
318
319 fn end(self) -> Result<Value> {
320 serde::ser::SerializeSeq::end(self)
321 }
322}
323
324impl serde::ser::SerializeTupleVariant for SerializeTupleVariant {
325 type Ok = Value;
326 type Error = Error;
327
328 fn serialize_field<T>(&mut self, value: &T) -> Result<()>
329 where
330 T: ?Sized + Serialize,
331 {
332 self.vec.push(stry!(to_value(value)));
333 Ok(())
334 }
335
336 fn end(self) -> Result<Value> {
337 let mut object = Object::with_capacity_and_hasher(1, ObjectHasher::default());
338 object.insert_nocheck(self.name, Value::Array(Box::new(self.vec)));
339 Ok(Value::from(object))
340 }
341}
342
343impl serde::ser::SerializeMap for SerializeMap {
344 type Ok = Value;
345 type Error = Error;
346
347 fn serialize_key<T>(&mut self, key: &T) -> Result<()>
348 where
349 T: ?Sized + Serialize,
350 {
351 self.next_key = Some(stry!(key.serialize(MapKeySerializer {})));
352 Ok(())
353 }
354
355 fn serialize_value<T>(&mut self, value: &T) -> Result<()>
356 where
357 T: ?Sized + Serialize,
358 {
359 let key = self.next_key.take();
360 let key = key.expect("serialize_value called before serialize_key");
363 self.map.insert(key, stry!(to_value(value)));
364 Ok(())
365 }
366
367 fn end(self) -> Result<Value> {
368 Ok(Value::from(self.map))
369 }
370}
371
372struct MapKeySerializer {}
373
374fn key_must_be_a_string() -> Error {
375 Error::generic(ErrorType::KeyMustBeAString)
376}
377
378impl serde_ext::Serializer for MapKeySerializer {
379 type Ok = String;
380 type Error = Error;
381
382 type SerializeSeq = Impossible<String>;
383 type SerializeTuple = Impossible<String>;
384 type SerializeTupleStruct = Impossible<String>;
385 type SerializeTupleVariant = Impossible<String>;
386 type SerializeMap = Impossible<String>;
387 type SerializeStruct = Impossible<String>;
388 type SerializeStructVariant = Impossible<String>;
389
390 #[cfg_attr(not(feature = "no-inline"), inline)]
391 fn serialize_unit_variant(
392 self,
393 _name: &'static str,
394 _variant_index: u32,
395 variant: &'static str,
396 ) -> Result<Self::Ok> {
397 Ok(variant.to_owned())
398 }
399
400 #[cfg_attr(not(feature = "no-inline"), inline)]
401 fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Self::Ok>
402 where
403 T: ?Sized + Serialize,
404 {
405 value.serialize(self)
406 }
407
408 fn serialize_bool(self, _value: bool) -> Result<Self::Ok> {
409 Err(key_must_be_a_string())
410 }
411
412 fn serialize_i8(self, value: i8) -> Result<Self::Ok> {
413 Ok(value.to_string())
414 }
415
416 fn serialize_i16(self, value: i16) -> Result<Self::Ok> {
417 Ok(value.to_string())
418 }
419
420 fn serialize_i32(self, value: i32) -> Result<Self::Ok> {
421 Ok(value.to_string())
422 }
423
424 fn serialize_i64(self, value: i64) -> Result<Self::Ok> {
425 Ok(value.to_string())
426 }
427
428 fn serialize_u8(self, value: u8) -> Result<Self::Ok> {
429 Ok(value.to_string())
430 }
431
432 fn serialize_u16(self, value: u16) -> Result<Self::Ok> {
433 Ok(value.to_string())
434 }
435
436 fn serialize_u32(self, value: u32) -> Result<Self::Ok> {
437 Ok(value.to_string())
438 }
439
440 fn serialize_u64(self, value: u64) -> Result<Self::Ok> {
441 Ok(value.to_string())
442 }
443
444 fn serialize_f32(self, _value: f32) -> Result<Self::Ok> {
445 Err(key_must_be_a_string())
446 }
447
448 fn serialize_f64(self, _value: f64) -> Result<Self::Ok> {
449 Err(key_must_be_a_string())
450 }
451
452 fn serialize_char(self, value: char) -> Result<Self::Ok> {
453 Ok({
454 let mut s = String::new();
455 s.push(value);
456 s
457 })
458 }
459
460 #[cfg_attr(not(feature = "no-inline"), inline)]
461 fn serialize_str(self, value: &str) -> Result<Self::Ok> {
462 Ok(value.to_owned())
463 }
464
465 fn serialize_bytes(self, _value: &[u8]) -> Result<Self::Ok> {
466 Err(key_must_be_a_string())
467 }
468
469 fn serialize_unit(self) -> Result<Self::Ok> {
470 Err(key_must_be_a_string())
471 }
472
473 fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
474 Err(key_must_be_a_string())
475 }
476
477 fn serialize_newtype_variant<T>(
478 self,
479 _name: &'static str,
480 _variant_index: u32,
481 _variant: &'static str,
482 _value: &T,
483 ) -> Result<Self::Ok>
484 where
485 T: ?Sized + Serialize,
486 {
487 Err(key_must_be_a_string())
488 }
489
490 fn serialize_none(self) -> Result<Self::Ok> {
491 Err(key_must_be_a_string())
492 }
493
494 fn serialize_some<T>(self, _value: &T) -> Result<Self::Ok>
495 where
496 T: ?Sized + Serialize,
497 {
498 Err(key_must_be_a_string())
499 }
500
501 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
502 Err(key_must_be_a_string())
503 }
504
505 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
506 Err(key_must_be_a_string())
507 }
508
509 fn serialize_tuple_struct(
510 self,
511 _name: &'static str,
512 _len: usize,
513 ) -> Result<Self::SerializeTupleStruct> {
514 Err(key_must_be_a_string())
515 }
516
517 fn serialize_tuple_variant(
518 self,
519 _name: &'static str,
520 _variant_index: u32,
521 _variant: &'static str,
522 _len: usize,
523 ) -> Result<Self::SerializeTupleVariant> {
524 Err(key_must_be_a_string())
525 }
526
527 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
528 Err(key_must_be_a_string())
529 }
530
531 fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
532 Err(key_must_be_a_string())
533 }
534
535 fn serialize_struct_variant(
536 self,
537 _name: &'static str,
538 _variant_index: u32,
539 _variant: &'static str,
540 _len: usize,
541 ) -> Result<Self::SerializeStructVariant> {
542 Err(key_must_be_a_string())
543 }
544}
545
546impl serde::ser::SerializeStruct for SerializeMap {
547 type Ok = Value;
548 type Error = Error;
549
550 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
551 where
552 T: ?Sized + Serialize,
553 {
554 stry!(serde::ser::SerializeMap::serialize_key(self, key));
555 serde::ser::SerializeMap::serialize_value(self, value)
556 }
557
558 fn end(self) -> Result<Value> {
559 serde::ser::SerializeMap::end(self)
560 }
561}
562
563impl serde::ser::SerializeStructVariant for SerializeStructVariant {
564 type Ok = Value;
565 type Error = Error;
566
567 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
568 where
569 T: ?Sized + Serialize,
570 {
571 self.map.insert(key.into(), stry!(to_value(value)));
572 Ok(())
573 }
574
575 fn end(self) -> Result<Value> {
576 let mut object = Object::with_capacity_and_hasher(1, ObjectHasher::default());
577 object.insert_nocheck(self.name, Value::from(self.map));
578 Ok(Value::from(object))
579 }
580}
581
582#[cfg(test)]
583mod test {
584 #![allow(clippy::ignored_unit_patterns)]
585 use crate::serde::from_slice;
586 #[cfg(not(target_arch = "wasm32"))]
587 use crate::serde::{from_str, to_string};
588 use serde::{Deserialize, Serialize};
589
590 #[derive(Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
591 struct UnitStruct;
592 #[derive(Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
596 struct TupleStruct(u8, u8);
597 #[derive(Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
598 struct TestStruct {
599 key: u32,
600 }
601 #[allow(clippy::struct_field_names)]
620 #[derive(Deserialize, Serialize, PartialEq, Debug, Default)]
621 struct Obj {
622 v_i128: i128,
623 v_i64: i64,
624 v_i32: i32,
625 v_i16: i16,
626 v_i8: i8,
627 v_u128: u128,
628 v_u64: u64,
629 v_usize: usize,
630 v_u32: u32,
631 v_u16: u16,
632 v_u8: u8,
633 v_bool: bool,
634 v_str: String,
635 v_char: char,
636 v_unit_struct: UnitStruct,
638 v_tuple_struct: TupleStruct,
640 v_struct: TestStruct,
641 v_option: Option<i8>,
643 v_arr: Vec<usize>,
644 v_null: (),
645 }
646 #[test]
647 fn from_slice_to_object() {
648 let o = Obj::default();
649 let mut vec = serde_json::to_vec(&o).expect("to_vec");
650 let vec2 = crate::serde::to_vec(&o).expect("to_vec");
651 assert_eq!(vec, vec2);
652
653 println!("{}", serde_json::to_string_pretty(&o).expect("json"));
654 let de: Obj = from_slice(&mut vec).expect("from_slice");
655 assert_eq!(o, de);
656 }
657
658 #[cfg(not(target_arch = "wasm32"))]
659 use proptest::prelude::*;
660 #[cfg(not(target_arch = "wasm32"))]
661 prop_compose! {
662 fn obj_case()(
663 v_i128 in any::<i64>().prop_map(i128::from),
664 v_i64 in any::<i64>(),
665 v_i32 in any::<i32>(),
666 v_i16 in any::<i16>(),
667 v_i8 in any::<i8>(),
668 v_u128 in any::<u64>().prop_map(u128::from),
669 v_u64 in any::<u64>(),
670 v_usize in any::<u32>().prop_map(|v| v as usize),
671 v_u32 in any::<u32>(),
672 v_u16 in any::<u16>(),
673 v_u8 in any::<u8>(),
674 v_bool in any::<bool>(),
675 v_str in ".*",
676 v_char in any::<char>(),
677 v_tuple_struct in any::<(u8, u8)>().prop_map(|(a, b)| TupleStruct(a, b)),
678 v_struct in any::<u32>().prop_map(|key| TestStruct{key}),
679 v_option in any::<Option<i8>>(),
680 v_arr in any::<Vec<usize>>(),
681 ) -> Obj {
682 Obj {
683 v_i128,
684 v_i64,
685 v_i32,
686 v_i16,
687 v_i8,
688 v_u128,
689 v_u64,
690 v_usize,
691 v_u32,
692 v_u16,
693 v_u8,
694 v_bool,
695 v_str,
696 v_char,
697 v_tuple_struct,
698 v_struct,
699 v_option,
700 v_arr,
701 ..Obj::default()
702 }
703 }
704 }
705
706 #[cfg(not(target_arch = "wasm32"))]
707 proptest! {
708 #![proptest_config(ProptestConfig {
709 .. ProptestConfig::default()
710 })]
711
712 #[test]
713 fn prop_deserialize_obj(obj in obj_case()) {
714 let mut vec = serde_json::to_vec(&obj).expect("to_vec");
715 let vec1 = vec.clone();
716 let vec2 = vec.clone();
717 println!("{}", serde_json::to_string_pretty(&obj).expect("json"));
718 let de: Obj = from_slice(&mut vec).expect("from_slice");
719 prop_assert_eq!(&obj, &de);
720
721 let borrowed: crate::BorrowedValue = serde_json::from_slice(& vec1).expect("from_slice");
722 let owned: crate::OwnedValue = serde_json::from_slice(& vec2).expect("from_slice");
723 prop_assert_eq!(&borrowed, &owned);
724 let mut owned_str = to_string(&obj).expect("to_string");
725 unsafe{from_str::<crate::OwnedValue>(&mut owned_str).expect("from_str")};
726
727 let de: Obj = Obj::deserialize(borrowed).expect("deserialize");
728 prop_assert_eq!(&obj, &de);
729 let de: Obj = Obj::deserialize(owned).expect("deserialize");
730 prop_assert_eq!(&obj, &de);
731
732 }
733 }
734}