1use crate::error::Error;
2use crate::map::Map;
3use crate::number::Number;
4use crate::value::Value;
5use alloc::borrow::{Cow, ToOwned};
6use alloc::string::String;
7#[cfg(feature = "raw_value")]
8use alloc::string::ToString;
9use alloc::vec::{self, Vec};
10use core::fmt;
11use core::slice;
12use core::str::FromStr;
13use serde::de::{
14 self, Deserialize, DeserializeSeed, EnumAccess, Expected, IntoDeserializer, MapAccess,
15 SeqAccess, Unexpected, VariantAccess, Visitor,
16};
17use serde::forward_to_deserialize_any;
18
19#[cfg(feature = "arbitrary_precision")]
20use crate::number::NumberFromString;
21
22impl<'de> Deserialize<'de> for Value {
23 #[inline]
24 fn deserialize<D>(deserializer: D) -> Result<Value, D::Error>
25 where
26 D: serde::Deserializer<'de>,
27 {
28 struct ValueVisitor;
29
30 impl<'de> Visitor<'de> for ValueVisitor {
31 type Value = Value;
32
33 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
34 formatter.write_str("any valid JSON value")
35 }
36
37 #[inline]
38 fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
39 Ok(Value::Bool(value))
40 }
41
42 #[inline]
43 fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
44 Ok(Value::Number(value.into()))
45 }
46
47 #[inline]
48 fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
49 Ok(Value::Number(value.into()))
50 }
51
52 #[inline]
53 fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
54 Ok(Number::from_f64(value).map_or(Value::Null, Value::Number))
55 }
56
57 #[cfg(any(feature = "std", feature = "alloc"))]
58 #[inline]
59 fn visit_str<E>(self, value: &str) -> Result<Value, E>
60 where
61 E: serde::de::Error,
62 {
63 self.visit_string(String::from(value))
64 }
65
66 #[cfg(any(feature = "std", feature = "alloc"))]
67 #[inline]
68 fn visit_string<E>(self, value: String) -> Result<Value, E> {
69 Ok(Value::String(value))
70 }
71
72 #[inline]
73 fn visit_none<E>(self) -> Result<Value, E> {
74 Ok(Value::Null)
75 }
76
77 #[inline]
78 fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error>
79 where
80 D: serde::Deserializer<'de>,
81 {
82 Deserialize::deserialize(deserializer)
83 }
84
85 #[inline]
86 fn visit_unit<E>(self) -> Result<Value, E> {
87 Ok(Value::Null)
88 }
89
90 #[inline]
91 fn visit_seq<V>(self, mut visitor: V) -> Result<Value, V::Error>
92 where
93 V: SeqAccess<'de>,
94 {
95 let mut vec = Vec::new();
96
97 while let Some(elem) = tri!(visitor.next_element()) {
98 vec.push(elem);
99 }
100
101 Ok(Value::Array(vec))
102 }
103
104 #[cfg(any(feature = "std", feature = "alloc"))]
105 fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error>
106 where
107 V: MapAccess<'de>,
108 {
109 match visitor.next_key_seed(KeyClassifier)? {
110 #[cfg(feature = "arbitrary_precision")]
111 Some(KeyClass::Number) => {
112 let number: NumberFromString = visitor.next_value()?;
113 Ok(Value::Number(number.value))
114 }
115 #[cfg(feature = "raw_value")]
116 Some(KeyClass::RawValue) => {
117 let value = visitor.next_value_seed(crate::raw::BoxedFromString)?;
118 crate::from_str(value.get()).map_err(de::Error::custom)
119 }
120 Some(KeyClass::Map(first_key)) => {
121 let mut values = Map::new();
122
123 values.insert(first_key, tri!(visitor.next_value()));
124 while let Some((key, value)) = tri!(visitor.next_entry()) {
125 values.insert(key, value);
126 }
127
128 Ok(Value::Object(values))
129 }
130 None => Ok(Value::Object(Map::new())),
131 }
132 }
133 }
134
135 deserializer.deserialize_any(ValueVisitor)
136 }
137}
138
139impl FromStr for Value {
140 type Err = Error;
141 fn from_str(s: &str) -> Result<Value, Error> {
142 super::super::de::from_str(s)
143 }
144}
145
146macro_rules! deserialize_number {
147 ($method:ident) => {
148 #[cfg(not(feature = "arbitrary_precision"))]
149 fn $method<V>(self, visitor: V) -> Result<V::Value, Error>
150 where
151 V: Visitor<'de>,
152 {
153 match self {
154 Value::Number(n) => n.deserialize_any(visitor),
155 _ => Err(self.invalid_type(&visitor)),
156 }
157 }
158
159 #[cfg(feature = "arbitrary_precision")]
160 fn $method<V>(self, visitor: V) -> Result<V::Value, Error>
161 where
162 V: Visitor<'de>,
163 {
164 match self {
165 Value::Number(n) => n.$method(visitor),
166 _ => self.deserialize_any(visitor),
167 }
168 }
169 };
170}
171
172fn visit_array<'de, V>(array: Vec<Value>, visitor: V) -> Result<V::Value, Error>
173where
174 V: Visitor<'de>,
175{
176 let len: usize = array.len();
177 let mut deserializer: SeqDeserializer = SeqDeserializer::new(vec:array);
178 let seq: ::Value = tri!(visitor.visit_seq(&mut deserializer));
179 let remaining: usize = deserializer.iter.len();
180 if remaining == 0 {
181 Ok(seq)
182 } else {
183 Err(serde::de::Error::invalid_length(
184 len,
185 &"fewer elements in array",
186 ))
187 }
188}
189
190fn visit_object<'de, V>(object: Map<String, Value>, visitor: V) -> Result<V::Value, Error>
191where
192 V: Visitor<'de>,
193{
194 let len: usize = object.len();
195 let mut deserializer: MapDeserializer = MapDeserializer::new(map:object);
196 let map: ::Value = tri!(visitor.visit_map(&mut deserializer));
197 let remaining: usize = deserializer.iter.len();
198 if remaining == 0 {
199 Ok(map)
200 } else {
201 Err(serde::de::Error::invalid_length(
202 len,
203 &"fewer elements in map",
204 ))
205 }
206}
207
208impl<'de> serde::Deserializer<'de> for Value {
209 type Error = Error;
210
211 #[inline]
212 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
213 where
214 V: Visitor<'de>,
215 {
216 match self {
217 Value::Null => visitor.visit_unit(),
218 Value::Bool(v) => visitor.visit_bool(v),
219 Value::Number(n) => n.deserialize_any(visitor),
220 #[cfg(any(feature = "std", feature = "alloc"))]
221 Value::String(v) => visitor.visit_string(v),
222 Value::Array(v) => visit_array(v, visitor),
223 Value::Object(v) => visit_object(v, visitor),
224 }
225 }
226
227 deserialize_number!(deserialize_i8);
228 deserialize_number!(deserialize_i16);
229 deserialize_number!(deserialize_i32);
230 deserialize_number!(deserialize_i64);
231 deserialize_number!(deserialize_i128);
232 deserialize_number!(deserialize_u8);
233 deserialize_number!(deserialize_u16);
234 deserialize_number!(deserialize_u32);
235 deserialize_number!(deserialize_u64);
236 deserialize_number!(deserialize_u128);
237 deserialize_number!(deserialize_f32);
238 deserialize_number!(deserialize_f64);
239
240 #[inline]
241 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
242 where
243 V: Visitor<'de>,
244 {
245 match self {
246 Value::Null => visitor.visit_none(),
247 _ => visitor.visit_some(self),
248 }
249 }
250
251 #[inline]
252 fn deserialize_enum<V>(
253 self,
254 _name: &str,
255 _variants: &'static [&'static str],
256 visitor: V,
257 ) -> Result<V::Value, Error>
258 where
259 V: Visitor<'de>,
260 {
261 let (variant, value) = match self {
262 Value::Object(value) => {
263 let mut iter = value.into_iter();
264 let (variant, value) = match iter.next() {
265 Some(v) => v,
266 None => {
267 return Err(serde::de::Error::invalid_value(
268 Unexpected::Map,
269 &"map with a single key",
270 ));
271 }
272 };
273 // enums are encoded in json as maps with a single key:value pair
274 if iter.next().is_some() {
275 return Err(serde::de::Error::invalid_value(
276 Unexpected::Map,
277 &"map with a single key",
278 ));
279 }
280 (variant, Some(value))
281 }
282 Value::String(variant) => (variant, None),
283 other => {
284 return Err(serde::de::Error::invalid_type(
285 other.unexpected(),
286 &"string or map",
287 ));
288 }
289 };
290
291 visitor.visit_enum(EnumDeserializer { variant, value })
292 }
293
294 #[inline]
295 fn deserialize_newtype_struct<V>(
296 self,
297 name: &'static str,
298 visitor: V,
299 ) -> Result<V::Value, Error>
300 where
301 V: Visitor<'de>,
302 {
303 #[cfg(feature = "raw_value")]
304 {
305 if name == crate::raw::TOKEN {
306 return visitor.visit_map(crate::raw::OwnedRawDeserializer {
307 raw_value: Some(self.to_string()),
308 });
309 }
310 }
311
312 let _ = name;
313 visitor.visit_newtype_struct(self)
314 }
315
316 fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Error>
317 where
318 V: Visitor<'de>,
319 {
320 match self {
321 Value::Bool(v) => visitor.visit_bool(v),
322 _ => Err(self.invalid_type(&visitor)),
323 }
324 }
325
326 fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Error>
327 where
328 V: Visitor<'de>,
329 {
330 self.deserialize_string(visitor)
331 }
332
333 fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Error>
334 where
335 V: Visitor<'de>,
336 {
337 self.deserialize_string(visitor)
338 }
339
340 fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Error>
341 where
342 V: Visitor<'de>,
343 {
344 match self {
345 #[cfg(any(feature = "std", feature = "alloc"))]
346 Value::String(v) => visitor.visit_string(v),
347 _ => Err(self.invalid_type(&visitor)),
348 }
349 }
350
351 fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Error>
352 where
353 V: Visitor<'de>,
354 {
355 self.deserialize_byte_buf(visitor)
356 }
357
358 fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Error>
359 where
360 V: Visitor<'de>,
361 {
362 match self {
363 #[cfg(any(feature = "std", feature = "alloc"))]
364 Value::String(v) => visitor.visit_string(v),
365 Value::Array(v) => visit_array(v, visitor),
366 _ => Err(self.invalid_type(&visitor)),
367 }
368 }
369
370 fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Error>
371 where
372 V: Visitor<'de>,
373 {
374 match self {
375 Value::Null => visitor.visit_unit(),
376 _ => Err(self.invalid_type(&visitor)),
377 }
378 }
379
380 fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value, Error>
381 where
382 V: Visitor<'de>,
383 {
384 self.deserialize_unit(visitor)
385 }
386
387 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Error>
388 where
389 V: Visitor<'de>,
390 {
391 match self {
392 Value::Array(v) => visit_array(v, visitor),
393 _ => Err(self.invalid_type(&visitor)),
394 }
395 }
396
397 fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error>
398 where
399 V: Visitor<'de>,
400 {
401 self.deserialize_seq(visitor)
402 }
403
404 fn deserialize_tuple_struct<V>(
405 self,
406 _name: &'static str,
407 _len: usize,
408 visitor: V,
409 ) -> Result<V::Value, Error>
410 where
411 V: Visitor<'de>,
412 {
413 self.deserialize_seq(visitor)
414 }
415
416 fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Error>
417 where
418 V: Visitor<'de>,
419 {
420 match self {
421 Value::Object(v) => visit_object(v, visitor),
422 _ => Err(self.invalid_type(&visitor)),
423 }
424 }
425
426 fn deserialize_struct<V>(
427 self,
428 _name: &'static str,
429 _fields: &'static [&'static str],
430 visitor: V,
431 ) -> Result<V::Value, Error>
432 where
433 V: Visitor<'de>,
434 {
435 match self {
436 Value::Array(v) => visit_array(v, visitor),
437 Value::Object(v) => visit_object(v, visitor),
438 _ => Err(self.invalid_type(&visitor)),
439 }
440 }
441
442 fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Error>
443 where
444 V: Visitor<'de>,
445 {
446 self.deserialize_string(visitor)
447 }
448
449 fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Error>
450 where
451 V: Visitor<'de>,
452 {
453 drop(self);
454 visitor.visit_unit()
455 }
456}
457
458struct EnumDeserializer {
459 variant: String,
460 value: Option<Value>,
461}
462
463impl<'de> EnumAccess<'de> for EnumDeserializer {
464 type Error = Error;
465 type Variant = VariantDeserializer;
466
467 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, VariantDeserializer), Error>
468 where
469 V: DeserializeSeed<'de>,
470 {
471 let variant: StringDeserializer = self.variant.into_deserializer();
472 let visitor: VariantDeserializer = VariantDeserializer { value: self.value };
473 seed.deserialize(variant).map(|v: ::Value| (v, visitor))
474 }
475}
476
477impl<'de> IntoDeserializer<'de, Error> for Value {
478 type Deserializer = Self;
479
480 fn into_deserializer(self) -> Self::Deserializer {
481 self
482 }
483}
484
485struct VariantDeserializer {
486 value: Option<Value>,
487}
488
489impl<'de> VariantAccess<'de> for VariantDeserializer {
490 type Error = Error;
491
492 fn unit_variant(self) -> Result<(), Error> {
493 match self.value {
494 Some(value) => Deserialize::deserialize(value),
495 None => Ok(()),
496 }
497 }
498
499 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error>
500 where
501 T: DeserializeSeed<'de>,
502 {
503 match self.value {
504 Some(value) => seed.deserialize(value),
505 None => Err(serde::de::Error::invalid_type(
506 Unexpected::UnitVariant,
507 &"newtype variant",
508 )),
509 }
510 }
511
512 fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error>
513 where
514 V: Visitor<'de>,
515 {
516 match self.value {
517 Some(Value::Array(v)) => {
518 if v.is_empty() {
519 visitor.visit_unit()
520 } else {
521 visit_array(v, visitor)
522 }
523 }
524 Some(other) => Err(serde::de::Error::invalid_type(
525 other.unexpected(),
526 &"tuple variant",
527 )),
528 None => Err(serde::de::Error::invalid_type(
529 Unexpected::UnitVariant,
530 &"tuple variant",
531 )),
532 }
533 }
534
535 fn struct_variant<V>(
536 self,
537 _fields: &'static [&'static str],
538 visitor: V,
539 ) -> Result<V::Value, Error>
540 where
541 V: Visitor<'de>,
542 {
543 match self.value {
544 Some(Value::Object(v)) => visit_object(v, visitor),
545 Some(other) => Err(serde::de::Error::invalid_type(
546 other.unexpected(),
547 &"struct variant",
548 )),
549 None => Err(serde::de::Error::invalid_type(
550 Unexpected::UnitVariant,
551 &"struct variant",
552 )),
553 }
554 }
555}
556
557struct SeqDeserializer {
558 iter: vec::IntoIter<Value>,
559}
560
561impl SeqDeserializer {
562 fn new(vec: Vec<Value>) -> Self {
563 SeqDeserializer {
564 iter: vec.into_iter(),
565 }
566 }
567}
568
569impl<'de> SeqAccess<'de> for SeqDeserializer {
570 type Error = Error;
571
572 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
573 where
574 T: DeserializeSeed<'de>,
575 {
576 match self.iter.next() {
577 Some(value: Value) => seed.deserialize(value).map(op:Some),
578 None => Ok(None),
579 }
580 }
581
582 fn size_hint(&self) -> Option<usize> {
583 match self.iter.size_hint() {
584 (lower: usize, Some(upper: usize)) if lower == upper => Some(upper),
585 _ => None,
586 }
587 }
588}
589
590struct MapDeserializer {
591 iter: <Map<String, Value> as IntoIterator>::IntoIter,
592 value: Option<Value>,
593}
594
595impl MapDeserializer {
596 fn new(map: Map<String, Value>) -> Self {
597 MapDeserializer {
598 iter: map.into_iter(),
599 value: None,
600 }
601 }
602}
603
604impl<'de> MapAccess<'de> for MapDeserializer {
605 type Error = Error;
606
607 fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
608 where
609 T: DeserializeSeed<'de>,
610 {
611 match self.iter.next() {
612 Some((key, value)) => {
613 self.value = Some(value);
614 let key_de = MapKeyDeserializer {
615 key: Cow::Owned(key),
616 };
617 seed.deserialize(key_de).map(Some)
618 }
619 None => Ok(None),
620 }
621 }
622
623 fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Error>
624 where
625 T: DeserializeSeed<'de>,
626 {
627 match self.value.take() {
628 Some(value) => seed.deserialize(value),
629 None => Err(serde::de::Error::custom("value is missing")),
630 }
631 }
632
633 fn size_hint(&self) -> Option<usize> {
634 match self.iter.size_hint() {
635 (lower, Some(upper)) if lower == upper => Some(upper),
636 _ => None,
637 }
638 }
639}
640
641macro_rules! deserialize_value_ref_number {
642 ($method:ident) => {
643 #[cfg(not(feature = "arbitrary_precision"))]
644 fn $method<V>(self, visitor: V) -> Result<V::Value, Error>
645 where
646 V: Visitor<'de>,
647 {
648 match self {
649 Value::Number(n) => n.deserialize_any(visitor),
650 _ => Err(self.invalid_type(&visitor)),
651 }
652 }
653
654 #[cfg(feature = "arbitrary_precision")]
655 fn $method<V>(self, visitor: V) -> Result<V::Value, Error>
656 where
657 V: Visitor<'de>,
658 {
659 match self {
660 Value::Number(n) => n.$method(visitor),
661 _ => self.deserialize_any(visitor),
662 }
663 }
664 };
665}
666
667fn visit_array_ref<'de, V>(array: &'de [Value], visitor: V) -> Result<V::Value, Error>
668where
669 V: Visitor<'de>,
670{
671 let len: usize = array.len();
672 let mut deserializer: SeqRefDeserializer<'_> = SeqRefDeserializer::new(slice:array);
673 let seq: ::Value = tri!(visitor.visit_seq(&mut deserializer));
674 let remaining: usize = deserializer.iter.len();
675 if remaining == 0 {
676 Ok(seq)
677 } else {
678 Err(serde::de::Error::invalid_length(
679 len,
680 &"fewer elements in array",
681 ))
682 }
683}
684
685fn visit_object_ref<'de, V>(object: &'de Map<String, Value>, visitor: V) -> Result<V::Value, Error>
686where
687 V: Visitor<'de>,
688{
689 let len: usize = object.len();
690 let mut deserializer: MapRefDeserializer<'_> = MapRefDeserializer::new(map:object);
691 let map: ::Value = tri!(visitor.visit_map(&mut deserializer));
692 let remaining: usize = deserializer.iter.len();
693 if remaining == 0 {
694 Ok(map)
695 } else {
696 Err(serde::de::Error::invalid_length(
697 len,
698 &"fewer elements in map",
699 ))
700 }
701}
702
703impl<'de> serde::Deserializer<'de> for &'de Value {
704 type Error = Error;
705
706 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
707 where
708 V: Visitor<'de>,
709 {
710 match self {
711 Value::Null => visitor.visit_unit(),
712 Value::Bool(v) => visitor.visit_bool(*v),
713 Value::Number(n) => n.deserialize_any(visitor),
714 Value::String(v) => visitor.visit_borrowed_str(v),
715 Value::Array(v) => visit_array_ref(v, visitor),
716 Value::Object(v) => visit_object_ref(v, visitor),
717 }
718 }
719
720 deserialize_value_ref_number!(deserialize_i8);
721 deserialize_value_ref_number!(deserialize_i16);
722 deserialize_value_ref_number!(deserialize_i32);
723 deserialize_value_ref_number!(deserialize_i64);
724 deserialize_number!(deserialize_i128);
725 deserialize_value_ref_number!(deserialize_u8);
726 deserialize_value_ref_number!(deserialize_u16);
727 deserialize_value_ref_number!(deserialize_u32);
728 deserialize_value_ref_number!(deserialize_u64);
729 deserialize_number!(deserialize_u128);
730 deserialize_value_ref_number!(deserialize_f32);
731 deserialize_value_ref_number!(deserialize_f64);
732
733 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
734 where
735 V: Visitor<'de>,
736 {
737 match *self {
738 Value::Null => visitor.visit_none(),
739 _ => visitor.visit_some(self),
740 }
741 }
742
743 fn deserialize_enum<V>(
744 self,
745 _name: &str,
746 _variants: &'static [&'static str],
747 visitor: V,
748 ) -> Result<V::Value, Error>
749 where
750 V: Visitor<'de>,
751 {
752 let (variant, value) = match self {
753 Value::Object(value) => {
754 let mut iter = value.into_iter();
755 let (variant, value) = match iter.next() {
756 Some(v) => v,
757 None => {
758 return Err(serde::de::Error::invalid_value(
759 Unexpected::Map,
760 &"map with a single key",
761 ));
762 }
763 };
764 // enums are encoded in json as maps with a single key:value pair
765 if iter.next().is_some() {
766 return Err(serde::de::Error::invalid_value(
767 Unexpected::Map,
768 &"map with a single key",
769 ));
770 }
771 (variant, Some(value))
772 }
773 Value::String(variant) => (variant, None),
774 other => {
775 return Err(serde::de::Error::invalid_type(
776 other.unexpected(),
777 &"string or map",
778 ));
779 }
780 };
781
782 visitor.visit_enum(EnumRefDeserializer { variant, value })
783 }
784
785 #[inline]
786 fn deserialize_newtype_struct<V>(
787 self,
788 name: &'static str,
789 visitor: V,
790 ) -> Result<V::Value, Error>
791 where
792 V: Visitor<'de>,
793 {
794 #[cfg(feature = "raw_value")]
795 {
796 if name == crate::raw::TOKEN {
797 return visitor.visit_map(crate::raw::OwnedRawDeserializer {
798 raw_value: Some(self.to_string()),
799 });
800 }
801 }
802
803 let _ = name;
804 visitor.visit_newtype_struct(self)
805 }
806
807 fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Error>
808 where
809 V: Visitor<'de>,
810 {
811 match *self {
812 Value::Bool(v) => visitor.visit_bool(v),
813 _ => Err(self.invalid_type(&visitor)),
814 }
815 }
816
817 fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Error>
818 where
819 V: Visitor<'de>,
820 {
821 self.deserialize_str(visitor)
822 }
823
824 fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Error>
825 where
826 V: Visitor<'de>,
827 {
828 match self {
829 Value::String(v) => visitor.visit_borrowed_str(v),
830 _ => Err(self.invalid_type(&visitor)),
831 }
832 }
833
834 fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Error>
835 where
836 V: Visitor<'de>,
837 {
838 self.deserialize_str(visitor)
839 }
840
841 fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Error>
842 where
843 V: Visitor<'de>,
844 {
845 match self {
846 Value::String(v) => visitor.visit_borrowed_str(v),
847 Value::Array(v) => visit_array_ref(v, visitor),
848 _ => Err(self.invalid_type(&visitor)),
849 }
850 }
851
852 fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Error>
853 where
854 V: Visitor<'de>,
855 {
856 self.deserialize_bytes(visitor)
857 }
858
859 fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Error>
860 where
861 V: Visitor<'de>,
862 {
863 match *self {
864 Value::Null => visitor.visit_unit(),
865 _ => Err(self.invalid_type(&visitor)),
866 }
867 }
868
869 fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value, Error>
870 where
871 V: Visitor<'de>,
872 {
873 self.deserialize_unit(visitor)
874 }
875
876 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Error>
877 where
878 V: Visitor<'de>,
879 {
880 match self {
881 Value::Array(v) => visit_array_ref(v, visitor),
882 _ => Err(self.invalid_type(&visitor)),
883 }
884 }
885
886 fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error>
887 where
888 V: Visitor<'de>,
889 {
890 self.deserialize_seq(visitor)
891 }
892
893 fn deserialize_tuple_struct<V>(
894 self,
895 _name: &'static str,
896 _len: usize,
897 visitor: V,
898 ) -> Result<V::Value, Error>
899 where
900 V: Visitor<'de>,
901 {
902 self.deserialize_seq(visitor)
903 }
904
905 fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Error>
906 where
907 V: Visitor<'de>,
908 {
909 match self {
910 Value::Object(v) => visit_object_ref(v, visitor),
911 _ => Err(self.invalid_type(&visitor)),
912 }
913 }
914
915 fn deserialize_struct<V>(
916 self,
917 _name: &'static str,
918 _fields: &'static [&'static str],
919 visitor: V,
920 ) -> Result<V::Value, Error>
921 where
922 V: Visitor<'de>,
923 {
924 match self {
925 Value::Array(v) => visit_array_ref(v, visitor),
926 Value::Object(v) => visit_object_ref(v, visitor),
927 _ => Err(self.invalid_type(&visitor)),
928 }
929 }
930
931 fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Error>
932 where
933 V: Visitor<'de>,
934 {
935 self.deserialize_str(visitor)
936 }
937
938 fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Error>
939 where
940 V: Visitor<'de>,
941 {
942 visitor.visit_unit()
943 }
944}
945
946struct EnumRefDeserializer<'de> {
947 variant: &'de str,
948 value: Option<&'de Value>,
949}
950
951impl<'de> EnumAccess<'de> for EnumRefDeserializer<'de> {
952 type Error = Error;
953 type Variant = VariantRefDeserializer<'de>;
954
955 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Error>
956 where
957 V: DeserializeSeed<'de>,
958 {
959 let variant: StrDeserializer<'_, Error> = self.variant.into_deserializer();
960 let visitor: VariantRefDeserializer<'_> = VariantRefDeserializer { value: self.value };
961 seed.deserialize(variant).map(|v: ::Value| (v, visitor))
962 }
963}
964
965struct VariantRefDeserializer<'de> {
966 value: Option<&'de Value>,
967}
968
969impl<'de> VariantAccess<'de> for VariantRefDeserializer<'de> {
970 type Error = Error;
971
972 fn unit_variant(self) -> Result<(), Error> {
973 match self.value {
974 Some(value) => Deserialize::deserialize(value),
975 None => Ok(()),
976 }
977 }
978
979 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error>
980 where
981 T: DeserializeSeed<'de>,
982 {
983 match self.value {
984 Some(value) => seed.deserialize(value),
985 None => Err(serde::de::Error::invalid_type(
986 Unexpected::UnitVariant,
987 &"newtype variant",
988 )),
989 }
990 }
991
992 fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error>
993 where
994 V: Visitor<'de>,
995 {
996 match self.value {
997 Some(Value::Array(v)) => {
998 if v.is_empty() {
999 visitor.visit_unit()
1000 } else {
1001 visit_array_ref(v, visitor)
1002 }
1003 }
1004 Some(other) => Err(serde::de::Error::invalid_type(
1005 other.unexpected(),
1006 &"tuple variant",
1007 )),
1008 None => Err(serde::de::Error::invalid_type(
1009 Unexpected::UnitVariant,
1010 &"tuple variant",
1011 )),
1012 }
1013 }
1014
1015 fn struct_variant<V>(
1016 self,
1017 _fields: &'static [&'static str],
1018 visitor: V,
1019 ) -> Result<V::Value, Error>
1020 where
1021 V: Visitor<'de>,
1022 {
1023 match self.value {
1024 Some(Value::Object(v)) => visit_object_ref(v, visitor),
1025 Some(other) => Err(serde::de::Error::invalid_type(
1026 other.unexpected(),
1027 &"struct variant",
1028 )),
1029 None => Err(serde::de::Error::invalid_type(
1030 Unexpected::UnitVariant,
1031 &"struct variant",
1032 )),
1033 }
1034 }
1035}
1036
1037struct SeqRefDeserializer<'de> {
1038 iter: slice::Iter<'de, Value>,
1039}
1040
1041impl<'de> SeqRefDeserializer<'de> {
1042 fn new(slice: &'de [Value]) -> Self {
1043 SeqRefDeserializer { iter: slice.iter() }
1044 }
1045}
1046
1047impl<'de> SeqAccess<'de> for SeqRefDeserializer<'de> {
1048 type Error = Error;
1049
1050 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
1051 where
1052 T: DeserializeSeed<'de>,
1053 {
1054 match self.iter.next() {
1055 Some(value: &Value) => seed.deserialize(value).map(op:Some),
1056 None => Ok(None),
1057 }
1058 }
1059
1060 fn size_hint(&self) -> Option<usize> {
1061 match self.iter.size_hint() {
1062 (lower: usize, Some(upper: usize)) if lower == upper => Some(upper),
1063 _ => None,
1064 }
1065 }
1066}
1067
1068struct MapRefDeserializer<'de> {
1069 iter: <&'de Map<String, Value> as IntoIterator>::IntoIter,
1070 value: Option<&'de Value>,
1071}
1072
1073impl<'de> MapRefDeserializer<'de> {
1074 fn new(map: &'de Map<String, Value>) -> Self {
1075 MapRefDeserializer {
1076 iter: map.into_iter(),
1077 value: None,
1078 }
1079 }
1080}
1081
1082impl<'de> MapAccess<'de> for MapRefDeserializer<'de> {
1083 type Error = Error;
1084
1085 fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
1086 where
1087 T: DeserializeSeed<'de>,
1088 {
1089 match self.iter.next() {
1090 Some((key, value)) => {
1091 self.value = Some(value);
1092 let key_de = MapKeyDeserializer {
1093 key: Cow::Borrowed(&**key),
1094 };
1095 seed.deserialize(key_de).map(Some)
1096 }
1097 None => Ok(None),
1098 }
1099 }
1100
1101 fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Error>
1102 where
1103 T: DeserializeSeed<'de>,
1104 {
1105 match self.value.take() {
1106 Some(value) => seed.deserialize(value),
1107 None => Err(serde::de::Error::custom("value is missing")),
1108 }
1109 }
1110
1111 fn size_hint(&self) -> Option<usize> {
1112 match self.iter.size_hint() {
1113 (lower, Some(upper)) if lower == upper => Some(upper),
1114 _ => None,
1115 }
1116 }
1117}
1118
1119struct MapKeyDeserializer<'de> {
1120 key: Cow<'de, str>,
1121}
1122
1123macro_rules! deserialize_integer_key {
1124 ($method:ident => $visit:ident) => {
1125 fn $method<V>(self, visitor: V) -> Result<V::Value, Error>
1126 where
1127 V: Visitor<'de>,
1128 {
1129 match (self.key.parse(), self.key) {
1130 (Ok(integer), _) => visitor.$visit(integer),
1131 (Err(_), Cow::Borrowed(s)) => visitor.visit_borrowed_str(s),
1132 #[cfg(any(feature = "std", feature = "alloc"))]
1133 (Err(_), Cow::Owned(s)) => visitor.visit_string(s),
1134 }
1135 }
1136 };
1137}
1138
1139impl<'de> serde::Deserializer<'de> for MapKeyDeserializer<'de> {
1140 type Error = Error;
1141
1142 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
1143 where
1144 V: Visitor<'de>,
1145 {
1146 BorrowedCowStrDeserializer::new(self.key).deserialize_any(visitor)
1147 }
1148
1149 deserialize_integer_key!(deserialize_i8 => visit_i8);
1150 deserialize_integer_key!(deserialize_i16 => visit_i16);
1151 deserialize_integer_key!(deserialize_i32 => visit_i32);
1152 deserialize_integer_key!(deserialize_i64 => visit_i64);
1153 deserialize_integer_key!(deserialize_i128 => visit_i128);
1154 deserialize_integer_key!(deserialize_u8 => visit_u8);
1155 deserialize_integer_key!(deserialize_u16 => visit_u16);
1156 deserialize_integer_key!(deserialize_u32 => visit_u32);
1157 deserialize_integer_key!(deserialize_u64 => visit_u64);
1158 deserialize_integer_key!(deserialize_u128 => visit_u128);
1159
1160 #[inline]
1161 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
1162 where
1163 V: Visitor<'de>,
1164 {
1165 // Map keys cannot be null.
1166 visitor.visit_some(self)
1167 }
1168
1169 #[inline]
1170 fn deserialize_newtype_struct<V>(
1171 self,
1172 _name: &'static str,
1173 visitor: V,
1174 ) -> Result<V::Value, Error>
1175 where
1176 V: Visitor<'de>,
1177 {
1178 visitor.visit_newtype_struct(self)
1179 }
1180
1181 fn deserialize_enum<V>(
1182 self,
1183 name: &'static str,
1184 variants: &'static [&'static str],
1185 visitor: V,
1186 ) -> Result<V::Value, Error>
1187 where
1188 V: Visitor<'de>,
1189 {
1190 self.key
1191 .into_deserializer()
1192 .deserialize_enum(name, variants, visitor)
1193 }
1194
1195 forward_to_deserialize_any! {
1196 bool f32 f64 char str string bytes byte_buf unit unit_struct seq tuple
1197 tuple_struct map struct identifier ignored_any
1198 }
1199}
1200
1201struct KeyClassifier;
1202
1203enum KeyClass {
1204 Map(String),
1205 #[cfg(feature = "arbitrary_precision")]
1206 Number,
1207 #[cfg(feature = "raw_value")]
1208 RawValue,
1209}
1210
1211impl<'de> DeserializeSeed<'de> for KeyClassifier {
1212 type Value = KeyClass;
1213
1214 fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1215 where
1216 D: serde::Deserializer<'de>,
1217 {
1218 deserializer.deserialize_str(self)
1219 }
1220}
1221
1222impl<'de> Visitor<'de> for KeyClassifier {
1223 type Value = KeyClass;
1224
1225 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1226 formatter.write_str("a string key")
1227 }
1228
1229 fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
1230 where
1231 E: de::Error,
1232 {
1233 match s {
1234 #[cfg(feature = "arbitrary_precision")]
1235 crate::number::TOKEN => Ok(KeyClass::Number),
1236 #[cfg(feature = "raw_value")]
1237 crate::raw::TOKEN => Ok(KeyClass::RawValue),
1238 _ => Ok(KeyClass::Map(s.to_owned())),
1239 }
1240 }
1241
1242 #[cfg(any(feature = "std", feature = "alloc"))]
1243 fn visit_string<E>(self, s: String) -> Result<Self::Value, E>
1244 where
1245 E: de::Error,
1246 {
1247 match s.as_str() {
1248 #[cfg(feature = "arbitrary_precision")]
1249 crate::number::TOKEN => Ok(KeyClass::Number),
1250 #[cfg(feature = "raw_value")]
1251 crate::raw::TOKEN => Ok(KeyClass::RawValue),
1252 _ => Ok(KeyClass::Map(s)),
1253 }
1254 }
1255}
1256
1257impl Value {
1258 #[cold]
1259 fn invalid_type<E>(&self, exp: &dyn Expected) -> E
1260 where
1261 E: serde::de::Error,
1262 {
1263 serde::de::Error::invalid_type(self.unexpected(), exp)
1264 }
1265
1266 #[cold]
1267 fn unexpected(&self) -> Unexpected {
1268 match self {
1269 Value::Null => Unexpected::Unit,
1270 Value::Bool(b: &bool) => Unexpected::Bool(*b),
1271 Value::Number(n: &Number) => n.unexpected(),
1272 Value::String(s: &String) => Unexpected::Str(s),
1273 Value::Array(_) => Unexpected::Seq,
1274 Value::Object(_) => Unexpected::Map,
1275 }
1276 }
1277}
1278
1279struct BorrowedCowStrDeserializer<'de> {
1280 value: Cow<'de, str>,
1281}
1282
1283impl<'de> BorrowedCowStrDeserializer<'de> {
1284 fn new(value: Cow<'de, str>) -> Self {
1285 BorrowedCowStrDeserializer { value }
1286 }
1287}
1288
1289impl<'de> de::Deserializer<'de> for BorrowedCowStrDeserializer<'de> {
1290 type Error = Error;
1291
1292 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
1293 where
1294 V: de::Visitor<'de>,
1295 {
1296 match self.value {
1297 Cow::Borrowed(string) => visitor.visit_borrowed_str(string),
1298 #[cfg(any(feature = "std", feature = "alloc"))]
1299 Cow::Owned(string) => visitor.visit_string(string),
1300 }
1301 }
1302
1303 fn deserialize_enum<V>(
1304 self,
1305 _name: &str,
1306 _variants: &'static [&'static str],
1307 visitor: V,
1308 ) -> Result<V::Value, Error>
1309 where
1310 V: de::Visitor<'de>,
1311 {
1312 visitor.visit_enum(self)
1313 }
1314
1315 forward_to_deserialize_any! {
1316 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
1317 bytes byte_buf option unit unit_struct newtype_struct seq tuple
1318 tuple_struct map struct identifier ignored_any
1319 }
1320}
1321
1322impl<'de> de::EnumAccess<'de> for BorrowedCowStrDeserializer<'de> {
1323 type Error = Error;
1324 type Variant = UnitOnly;
1325
1326 fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Error>
1327 where
1328 T: de::DeserializeSeed<'de>,
1329 {
1330 let value: ::Value = seed.deserialize(self)?;
1331 Ok((value, UnitOnly))
1332 }
1333}
1334
1335struct UnitOnly;
1336
1337impl<'de> de::VariantAccess<'de> for UnitOnly {
1338 type Error = Error;
1339
1340 fn unit_variant(self) -> Result<(), Error> {
1341 Ok(())
1342 }
1343
1344 fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Error>
1345 where
1346 T: de::DeserializeSeed<'de>,
1347 {
1348 Err(de::Error::invalid_type(
1349 Unexpected::UnitVariant,
1350 &"newtype variant",
1351 ))
1352 }
1353
1354 fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Error>
1355 where
1356 V: de::Visitor<'de>,
1357 {
1358 Err(de::Error::invalid_type(
1359 Unexpected::UnitVariant,
1360 &"tuple variant",
1361 ))
1362 }
1363
1364 fn struct_variant<V>(
1365 self,
1366 _fields: &'static [&'static str],
1367 _visitor: V,
1368 ) -> Result<V::Value, Error>
1369 where
1370 V: de::Visitor<'de>,
1371 {
1372 Err(de::Error::invalid_type(
1373 Unexpected::UnitVariant,
1374 &"struct variant",
1375 ))
1376 }
1377}
1378