1use crate::ErrorType;
3use crate::{Error, ObjectHasher};
4use crate::{
5 prelude::*,
6 serde::value::shared::MapKeyDeserializer,
7 value::owned::{Object, Value},
8};
9use serde_ext::{
10 de::{
11 self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, IntoDeserializer, MapAccess,
12 SeqAccess, VariantAccess, Visitor,
13 },
14 forward_to_deserialize_any,
15};
16use std::fmt;
17
18impl<'de> de::Deserializer<'de> for Value {
19 type Error = Error;
20
21 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
25 where
26 V: Visitor<'de>,
27 {
28 match self {
29 Value::Static(StaticNode::Null) => visitor.visit_unit(),
30 Value::Static(StaticNode::Bool(b)) => visitor.visit_bool(b),
31 Value::Static(StaticNode::I64(n)) => visitor.visit_i64(n),
32 #[cfg(feature = "128bit")]
33 Value::Static(StaticNode::I128(n)) => visitor.visit_i128(n),
34 Value::Static(StaticNode::U64(n)) => visitor.visit_u64(n),
35 #[cfg(feature = "128bit")]
36 Value::Static(StaticNode::U128(n)) => visitor.visit_u128(n),
37 #[allow(clippy::useless_conversion)] Value::Static(StaticNode::F64(n)) => visitor.visit_f64(n.into()),
39 Value::String(s) => visitor.visit_string(s),
40 Value::Array(a) => visit_array(Array(a.into_iter()), visitor),
41 Value::Object(o) => visitor.visit_map(ObjectAccess {
42 i: o.into_iter(),
43 v: None,
44 }),
45 }
46 }
47
48 #[cfg_attr(not(feature = "no-inline"), inline)]
49 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
50 where
51 V: Visitor<'de>,
52 {
53 if self == Value::Static(StaticNode::Null) {
54 visitor.visit_unit()
55 } else {
56 visitor.visit_some(self)
57 }
58 }
59 #[cfg_attr(not(feature = "no-inline"), inline)]
60 fn deserialize_enum<V>(
61 self,
62 _name: &str,
63 _variants: &'static [&'static str],
64 visitor: V,
65 ) -> Result<V::Value, Error>
66 where
67 V: Visitor<'de>,
68 {
69 let (variant, value) = match self {
70 Value::Object(value) => {
71 let mut iter = value.into_iter();
72 let Some((variant, value)) = iter.next() else {
73 return Err(crate::Deserializer::error(ErrorType::Eof));
74 };
75 if iter.next().is_some() {
77 return Err(crate::Deserializer::error(ErrorType::TrailingData));
78 }
79 (variant, Some(value))
80 }
81 Value::String(variant) => (variant, None),
82 other => {
83 return Err(crate::Deserializer::error(ErrorType::Unexpected(
84 Some(ValueType::Object),
85 Some(other.value_type()),
86 )));
87 }
88 };
89
90 visitor.visit_enum(EnumDeserializer { variant, value })
91 }
92
93 #[cfg_attr(not(feature = "no-inline"), inline)]
94 fn deserialize_newtype_struct<V>(
95 self,
96 _name: &'static str,
97 visitor: V,
98 ) -> Result<V::Value, Error>
99 where
100 V: Visitor<'de>,
101 {
102 visitor.visit_newtype_struct(self)
103 }
104
105 #[cfg_attr(not(feature = "no-inline"), inline)]
106 fn deserialize_struct<V>(
107 self,
108 _name: &'static str,
109 _fields: &'static [&'static str],
110 visitor: V,
111 ) -> Result<V::Value, Error>
112 where
113 V: Visitor<'de>,
114 {
115 match self {
116 Value::Array(a) => visit_array(Array(a.into_iter()), visitor),
118 Value::Object(o) => visitor.visit_map(ObjectAccess::new(o.into_iter())),
119 other => Err(crate::Deserializer::error(ErrorType::Unexpected(
120 Some(ValueType::Object),
121 Some(other.value_type()),
122 ))),
123 }
124 }
125
126 forward_to_deserialize_any! {
127 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
128 bytes byte_buf unit unit_struct seq tuple
129 tuple_struct map identifier ignored_any
130 }
131}
132
133trait Remaining {
135 fn remaining(&self) -> usize;
136}
137
138fn visit_array<'de, A, V>(mut seq: A, visitor: V) -> Result<V::Value, Error>
141where
142 A: SeqAccess<'de, Error = Error> + Remaining,
143 V: Visitor<'de>,
144{
145 let len = seq.remaining();
146 let value = visitor.visit_seq(&mut seq)?;
147 if seq.remaining() == 0 {
148 Ok(value)
149 } else {
150 Err(de::Error::invalid_length(len, &"fewer elements in array"))
151 }
152}
153
154struct Array(std::vec::IntoIter<Value>);
155impl Remaining for Array {
156 fn remaining(&self) -> usize {
157 self.0.len()
158 }
159}
160
161impl<'de> SeqAccess<'de> for Array {
164 type Error = Error;
165
166 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
167 where
168 T: DeserializeSeed<'de>,
169 {
170 self.0
171 .next()
172 .map_or(Ok(None), |v| seed.deserialize(v).map(Some))
173 }
174}
175
176struct ArrayRef<'de>(std::slice::Iter<'de, Value>);
177impl Remaining for ArrayRef<'_> {
178 fn remaining(&self) -> usize {
179 self.0.len()
180 }
181}
182
183impl<'de> SeqAccess<'de> for ArrayRef<'de> {
186 type Error = Error;
187
188 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
189 where
190 T: DeserializeSeed<'de>,
191 {
192 self.0
193 .next()
194 .map_or(Ok(None), |v| seed.deserialize(v).map(Some))
195 }
196}
197
198struct ObjectAccess<const N: usize = 32> {
199 i: halfbrown::IntoIter<String, Value, N>,
200 v: Option<Value>,
201}
202
203impl<const N: usize> ObjectAccess<N> {
204 fn new(i: halfbrown::IntoIter<String, Value, N>) -> Self {
205 Self { i, v: None }
206 }
207}
208impl<'de> MapAccess<'de> for ObjectAccess {
211 type Error = Error;
212
213 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
214 where
215 K: DeserializeSeed<'de>,
216 {
217 match self.i.next() {
218 Some((k, v)) => {
219 self.v = Some(v);
220 seed.deserialize(MapKeyDeserializer::new(k)).map(Some)
222 }
223 _ => Ok(None),
224 }
225 }
226
227 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
228 where
229 V: DeserializeSeed<'de>,
230 {
231 match self.v.take() {
232 Some(v) => seed.deserialize(v),
233 None => Err(crate::Deserializer::error(ErrorType::Eof)),
234 }
235 }
236}
237
238struct ObjectRefAccess<'de> {
239 i: halfbrown::Iter<'de, String, Value>,
240 v: Option<&'de Value>,
241}
242
243impl<'de> ObjectRefAccess<'de> {
244 fn new(i: halfbrown::Iter<'de, String, Value>) -> Self {
245 Self { i, v: None }
246 }
247}
248
249impl<'de> MapAccess<'de> for ObjectRefAccess<'de> {
252 type Error = Error;
253
254 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
255 where
256 K: DeserializeSeed<'de>,
257 {
258 if let Some((k, v)) = self.i.next() {
259 self.v = Some(v);
260 seed.deserialize(MapKeyDeserializer::new(k.as_str()))
261 .map(Some)
262 } else {
263 Ok(None)
264 }
265 }
266
267 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
268 where
269 V: DeserializeSeed<'de>,
270 {
271 match self.v.take() {
272 Some(v) => seed.deserialize(v),
273 None => Err(crate::Deserializer::error(ErrorType::Eof)),
274 }
275 }
276}
277
278impl<'de> Deserialize<'de> for Value {
279 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
280 where
281 D: Deserializer<'de>,
282 {
283 deserializer.deserialize_any(ValueVisitor)
284 }
285}
286
287struct ValueVisitor;
288
289impl<'de> Visitor<'de> for ValueVisitor {
290 type Value = Value;
291
292 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
293 formatter.write_str("a JSONesque value")
294 }
295
296 #[cfg_attr(not(feature = "no-inline"), inline)]
298 fn visit_unit<E>(self) -> Result<Self::Value, E> {
299 Ok(Value::Static(StaticNode::Null))
300 }
301
302 #[cfg_attr(not(feature = "no-inline"), inline)]
304 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> {
305 Ok(Value::Static(StaticNode::Bool(value)))
306 }
307
308 #[cfg_attr(not(feature = "no-inline"), inline)]
310 fn visit_none<E>(self) -> Result<Self::Value, E> {
311 Ok(Value::Static(StaticNode::Null))
312 }
313
314 #[cfg_attr(not(feature = "no-inline"), inline)]
315 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
316 where
317 D: Deserializer<'de>,
318 {
319 deserializer.deserialize_any(self)
320 }
321
322 #[cfg_attr(not(feature = "no-inline"), inline)]
332 fn visit_i8<E>(self, value: i8) -> Result<Self::Value, E>
333 where
334 E: de::Error,
335 {
336 Ok(Value::Static(StaticNode::I64(i64::from(value))))
337 }
338
339 #[cfg_attr(not(feature = "no-inline"), inline)]
340 fn visit_i16<E>(self, value: i16) -> Result<Self::Value, E>
341 where
342 E: de::Error,
343 {
344 Ok(Value::Static(StaticNode::I64(i64::from(value))))
345 }
346
347 #[cfg_attr(not(feature = "no-inline"), inline)]
348 fn visit_i32<E>(self, value: i32) -> Result<Self::Value, E>
349 where
350 E: de::Error,
351 {
352 Ok(Value::Static(StaticNode::I64(i64::from(value))))
353 }
354
355 #[cfg_attr(not(feature = "no-inline"), inline)]
356 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
357 where
358 E: de::Error,
359 {
360 Ok(Value::Static(StaticNode::I64(value)))
361 }
362
363 #[cfg(feature = "128bit")]
364 #[cfg_attr(not(feature = "no-inline"), inline)]
365 fn visit_i128<E>(self, value: i128) -> Result<Self::Value, E>
366 where
367 E: de::Error,
368 {
369 Ok(Value::Static(StaticNode::I128(value)))
370 }
371
372 #[cfg_attr(not(feature = "no-inline"), inline)]
375 fn visit_u8<E>(self, value: u8) -> Result<Self::Value, E>
376 where
377 E: de::Error,
378 {
379 Ok(Value::Static(StaticNode::U64(u64::from(value))))
380 }
381
382 #[cfg_attr(not(feature = "no-inline"), inline)]
383 fn visit_u16<E>(self, value: u16) -> Result<Self::Value, E>
384 where
385 E: de::Error,
386 {
387 Ok(Value::Static(StaticNode::U64(u64::from(value))))
388 }
389
390 #[cfg_attr(not(feature = "no-inline"), inline)]
391 fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E>
392 where
393 E: de::Error,
394 {
395 Ok(Value::Static(StaticNode::U64(u64::from(value))))
396 }
397
398 #[cfg_attr(not(feature = "no-inline"), inline)]
399 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
400 where
401 E: de::Error,
402 {
403 Ok(Value::Static(StaticNode::U64(value)))
404 }
405
406 #[cfg(feature = "128bit")]
407 #[cfg_attr(not(feature = "no-inline"), inline)]
408 fn visit_u128<E>(self, value: u128) -> Result<Self::Value, E>
409 where
410 E: de::Error,
411 {
412 Ok(Value::Static(StaticNode::U128(value)))
413 }
414 #[cfg_attr(not(feature = "no-inline"), inline)]
417 fn visit_f32<E>(self, value: f32) -> Result<Self::Value, E>
418 where
419 E: de::Error,
420 {
421 Ok(Value::Static(StaticNode::from(f64::from(value))))
422 }
423
424 #[cfg_attr(not(feature = "no-inline"), inline)]
425 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
426 where
427 E: de::Error,
428 {
429 Ok(Value::Static(StaticNode::from(value)))
430 }
431
432 #[cfg_attr(not(feature = "no-inline"), inline)]
434 fn visit_char<E>(self, value: char) -> Result<Self::Value, E>
435 where
436 E: de::Error,
437 {
438 Ok(Value::from(value.to_string()))
439 }
440
441 #[cfg_attr(not(feature = "no-inline"), inline)]
442 fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Self::Value, E>
443 where
444 E: de::Error,
445 {
446 Ok(Value::from(value))
447 }
448
449 #[cfg_attr(not(feature = "no-inline"), inline)]
450 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
451 where
452 E: de::Error,
453 {
454 Ok(Value::String(value.to_owned()))
455 }
456
457 #[cfg_attr(not(feature = "no-inline"), inline)]
458 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
459 where
460 E: de::Error,
461 {
462 Ok(Value::String(value))
463 }
464
465 #[cfg_attr(not(feature = "no-inline"), inline)]
496 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
497 where
498 A: MapAccess<'de>,
499 {
500 let size = map.size_hint().unwrap_or_default();
501
502 let mut m = Object::with_capacity_and_hasher(size, ObjectHasher::default());
503 while let Some(k) = map.next_key()? {
504 let v = map.next_value()?;
505 m.insert(k, v);
506 }
507 Ok(Value::from(m))
508 }
509
510 #[cfg_attr(not(feature = "no-inline"), inline)]
511 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
512 where
513 A: SeqAccess<'de>,
514 {
515 let size = seq.size_hint().unwrap_or_default();
516
517 let mut v = Vec::with_capacity(size);
518 while let Some(e) = seq.next_element()? {
519 v.push(e);
520 }
521 Ok(Value::Array(Box::new(v)))
522 }
523}
524
525struct EnumDeserializer {
526 variant: String,
527 value: Option<Value>,
528}
529
530impl<'de> EnumAccess<'de> for EnumDeserializer {
531 type Error = Error;
532 type Variant = VariantDeserializer;
533
534 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, VariantDeserializer), Error>
535 where
536 V: DeserializeSeed<'de>,
537 {
538 let variant = self.variant.into_deserializer();
539 let visitor = VariantDeserializer { value: self.value };
540 seed.deserialize(variant).map(|v| (v, visitor))
541 }
542}
543
544impl IntoDeserializer<'_, Error> for Value {
545 type Deserializer = Self;
546
547 fn into_deserializer(self) -> Self::Deserializer {
548 self
549 }
550}
551
552struct VariantDeserializer {
553 value: Option<Value>,
554}
555
556impl<'de> VariantAccess<'de> for VariantDeserializer {
557 type Error = Error;
558
559 fn unit_variant(self) -> Result<(), Error> {
560 match self.value {
561 Some(value) => Deserialize::deserialize(value),
562 None => Ok(()),
563 }
564 }
565
566 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error>
567 where
568 T: DeserializeSeed<'de>,
569 {
570 match self.value {
571 Some(value) => seed.deserialize(value),
572 None => Err(crate::Deserializer::error(ErrorType::Unexpected(
573 Some(ValueType::Object),
574 None,
575 ))),
576 }
577 }
578
579 fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error>
580 where
581 V: Visitor<'de>,
582 {
583 match self.value {
584 Some(Value::Array(v)) => visit_array(Array(v.into_iter()), visitor),
585 Some(other) => Err(crate::Deserializer::error(ErrorType::Unexpected(
586 Some(ValueType::Array),
587 Some(other.value_type()),
588 ))),
589 None => Err(crate::Deserializer::error(ErrorType::Unexpected(
590 Some(ValueType::Array),
591 None,
592 ))),
593 }
594 }
595
596 fn struct_variant<V>(
597 self,
598 _fields: &'static [&'static str],
599 visitor: V,
600 ) -> Result<V::Value, Error>
601 where
602 V: Visitor<'de>,
603 {
604 match self.value {
605 Some(Value::Object(o)) => visitor.visit_map(ObjectAccess::new(o.into_iter())),
606 Some(Value::Array(a)) => visit_array(Array(a.into_iter()), visitor),
608 Some(other) => Err(crate::Deserializer::error(ErrorType::Unexpected(
609 Some(ValueType::Object),
610 Some(other.value_type()),
611 ))),
612 None => Err(crate::Deserializer::error(ErrorType::Unexpected(
613 Some(ValueType::Object),
614 None,
615 ))),
616 }
617 }
618}
619
620impl<'de> de::Deserializer<'de> for &'de Value {
621 type Error = Error;
622
623 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
627 where
628 V: Visitor<'de>,
629 {
630 match self {
631 Value::Static(StaticNode::Null) => visitor.visit_unit(),
632 Value::Static(StaticNode::Bool(b)) => visitor.visit_bool(*b),
633 Value::Static(StaticNode::I64(n)) => visitor.visit_i64(*n),
634 #[cfg(feature = "128bit")]
635 Value::Static(StaticNode::I128(n)) => visitor.visit_i128(*n),
636 Value::Static(StaticNode::U64(n)) => visitor.visit_u64(*n),
637 #[cfg(feature = "128bit")]
638 Value::Static(StaticNode::U128(n)) => visitor.visit_u128(*n),
639 #[allow(clippy::useless_conversion)] Value::Static(StaticNode::F64(n)) => visitor.visit_f64((*n).into()),
641 Value::String(s) => visitor.visit_borrowed_str(s),
642 Value::Array(a) => visit_array(ArrayRef(a.as_slice().iter()), visitor),
643 Value::Object(o) => visitor.visit_map(ObjectRefAccess::new(o.iter())),
644 }
645 }
646
647 #[cfg_attr(not(feature = "no-inline"), inline)]
648 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
649 where
650 V: Visitor<'de>,
651 {
652 if self == &Value::Static(StaticNode::Null) {
653 visitor.visit_unit()
654 } else {
655 visitor.visit_some(self)
656 }
657 }
658
659 #[cfg_attr(not(feature = "no-inline"), inline)]
660 fn deserialize_newtype_struct<V>(
661 self,
662 _name: &'static str,
663 visitor: V,
664 ) -> Result<V::Value, Error>
665 where
666 V: Visitor<'de>,
667 {
668 visitor.visit_newtype_struct(self)
669 }
670
671 #[cfg_attr(not(feature = "no-inline"), inline)]
672 fn deserialize_struct<V>(
673 self,
674 _name: &'static str,
675 _fields: &'static [&'static str],
676 visitor: V,
677 ) -> Result<V::Value, Error>
678 where
679 V: Visitor<'de>,
680 {
681 match self {
682 Value::Array(a) => visit_array(ArrayRef(a.as_slice().iter()), visitor),
684 Value::Object(o) => visitor.visit_map(ObjectRefAccess::new(o.iter())),
685 other => Err(crate::Deserializer::error(ErrorType::Unexpected(
686 Some(ValueType::Object),
687 Some(other.value_type()),
688 ))),
689 }
690 }
691
692 #[cfg_attr(not(feature = "no-inline"), inline)]
693 fn deserialize_enum<V>(
694 self,
695 _name: &str,
696 _variants: &'static [&'static str],
697 visitor: V,
698 ) -> Result<V::Value, Error>
699 where
700 V: Visitor<'de>,
701 {
702 let (variant, value) = match self {
703 Value::Object(value) => {
704 let mut iter = value.iter();
705 let Some((variant, value)) = iter.next() else {
706 return Err(crate::Deserializer::error(ErrorType::Eof));
707 };
708 if iter.next().is_some() {
710 return Err(crate::Deserializer::error(ErrorType::TrailingData));
711 }
712 (variant, Some(value))
713 }
714 Value::String(variant) => (variant, None),
715 other => {
716 return Err(crate::Deserializer::error(ErrorType::Unexpected(
717 Some(ValueType::Object),
718 Some(other.value_type()),
719 )));
720 }
721 };
722
723 visitor.visit_enum(EnumRefDeserializer { variant, value })
724 }
725
726 forward_to_deserialize_any! {
727 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
728 bytes byte_buf unit unit_struct seq tuple
729 tuple_struct map identifier ignored_any
730 }
731}
732
733struct EnumRefDeserializer<'de> {
734 variant: &'de str,
735 value: Option<&'de Value>,
736}
737
738impl<'de> EnumAccess<'de> for EnumRefDeserializer<'de> {
739 type Error = Error;
740 type Variant = VariantRefDeserializer<'de>;
741
742 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Error>
743 where
744 V: DeserializeSeed<'de>,
745 {
746 let variant = self.variant.into_deserializer();
747 let visitor = VariantRefDeserializer { value: self.value };
748 seed.deserialize(variant).map(|v| (v, visitor))
749 }
750}
751struct VariantRefDeserializer<'de> {
752 value: Option<&'de Value>,
753}
754
755impl<'de> VariantAccess<'de> for VariantRefDeserializer<'de> {
756 type Error = Error;
757
758 fn unit_variant(self) -> Result<(), Error> {
759 match self.value {
760 Some(value) => Deserialize::deserialize(value),
761 None => Ok(()),
762 }
763 }
764
765 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error>
766 where
767 T: DeserializeSeed<'de>,
768 {
769 match self.value {
770 Some(value) => seed.deserialize(value),
771 None => Err(crate::Deserializer::error(ErrorType::Unexpected(
772 Some(ValueType::Object),
773 None,
774 ))),
775 }
776 }
777
778 fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error>
779 where
780 V: Visitor<'de>,
781 {
782 match self.value {
783 Some(Value::Array(v)) => visit_array(ArrayRef(v.as_slice().iter()), visitor),
784 Some(other) => Err(crate::Deserializer::error(ErrorType::Unexpected(
785 Some(ValueType::Array),
786 Some(other.value_type()),
787 ))),
788 None => Err(crate::Deserializer::error(ErrorType::Unexpected(
789 Some(ValueType::Array),
790 None,
791 ))),
792 }
793 }
794
795 fn struct_variant<V>(
796 self,
797 _fields: &'static [&'static str],
798 visitor: V,
799 ) -> Result<V::Value, Error>
800 where
801 V: Visitor<'de>,
802 {
803 match self.value {
804 Some(Value::Object(o)) => visitor.visit_map(ObjectRefAccess::new(o.iter())),
805 Some(Value::Array(a)) => visit_array(ArrayRef(a.as_slice().iter()), visitor),
807 Some(other) => Err(crate::Deserializer::error(ErrorType::Unexpected(
808 Some(ValueType::Object),
809 Some(other.value_type()),
810 ))),
811 None => Err(crate::Deserializer::error(ErrorType::Unexpected(
812 Some(ValueType::Object),
813 None,
814 ))),
815 }
816 }
817}
818
819#[cfg(test)]
820mod test {
821 use crate::{json, owned, prelude::*};
822 use serde::Deserialize;
823
824 #[test]
825 fn option_field_absent_owned() {
826 #[derive(serde::Deserialize, Debug, PartialEq, Eq)]
827 pub struct Person {
828 pub name: String,
829 pub middle_name: Option<String>,
830 pub friends: Vec<String>,
831 }
832 let mut raw_json = r#"{"name":"bob","friends":[]}"#.to_string();
833 let result: Result<Person, _> = crate::to_owned_value(unsafe { raw_json.as_bytes_mut() })
834 .and_then(super::super::from_value);
835 assert_eq!(
836 result,
837 Ok(Person {
838 name: "bob".to_string(),
839 middle_name: None,
840 friends: vec![]
841 })
842 );
843 }
844 #[test]
845 fn option_field_present_owned() {
846 #[derive(serde::Deserialize, Debug, PartialEq, Eq)]
847 pub struct Point {
848 pub x: u64,
849 pub y: u64,
850 }
851 #[derive(serde::Deserialize, Debug, PartialEq, Eq)]
852 pub struct Person {
853 pub name: String,
854 pub middle_name: Option<String>,
855 pub friends: Vec<String>,
856 pub pos: Point,
857 }
858 let mut raw_json =
859 r#"{"name":"bob","middle_name": "frank", "friends":[], "pos": [1,2]}"#.to_string();
860 let result: Result<Person, _> = crate::to_owned_value(unsafe { raw_json.as_bytes_mut() })
861 .and_then(super::super::from_value);
862 assert_eq!(
863 result,
864 Ok(Person {
865 name: "bob".to_string(),
866 middle_name: Some("frank".to_string()),
867 friends: vec![],
868 pos: Point { x: 1, y: 2 }
869 })
870 );
871 }
872
873 #[test]
874 fn deserialize() {
875 use halfbrown::{HashMap, hashmap};
876 #[derive(serde::Deserialize, Debug, PartialEq, Eq)]
877 #[serde(rename_all = "lowercase")]
878 pub enum Rotate {
879 Left,
880 Right,
881 Up,
882 Down,
883 }
884 #[derive(serde::Deserialize, Debug, PartialEq)]
885 pub struct Point {
886 pub x: i64,
887 pub y: i64,
888 pub z: f64,
889 pub rotate: Rotate,
890 }
891 #[derive(serde::Deserialize, Debug, PartialEq)]
892 pub struct Person {
893 pub name: String,
894 pub middle_name: Option<String>,
895 pub friends: Vec<String>,
896 pub pos: Point,
897 pub age: u64,
898 }
899 #[derive(serde::Deserialize, Debug, PartialEq, Eq)]
900 pub struct TestStruct {
901 pub key: HashMap<String, String>,
902 pub vec: Vec<Vec<Option<u8>>>,
903 }
904
905 let mut raw_json =
906 r#"{"name":"bob","middle_name": "frank", "friends":[], "pos": [-1, 2, -3.25, "up"], "age": 123}"#.to_string();
907 let serde_result: Person = serde_json::from_str(&raw_json).expect("serde_json::from_str");
908 let value =
909 crate::to_owned_value(unsafe { raw_json.as_bytes_mut() }).expect("to_owned_value");
910 let result: Person = super::super::from_refvalue(&value).expect("from_refvalue");
911 let expected = Person {
912 name: "bob".to_string(),
913 middle_name: Some("frank".to_string()),
914 friends: Vec::new(),
915 pos: Point {
916 x: -1,
917 y: 2,
918 z: -3.25_f64,
919 rotate: Rotate::Up,
920 },
921 age: 123,
922 };
923 assert_eq!(result, expected);
924 assert_eq!(result, serde_result);
925
926 let mut raw_json = r#"{"key":{"subkey": "value"}, "vec":[[null], [1]]}"#.to_string();
927 let value =
928 crate::to_owned_value(unsafe { raw_json.as_bytes_mut() }).expect("to_owned_value");
929 let result: TestStruct = super::super::from_refvalue(&value).expect("from_refvalue");
930 let expected = TestStruct {
931 key: hashmap!("subkey".to_string() => "value".to_string()),
932 vec: vec![vec![None], vec![Some(1)]],
933 };
934 assert_eq!(result, expected);
935 }
936
937 #[cfg(feature = "128bit")]
938 #[test]
939 fn deserialize_128bit() {
940 let value = i128::from(i64::MIN) - 1;
941 let int128 = crate::OwnedValue::Static(crate::StaticNode::I128(value));
942 let res: i128 = super::super::from_refvalue(&int128).expect("from_refvalue");
943 assert_eq!(value, res);
944
945 let value = u128::from(u64::MAX);
946 let int128 = crate::OwnedValue::Static(crate::StaticNode::U128(value));
947 let res: u128 = super::super::from_refvalue(&int128).expect("from_refvalue");
948 assert_eq!(value, res);
949 }
950 #[test]
951 fn variant() {
952 struct NameAndConfig {
953 name: String,
954 config: Option<owned::Value>,
955 }
956 impl<'v> serde::Deserialize<'v> for NameAndConfig {
957 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
958 where
959 D: serde::Deserializer<'v>,
960 {
961 #[derive(Deserialize)]
962 #[serde(untagged)]
963 enum Variants {
964 Name(String),
965 NameAndConfig {
966 name: String,
967 config: Option<owned::Value>,
968 },
969 }
970
971 let var = Variants::deserialize(deserializer)?;
972
973 match var {
974 Variants::Name(name) => Ok(NameAndConfig { name, config: None }),
975 Variants::NameAndConfig { name, config } => Ok(NameAndConfig { name, config }),
976 }
977 }
978 }
979
980 let v = json!({"name": "name", "config": 42});
981 let nac = NameAndConfig::deserialize(v).expect("could structurize two element struct");
982 assert_eq!(nac.name, "name");
983 assert_eq!(nac.config.as_u8(), Some(42));
984 let v = json!({"name": "name"});
985 let nac = NameAndConfig::deserialize(v).expect("could structurize one element struct");
986 assert_eq!(nac.name, "name");
987 assert_eq!(nac.config, None);
988 let v = json!("name");
989 let nac = NameAndConfig::deserialize(v).expect("could structurize string");
990 assert_eq!(nac.name, "name");
991 assert_eq!(nac.config, None);
992 }
993}