Skip to main content

simd_json/serde/value/borrowed/
de.rs

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