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