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