simd_json/serde/value/owned/
de.rs

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