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