scale_value/serde_impls/
deserializer.rs

1// Copyright (C) 2022-2023 Parity Technologies (UK) Ltd. (admin@parity.io)
2// This file is a part of the scale-value crate.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//         http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! This module implements the [`Deserializer`] (note the 'r') trait on our Value enum.
17//!
18//! A deserializer is a thing which implements methods like `deserialize_i128`. Each of these
19//! methods serves as a hint about what the thing calling it (probably a thing implementing
20//! [`Deserialize`]) actually wants back. The methods are given a "visitor" which actually accepts
21//! values back. We might not give the visitor back the value that it hinted that it wanted, but
22//! it's up to the visitor to do its best to accept what it's handed, or reject it if it's simply
23//! not going to work out.
24
25use super::bitvec_helpers;
26use crate::prelude::*;
27use crate::{Composite, Primitive, Value, ValueDef, Variant};
28use alloc::{borrow::Cow, fmt::Display};
29use serde::{
30    de::{self, EnumAccess, IntoDeserializer, VariantAccess},
31    forward_to_deserialize_any, ser, Deserialize, Deserializer,
32};
33
34/// An opaque error to describe in human terms what went wrong.
35/// Many internal serialization/deserialization errors are relayed
36/// to this in string form, and so we use basic strings for custom
37/// errors as well for simplicity.
38#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
39#[error("{0}")]
40pub struct DeserializerError(Cow<'static, str>);
41
42impl DeserializerError {
43    fn from_string<S: Into<String>>(s: S) -> DeserializerError {
44        DeserializerError(Cow::Owned(s.into()))
45    }
46    fn from_str(s: &'static str) -> DeserializerError {
47        DeserializerError(Cow::Borrowed(s))
48    }
49}
50
51impl de::Error for DeserializerError {
52    fn custom<T: Display>(msg: T) -> Self {
53        DeserializerError::from_string(msg.to_string())
54    }
55}
56impl ser::Error for DeserializerError {
57    fn custom<T: Display>(msg: T) -> Self {
58        DeserializerError::from_string(msg.to_string())
59    }
60}
61
62/// Spit out the simple deserialize methods to avoid loads of repetition.
63macro_rules! deserialize_x {
64    ($fn_name:ident) => {
65        fn $fn_name<V>(self, visitor: V) -> Result<V::Value, Self::Error>
66        where
67            V: de::Visitor<'de>,
68        {
69            self.value.$fn_name(visitor)
70        }
71    };
72}
73
74// Our Value type has some context, which we ignore, and some definition, whose deserializer
75// impl we forward to.
76impl<'de, T> Deserializer<'de> for Value<T> {
77    type Error = DeserializerError;
78
79    deserialize_x!(deserialize_any);
80    deserialize_x!(deserialize_bool);
81    deserialize_x!(deserialize_i8);
82    deserialize_x!(deserialize_i16);
83    deserialize_x!(deserialize_i32);
84    deserialize_x!(deserialize_i64);
85    deserialize_x!(deserialize_i128);
86    deserialize_x!(deserialize_u8);
87    deserialize_x!(deserialize_u16);
88    deserialize_x!(deserialize_u32);
89    deserialize_x!(deserialize_u64);
90    deserialize_x!(deserialize_u128);
91    deserialize_x!(deserialize_f32);
92    deserialize_x!(deserialize_f64);
93    deserialize_x!(deserialize_char);
94    deserialize_x!(deserialize_str);
95    deserialize_x!(deserialize_string);
96    deserialize_x!(deserialize_bytes);
97    deserialize_x!(deserialize_byte_buf);
98    deserialize_x!(deserialize_option);
99    deserialize_x!(deserialize_unit);
100    deserialize_x!(deserialize_seq);
101    deserialize_x!(deserialize_map);
102    deserialize_x!(deserialize_identifier);
103    deserialize_x!(deserialize_ignored_any);
104
105    fn deserialize_unit_struct<V>(
106        self,
107        name: &'static str,
108        visitor: V,
109    ) -> Result<V::Value, Self::Error>
110    where
111        V: de::Visitor<'de>,
112    {
113        self.value.deserialize_unit_struct(name, visitor)
114    }
115
116    fn deserialize_newtype_struct<V>(
117        self,
118        name: &'static str,
119        visitor: V,
120    ) -> Result<V::Value, Self::Error>
121    where
122        V: de::Visitor<'de>,
123    {
124        self.value.deserialize_newtype_struct(name, visitor)
125    }
126
127    fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
128    where
129        V: de::Visitor<'de>,
130    {
131        self.value.deserialize_tuple(len, visitor)
132    }
133
134    fn deserialize_tuple_struct<V>(
135        self,
136        name: &'static str,
137        len: usize,
138        visitor: V,
139    ) -> Result<V::Value, Self::Error>
140    where
141        V: de::Visitor<'de>,
142    {
143        self.value.deserialize_tuple_struct(name, len, visitor)
144    }
145
146    fn deserialize_struct<V>(
147        self,
148        name: &'static str,
149        fields: &'static [&'static str],
150        visitor: V,
151    ) -> Result<V::Value, Self::Error>
152    where
153        V: de::Visitor<'de>,
154    {
155        self.value.deserialize_struct(name, fields, visitor)
156    }
157
158    fn deserialize_enum<V>(
159        self,
160        name: &'static str,
161        variants: &'static [&'static str],
162        visitor: V,
163    ) -> Result<V::Value, Self::Error>
164    where
165        V: de::Visitor<'de>,
166    {
167        self.value.deserialize_enum(name, variants, visitor)
168    }
169}
170
171// Our ValueDef deserializer needs to handle BitSeq itself, but otherwise delegates to
172// the inner implementations of things to handle. This macro makes that less repetitive
173// to write by only requiring a bitseq impl.
174macro_rules! delegate_except_bitseq {
175    (
176        $name:ident ( $self:ident, $($arg:ident),* ),
177            $seq:pat => $expr:expr
178    ) => {
179        match $self {
180            ValueDef::BitSequence($seq) => {
181                $expr
182            },
183            ValueDef::Composite(composite) => {
184                composite.$name( $($arg),* )
185            },
186            ValueDef::Variant(variant) => {
187                variant.$name( $($arg),* )
188            },
189            ValueDef::Primitive(prim) => {
190                prim.$name( $($arg),* )
191            },
192        }
193    }
194}
195
196macro_rules! delegate_method {
197    ($name:ident $ty:ident) => {
198        fn $name<V>(self, visitor: V) -> Result<V::Value, Self::Error>
199        where
200            V: serde::de::Visitor<'de>,
201        {
202            delegate_except_bitseq! { $name(self, visitor),
203                seq => {
204                    let map = bitvec_helpers::map_access(seq);
205                    visitor.visit_map(map)
206                }
207            }
208        }
209    };
210}
211
212// The goal here is simply to forward deserialization methods of interest to
213// the relevant subtype. The exception is our BitSequence type, which doesn't
214// have a sub type to forward to and so is handled here.
215impl<'de, T> Deserializer<'de> for ValueDef<T> {
216    type Error = DeserializerError;
217
218    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
219    where
220        V: serde::de::Visitor<'de>,
221    {
222        delegate_except_bitseq! { deserialize_any(self, visitor),
223            seq => {
224                let map = bitvec_helpers::map_access(seq);
225                visitor.visit_map(map)
226            }
227        }
228    }
229
230    delegate_method!(deserialize_u8 u8);
231    delegate_method!(deserialize_u16 u16);
232    delegate_method!(deserialize_u32 u32);
233    delegate_method!(deserialize_u64 u64);
234    delegate_method!(deserialize_u128 u128);
235    delegate_method!(deserialize_i8 i8);
236    delegate_method!(deserialize_i16 i16);
237    delegate_method!(deserialize_i32 i32);
238    delegate_method!(deserialize_i64 i64);
239    delegate_method!(deserialize_i128 i128);
240    delegate_method!(deserialize_bool bool);
241    delegate_method!(deserialize_f32 f32);
242    delegate_method!(deserialize_f64 f64);
243    delegate_method!(deserialize_char char);
244    delegate_method!(deserialize_str str);
245    delegate_method!(deserialize_string String);
246
247    fn deserialize_newtype_struct<V>(
248        self,
249        name: &'static str,
250        visitor: V,
251    ) -> Result<V::Value, Self::Error>
252    where
253        V: de::Visitor<'de>,
254    {
255        delegate_except_bitseq! { deserialize_newtype_struct(self, name, visitor),
256            _ => {
257                Err(DeserializerError::from_str("Cannot deserialize BitSequence into a newtype struct"))
258            }
259        }
260    }
261
262    fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
263    where
264        V: de::Visitor<'de>,
265    {
266        delegate_except_bitseq! { deserialize_tuple(self, len, visitor),
267            _ => {
268                Err(DeserializerError::from_str("Cannot deserialize BitSequence into a tuple"))
269            }
270        }
271    }
272
273    fn deserialize_tuple_struct<V>(
274        self,
275        name: &'static str,
276        len: usize,
277        visitor: V,
278    ) -> Result<V::Value, Self::Error>
279    where
280        V: de::Visitor<'de>,
281    {
282        delegate_except_bitseq! { deserialize_tuple_struct(self, name, len, visitor),
283            _ => {
284                Err(DeserializerError::from_str("Cannot deserialize BitSequence into a tuple struct"))
285            }
286        }
287    }
288
289    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
290    where
291        V: de::Visitor<'de>,
292    {
293        delegate_except_bitseq! { deserialize_unit(self, visitor),
294            _ => {
295                Err(DeserializerError::from_str("Cannot deserialize BitSequence into a ()"))
296            }
297        }
298    }
299
300    fn deserialize_unit_struct<V>(
301        self,
302        name: &'static str,
303        visitor: V,
304    ) -> Result<V::Value, Self::Error>
305    where
306        V: de::Visitor<'de>,
307    {
308        delegate_except_bitseq! { deserialize_unit_struct(self, name, visitor),
309            _ => {
310                Err(DeserializerError::from_string(format!("Cannot deserialize BitSequence into the unit struct {name}")))
311            }
312        }
313    }
314
315    fn deserialize_enum<V>(
316        self,
317        name: &'static str,
318        variants: &'static [&'static str],
319        visitor: V,
320    ) -> Result<V::Value, Self::Error>
321    where
322        V: de::Visitor<'de>,
323    {
324        delegate_except_bitseq! { deserialize_enum(self, name, variants, visitor),
325            _ => {
326                Err(DeserializerError::from_string(format!("Cannot deserialize BitSequence into the enum {name}")))
327            }
328        }
329    }
330
331    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
332    where
333        V: de::Visitor<'de>,
334    {
335        delegate_except_bitseq! { deserialize_bytes(self, visitor),
336            _ => {
337                Err(DeserializerError::from_str("Cannot deserialize BitSequence into raw bytes"))
338            }
339        }
340    }
341
342    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
343    where
344        V: de::Visitor<'de>,
345    {
346        delegate_except_bitseq! { deserialize_byte_buf(self, visitor),
347            _ => {
348                Err(DeserializerError::from_str("Cannot deserialize BitSequence into raw bytes"))
349            }
350        }
351    }
352
353    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
354    where
355        V: de::Visitor<'de>,
356    {
357        delegate_except_bitseq! { deserialize_seq(self, visitor),
358            _ => {
359                Err(DeserializerError::from_str("Cannot deserialize BitSequence into a sequence"))
360            }
361        }
362    }
363
364    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
365    where
366        V: de::Visitor<'de>,
367    {
368        delegate_except_bitseq! { deserialize_map(self, visitor),
369            _ => {
370                Err(DeserializerError::from_str("Cannot deserialize BitSequence into a map"))
371            }
372        }
373    }
374
375    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
376    where
377        V: de::Visitor<'de>,
378    {
379        // Special handling to turn a variant value of "Some" or "None" into an option.
380        if let ValueDef::Variant(Variant { name, values: Composite::Unnamed(mut vs) }) = self {
381            if name == "Some" && vs.len() == 1 {
382                visitor.visit_some(vs.pop().expect("length checked"))
383            } else if name == "None" && vs.is_empty() {
384                visitor.visit_none()
385            } else {
386                // Reconstruct the variant and try to deserialize without the option hint:
387                ValueDef::Variant(Variant { name, values: Composite::Unnamed(vs) })
388                    .deserialize_any(visitor)
389            }
390        } else {
391            // fall back to deserializing based on the value type if it doesn't look like an Option:
392            self.deserialize_any(visitor)
393        }
394    }
395
396    // None of the sub types particularly care about these, so we just allow them to forward to
397    // deserialize_any and go from there.
398    forward_to_deserialize_any! {
399        struct identifier ignored_any
400    }
401}
402
403impl<'de, T> IntoDeserializer<'de, DeserializerError> for Value<T> {
404    type Deserializer = Value<T>;
405    fn into_deserializer(self) -> Self::Deserializer {
406        self
407    }
408}
409
410impl<'de, T> Deserializer<'de> for Composite<T> {
411    type Error = DeserializerError;
412
413    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
414    where
415        V: serde::de::Visitor<'de>,
416    {
417        match self {
418            Composite::Named(values) => {
419                visitor.visit_map(de::value::MapDeserializer::new(values.into_iter()))
420            }
421            Composite::Unnamed(values) => {
422                visitor.visit_seq(de::value::SeqDeserializer::new(values.into_iter()))
423            }
424        }
425    }
426
427    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
428    where
429        V: de::Visitor<'de>,
430    {
431        match self {
432            Composite::Named(values) => visitor
433                .visit_seq(de::value::SeqDeserializer::new(values.into_iter().map(|(_, v)| v))),
434            Composite::Unnamed(values) => {
435                visitor.visit_seq(de::value::SeqDeserializer::new(values.into_iter()))
436            }
437        }
438    }
439
440    fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
441    where
442        V: de::Visitor<'de>,
443    {
444        match self {
445            // A sequence of named values? just ignores the names:
446            Composite::Named(values) => {
447                if values.len() != len {
448                    return Err(DeserializerError::from_string(format!(
449                        "Cannot deserialize composite of length {} into tuple of length {}",
450                        values.len(),
451                        len
452                    )));
453                }
454                visitor
455                    .visit_seq(de::value::SeqDeserializer::new(values.into_iter().map(|(_, v)| v)))
456            }
457            // A sequence of unnamed values is ideal:
458            Composite::Unnamed(values) => {
459                if values.len() != len {
460                    return Err(DeserializerError::from_string(format!(
461                        "Cannot deserialize composite of length {} into tuple of length {}",
462                        values.len(),
463                        len
464                    )));
465                }
466                visitor.visit_seq(de::value::SeqDeserializer::new(values.into_iter()))
467            }
468        }
469    }
470
471    fn deserialize_tuple_struct<V>(
472        self,
473        _name: &'static str,
474        len: usize,
475        visitor: V,
476    ) -> Result<V::Value, Self::Error>
477    where
478        V: de::Visitor<'de>,
479    {
480        self.deserialize_tuple(len, visitor)
481    }
482
483    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
484    where
485        V: de::Visitor<'de>,
486    {
487        // 0 length composite types can be treated as the unit type:
488        if self.is_empty() {
489            visitor.visit_unit()
490        } else {
491            Err(DeserializerError::from_str(
492                "Cannot deserialize non-empty Composite into a unit value",
493            ))
494        }
495    }
496
497    fn deserialize_unit_struct<V>(
498        self,
499        _name: &'static str,
500        visitor: V,
501    ) -> Result<V::Value, Self::Error>
502    where
503        V: de::Visitor<'de>,
504    {
505        self.deserialize_unit(visitor)
506    }
507
508    fn deserialize_newtype_struct<V>(
509        self,
510        _name: &'static str,
511        visitor: V,
512    ) -> Result<V::Value, Self::Error>
513    where
514        V: de::Visitor<'de>,
515    {
516        visitor.visit_seq(de::value::SeqDeserializer::new(Some(self).into_iter()))
517    }
518
519    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
520    where
521        V: de::Visitor<'de>,
522    {
523        let bytes = self.into_values().map(|v| {
524            match v.value {
525                ValueDef::Primitive(Primitive::U128(n)) => {
526                    n.try_into()
527                     .map_err(|_| DeserializerError::from_str("Cannot deserialize composite that is not entirely U8's into bytes (number out of range)"))
528                },
529                _ => {
530                    Err(DeserializerError::from_str(
531                        "Cannot deserialize composite that is not entirely U8's into bytes (non-numeric values encountered)",
532                    ))
533                }
534            }
535        }).collect::<Result<Vec<u8>, _>>()?;
536        visitor.visit_byte_buf(bytes)
537    }
538
539    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
540    where
541        V: de::Visitor<'de>,
542    {
543        self.deserialize_byte_buf(visitor)
544    }
545
546    forward_to_deserialize_any! {
547        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
548        option struct map
549        enum identifier ignored_any
550    }
551}
552
553impl<'de, T> IntoDeserializer<'de, DeserializerError> for Composite<T> {
554    type Deserializer = Composite<T>;
555    fn into_deserializer(self) -> Self::Deserializer {
556        self
557    }
558}
559
560// Because composite types are used to represent variant fields, we allow
561// variant accesses to be called on it, which just delegate to methods defined above.
562impl<'de, T> VariantAccess<'de> for Composite<T> {
563    type Error = DeserializerError;
564
565    fn unit_variant(self) -> Result<(), Self::Error> {
566        Deserialize::deserialize(self)
567    }
568
569    fn newtype_variant_seed<S>(self, seed: S) -> Result<S::Value, Self::Error>
570    where
571        S: de::DeserializeSeed<'de>,
572    {
573        seed.deserialize(self)
574    }
575
576    fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
577    where
578        V: de::Visitor<'de>,
579    {
580        self.deserialize_tuple(len, visitor)
581    }
582
583    fn struct_variant<V>(
584        self,
585        _fields: &'static [&'static str],
586        visitor: V,
587    ) -> Result<V::Value, Self::Error>
588    where
589        V: de::Visitor<'de>,
590    {
591        self.deserialize_any(visitor)
592    }
593}
594
595impl<'de, T> Deserializer<'de> for Variant<T> {
596    type Error = DeserializerError;
597
598    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
599    where
600        V: serde::de::Visitor<'de>,
601    {
602        visitor.visit_enum(self)
603    }
604
605    fn deserialize_enum<V>(
606        self,
607        _name: &'static str,
608        _variants: &'static [&'static str],
609        visitor: V,
610    ) -> Result<V::Value, Self::Error>
611    where
612        V: de::Visitor<'de>,
613    {
614        visitor.visit_enum(self)
615    }
616
617    fn deserialize_newtype_struct<V>(
618        self,
619        _name: &'static str,
620        visitor: V,
621    ) -> Result<V::Value, Self::Error>
622    where
623        V: de::Visitor<'de>,
624    {
625        visitor.visit_seq(de::value::SeqDeserializer::new(Some(self).into_iter()))
626    }
627
628    // All of the below functions delegate to the Composite deserializing methods using the enum values.
629
630    fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
631    where
632        V: de::Visitor<'de>,
633    {
634        self.values.deserialize_tuple(len, visitor)
635    }
636
637    fn deserialize_tuple_struct<V>(
638        self,
639        name: &'static str,
640        len: usize,
641        visitor: V,
642    ) -> Result<V::Value, Self::Error>
643    where
644        V: de::Visitor<'de>,
645    {
646        self.values.deserialize_tuple_struct(name, len, visitor)
647    }
648
649    fn deserialize_unit_struct<V>(
650        self,
651        name: &'static str,
652        visitor: V,
653    ) -> Result<V::Value, Self::Error>
654    where
655        V: de::Visitor<'de>,
656    {
657        self.values.deserialize_unit_struct(name, visitor)
658    }
659
660    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
661    where
662        V: de::Visitor<'de>,
663    {
664        self.values.deserialize_unit(visitor)
665    }
666
667    fn deserialize_struct<V>(
668        self,
669        name: &'static str,
670        fields: &'static [&'static str],
671        visitor: V,
672    ) -> Result<V::Value, Self::Error>
673    where
674        V: de::Visitor<'de>,
675    {
676        self.values.deserialize_struct(name, fields, visitor)
677    }
678
679    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
680    where
681        V: de::Visitor<'de>,
682    {
683        self.values.deserialize_map(visitor)
684    }
685
686    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
687    where
688        V: de::Visitor<'de>,
689    {
690        self.values.deserialize_seq(visitor)
691    }
692
693    forward_to_deserialize_any! {
694        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
695        bytes byte_buf option identifier ignored_any
696    }
697}
698
699impl<'de, T> IntoDeserializer<'de, DeserializerError> for Variant<T> {
700    type Deserializer = Variant<T>;
701    fn into_deserializer(self) -> Self::Deserializer {
702        self
703    }
704}
705
706// Variant types can be treated as serde enums. Here we just hand back
707// the pair of name and values, where values is a composite type that impls
708// VariantAccess to actually allow deserializing of those values.
709impl<'de, T> EnumAccess<'de> for Variant<T> {
710    type Error = DeserializerError;
711
712    type Variant = Composite<T>;
713
714    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
715    where
716        V: de::DeserializeSeed<'de>,
717    {
718        let name = self.name.into_deserializer();
719        let values = self.values;
720        seed.deserialize(name).map(|name| (name, values))
721    }
722}
723
724macro_rules! deserialize_number {
725    ($name:ident $visit_fn:ident) => {
726        fn $name<V>(self, visitor: V) -> Result<V::Value, Self::Error>
727        where
728            V: de::Visitor<'de>,
729        {
730            match self {
731                Primitive::U128(n) => match n.try_into() {
732                    Ok(val) => visitor.$visit_fn(val),
733                    Err(_) => self.deserialize_any(visitor),
734                },
735                Primitive::I128(n) => match n.try_into() {
736                    Ok(val) => visitor.$visit_fn(val),
737                    Err(_) => self.deserialize_any(visitor),
738                },
739                _ => self.deserialize_any(visitor),
740            }
741        }
742    };
743}
744
745impl<'de> Deserializer<'de> for Primitive {
746    type Error = DeserializerError;
747
748    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
749    where
750        V: serde::de::Visitor<'de>,
751    {
752        match self {
753            Primitive::Bool(v) => visitor.visit_bool(v),
754            Primitive::Char(v) => visitor.visit_char(v),
755            Primitive::String(v) => visitor.visit_string(v),
756            Primitive::U128(v) => visitor.visit_u128(v),
757            Primitive::U256(v) => visitor.visit_bytes(&v),
758            Primitive::I128(v) => visitor.visit_i128(v),
759            Primitive::I256(v) => visitor.visit_bytes(&v),
760        }
761    }
762
763    // if we're asked to deserialize into some numeric type,
764    // we do our best to visit that same type with a value, but
765    // if we can't coerce our value to it, we fall back to
766    // deserialize_any.
767    deserialize_number!(deserialize_u8 visit_u8);
768    deserialize_number!(deserialize_u16 visit_u16);
769    deserialize_number!(deserialize_u32 visit_u32);
770    deserialize_number!(deserialize_u64 visit_u64);
771    deserialize_number!(deserialize_u128 visit_u128);
772    deserialize_number!(deserialize_i8 visit_i8);
773    deserialize_number!(deserialize_i16 visit_i16);
774    deserialize_number!(deserialize_i32 visit_i32);
775    deserialize_number!(deserialize_i64 visit_i64);
776    deserialize_number!(deserialize_i128 visit_i128);
777
778    fn deserialize_newtype_struct<V>(
779        self,
780        _name: &'static str,
781        visitor: V,
782    ) -> Result<V::Value, Self::Error>
783    where
784        V: de::Visitor<'de>,
785    {
786        visitor.visit_seq(de::value::SeqDeserializer::new(Some(self).into_iter()))
787    }
788
789    forward_to_deserialize_any! {
790        bool f32 f64 char str string
791        bytes byte_buf option unit unit_struct seq tuple
792        tuple_struct map struct enum identifier ignored_any
793    }
794}
795
796impl<'de> IntoDeserializer<'de, DeserializerError> for Primitive {
797    type Deserializer = Primitive;
798    fn into_deserializer(self) -> Self::Deserializer {
799        self
800    }
801}
802
803#[cfg(test)]
804mod test {
805    use crate::value;
806
807    use super::*;
808    use serde::Deserialize;
809
810    #[test]
811    fn de_into_struct() {
812        #[derive(Deserialize, Debug, PartialEq)]
813        struct Foo {
814            a: u8,
815            b: bool,
816        }
817
818        let val = ValueDef::Composite(Composite::Named(vec![
819            // Order shouldn't matter; match on names:
820            ("b".into(), Value::bool(true)),
821            ("a".into(), Value::u128(123)),
822        ]));
823
824        assert_eq!(Foo::deserialize(val), Ok(Foo { a: 123, b: true }))
825    }
826
827    #[test]
828    fn de_unwrapped_into_struct() {
829        #[derive(Deserialize, Debug, PartialEq)]
830        struct Foo {
831            a: u8,
832            b: bool,
833        }
834
835        let val = Composite::Named(vec![
836            // Order shouldn't matter; match on names:
837            ("b".into(), Value::bool(true)),
838            ("a".into(), Value::u128(123)),
839        ]);
840
841        assert_eq!(Foo::deserialize(val), Ok(Foo { a: 123, b: true }))
842    }
843
844    #[test]
845    fn de_into_tuple_struct() {
846        #[derive(Deserialize, Debug, PartialEq)]
847        struct Foo(u8, bool, String);
848
849        let val = ValueDef::Composite(Composite::Unnamed(vec![
850            Value::u128(123),
851            Value::bool(true),
852            Value::string("hello"),
853        ]));
854
855        assert_eq!(Foo::deserialize(val), Ok(Foo(123, true, "hello".into())))
856    }
857
858    #[test]
859    fn de_unwrapped_into_tuple_struct() {
860        #[derive(Deserialize, Debug, PartialEq)]
861        struct Foo(u8, bool, String);
862
863        let val =
864            Composite::Unnamed(vec![Value::u128(123), Value::bool(true), Value::string("hello")]);
865
866        assert_eq!(Foo::deserialize(val), Ok(Foo(123, true, "hello".into())))
867    }
868
869    #[test]
870    fn de_into_newtype_struct() {
871        #[derive(Deserialize, Debug, PartialEq)]
872        struct FooStr(String);
873        let val = ValueDef::<()>::Primitive(Primitive::String("hello".into()));
874        assert_eq!(FooStr::deserialize(val), Ok(FooStr("hello".into())));
875        let val = Value::string("hello");
876        assert_eq!(FooStr::deserialize(val), Ok(FooStr("hello".into())));
877
878        #[derive(Deserialize, Debug, PartialEq)]
879        struct FooVecU8(Vec<u8>);
880        let val = ValueDef::Composite(Composite::Unnamed(vec![
881            Value::u128(1),
882            Value::u128(2),
883            Value::u128(3),
884        ]));
885        assert_eq!(FooVecU8::deserialize(val), Ok(FooVecU8(vec![1, 2, 3])));
886
887        #[derive(Deserialize, Debug, PartialEq)]
888        enum MyEnum {
889            Foo(u8, u8, u8),
890        }
891        #[derive(Deserialize, Debug, PartialEq)]
892        struct FooVar(MyEnum);
893        let val = ValueDef::Variant(Variant {
894            name: "Foo".into(),
895            values: Composite::Unnamed(vec![Value::u128(1), Value::u128(2), Value::u128(3)]),
896        });
897        assert_eq!(FooVar::deserialize(val), Ok(FooVar(MyEnum::Foo(1, 2, 3))));
898    }
899
900    #[test]
901    fn de_unwrapped_into_newtype_struct() {
902        #[derive(Deserialize, Debug, PartialEq)]
903        struct FooStr(String);
904        let val = Primitive::String("hello".into());
905        assert_eq!(FooStr::deserialize(val), Ok(FooStr("hello".into())));
906
907        #[derive(Deserialize, Debug, PartialEq)]
908        struct FooVecU8(Vec<u8>);
909        let val = Composite::Unnamed(vec![Value::u128(1), Value::u128(2), Value::u128(3)]);
910        assert_eq!(FooVecU8::deserialize(val), Ok(FooVecU8(vec![1, 2, 3])));
911
912        #[derive(Deserialize, Debug, PartialEq)]
913        enum MyEnum {
914            Foo(u8, u8, u8),
915        }
916        #[derive(Deserialize, Debug, PartialEq)]
917        struct FooVar(MyEnum);
918        let val = Variant {
919            name: "Foo".into(),
920            values: Composite::Unnamed(vec![Value::u128(1), Value::u128(2), Value::u128(3)]),
921        };
922        assert_eq!(FooVar::deserialize(val), Ok(FooVar(MyEnum::Foo(1, 2, 3))));
923    }
924
925    #[test]
926    fn de_into_vec() {
927        let val = ValueDef::Composite(Composite::Unnamed(vec![
928            Value::u128(1),
929            Value::u128(2),
930            Value::u128(3),
931        ]));
932        assert_eq!(<Vec<u8>>::deserialize(val), Ok(vec![1, 2, 3]));
933
934        let val = ValueDef::Composite(Composite::Unnamed(vec![
935            Value::string("a"),
936            Value::string("b"),
937            Value::string("c"),
938        ]));
939        assert_eq!(<Vec<String>>::deserialize(val), Ok(vec!["a".into(), "b".into(), "c".into()]));
940    }
941
942    #[test]
943    fn de_unwrapped_into_vec() {
944        let val = Composite::Unnamed(vec![Value::u128(1), Value::u128(2), Value::u128(3)]);
945        assert_eq!(<Vec<u8>>::deserialize(val), Ok(vec![1, 2, 3]));
946
947        let val = Composite::Named(vec![
948            ("a".into(), Value::u128(1)),
949            ("b".into(), Value::u128(2)),
950            ("c".into(), Value::u128(3)),
951        ]);
952        assert_eq!(<Vec<u8>>::deserialize(val), Ok(vec![1, 2, 3]));
953
954        let val =
955            Composite::Unnamed(vec![Value::string("a"), Value::string("b"), Value::string("c")]);
956        assert_eq!(<Vec<String>>::deserialize(val), Ok(vec!["a".into(), "b".into(), "c".into()]));
957    }
958
959    #[test]
960    fn de_into_map() {
961        use alloc::collections::BTreeMap;
962
963        let val = ValueDef::Composite(Composite::Named(vec![
964            ("a".into(), Value::u128(1)),
965            ("b".into(), Value::u128(2)),
966            ("c".into(), Value::u128(3)),
967        ]));
968        assert_eq!(
969            <BTreeMap<String, u8>>::deserialize(val),
970            Ok(vec![("a".into(), 1), ("b".into(), 2), ("c".into(), 3)].into_iter().collect())
971        );
972
973        let val = ValueDef::Composite(Composite::Unnamed(vec![
974            Value::u128(1),
975            Value::u128(2),
976            Value::u128(3),
977        ]));
978        <BTreeMap<String, u8>>::deserialize(val).expect_err("no names; can't be map");
979    }
980
981    #[test]
982    fn de_into_tuple() {
983        let val = ValueDef::Composite(Composite::Unnamed(vec![
984            Value::string("hello"),
985            Value::bool(true),
986        ]));
987        assert_eq!(<(String, bool)>::deserialize(val), Ok(("hello".into(), true)));
988
989        // names will just be ignored:
990        let val = ValueDef::Composite(Composite::Named(vec![
991            ("a".into(), Value::string("hello")),
992            ("b".into(), Value::bool(true)),
993        ]));
994        assert_eq!(<(String, bool)>::deserialize(val), Ok(("hello".into(), true)));
995
996        // Enum variants are allowed! The variant name will be ignored:
997        let val = ValueDef::Variant(Variant::unnamed_fields(
998            "Foo",
999            vec![Value::string("hello"), Value::bool(true)],
1000        ));
1001        assert_eq!(<(String, bool)>::deserialize(val), Ok(("hello".into(), true)));
1002
1003        // Enum variants with names values are allowed! The variant name will be ignored:
1004        let val = ValueDef::Variant(Variant::named_fields(
1005            "Foo",
1006            [("a", Value::string("hello")), ("b", Value::bool(true))],
1007        ));
1008        assert_eq!(<(String, bool)>::deserialize(val), Ok(("hello".into(), true)));
1009
1010        // Wrong number of values should fail:
1011        let val = ValueDef::Composite(Composite::Unnamed(vec![
1012            Value::string("hello"),
1013            Value::bool(true),
1014            Value::u128(123),
1015        ]));
1016        <(String, bool)>::deserialize(val).expect_err("Wrong length, should err");
1017    }
1018
1019    #[test]
1020    fn de_unwrapped_into_tuple() {
1021        let val = Composite::Unnamed(vec![Value::string("hello"), Value::bool(true)]);
1022        assert_eq!(<(String, bool)>::deserialize(val), Ok(("hello".into(), true)));
1023
1024        // names will just be ignored:
1025        let val = Composite::Named(vec![
1026            ("a".into(), Value::string("hello")),
1027            ("b".into(), Value::bool(true)),
1028        ]);
1029        assert_eq!(<(String, bool)>::deserialize(val), Ok(("hello".into(), true)));
1030
1031        // Wrong number of values should fail:
1032        let val =
1033            Composite::Unnamed(vec![Value::string("hello"), Value::bool(true), Value::u128(123)]);
1034        <(String, bool)>::deserialize(val).expect_err("Wrong length, should err");
1035    }
1036
1037    #[test]
1038    fn de_bitvec() {
1039        use scale_bits::bits;
1040
1041        // If we deserialize a bitvec value into a value, it should come back out the same.
1042        let val = Value::bit_sequence(bits![0, 1, 1, 0, 1, 0, 1, 0, 1]);
1043        assert_eq!(Value::deserialize(val.clone()), Ok(val.clone()));
1044
1045        // We can serialize a bitvec Value to something like JSON and deserialize it again, too.
1046        let json_val = serde_json::to_value(&val).expect("can encode to json");
1047        let new_val: Value<()> =
1048            serde_json::from_value(json_val).expect("can decode back from json");
1049        assert_eq!(new_val, val);
1050    }
1051
1052    #[test]
1053    fn de_into_tuple_variant() {
1054        #[derive(Deserialize, Debug, PartialEq)]
1055        enum MyEnum {
1056            Foo(String, bool, u8),
1057        }
1058
1059        let val = ValueDef::Variant(Variant {
1060            name: "Foo".into(),
1061            values: Composite::Unnamed(vec![
1062                Value::string("hello"),
1063                Value::bool(true),
1064                Value::u128(123),
1065            ]),
1066        });
1067        assert_eq!(MyEnum::deserialize(val), Ok(MyEnum::Foo("hello".into(), true, 123)));
1068
1069        // it's fine to name the fields; we'll just ignore the names
1070        let val = ValueDef::Variant(Variant {
1071            name: "Foo".into(),
1072            values: Composite::Named(vec![
1073                ("a".into(), Value::string("hello")),
1074                ("b".into(), Value::bool(true)),
1075                ("c".into(), Value::u128(123)),
1076            ]),
1077        });
1078        assert_eq!(MyEnum::deserialize(val), Ok(MyEnum::Foo("hello".into(), true, 123)));
1079    }
1080
1081    #[test]
1082    fn de_unwrapped_into_tuple_variant() {
1083        #[derive(Deserialize, Debug, PartialEq)]
1084        enum MyEnum {
1085            Foo(String, bool, u8),
1086        }
1087
1088        let val = Variant {
1089            name: "Foo".into(),
1090            values: Composite::Unnamed(vec![
1091                Value::string("hello"),
1092                Value::bool(true),
1093                Value::u128(123),
1094            ]),
1095        };
1096        assert_eq!(MyEnum::deserialize(val), Ok(MyEnum::Foo("hello".into(), true, 123)));
1097
1098        // it's fine to name the fields; we'll just ignore the names
1099        let val = Variant {
1100            name: "Foo".into(),
1101            values: Composite::Named(vec![
1102                ("a".into(), Value::string("hello")),
1103                ("b".into(), Value::bool(true)),
1104                ("c".into(), Value::u128(123)),
1105            ]),
1106        };
1107        assert_eq!(MyEnum::deserialize(val), Ok(MyEnum::Foo("hello".into(), true, 123)));
1108    }
1109
1110    #[test]
1111    fn de_into_struct_variant() {
1112        #[derive(Deserialize, Debug, PartialEq)]
1113        enum MyEnum {
1114            Foo { hi: String, a: bool, b: u8 },
1115        }
1116
1117        // If names given, order doesn't matter:
1118        let val = ValueDef::Variant(Variant {
1119            name: "Foo".into(),
1120            values: Composite::Named(vec![
1121                // Deliberately out of order: names should ensure alignment:
1122                ("b".into(), Value::u128(123)),
1123                ("a".into(), Value::bool(true)),
1124                ("hi".into(), Value::string("hello")),
1125            ]),
1126        });
1127        assert_eq!(
1128            MyEnum::deserialize(val),
1129            Ok(MyEnum::Foo { hi: "hello".into(), a: true, b: 123 })
1130        );
1131
1132        // No names needed if order is OK:
1133        let val = ValueDef::Variant(Variant {
1134            name: "Foo".into(),
1135            values: Composite::Unnamed(vec![
1136                Value::string("hello"),
1137                Value::bool(true),
1138                Value::u128(123),
1139            ]),
1140        });
1141        assert_eq!(
1142            MyEnum::deserialize(val),
1143            Ok(MyEnum::Foo { hi: "hello".into(), a: true, b: 123 })
1144        );
1145
1146        // Wrong order won't work if no names:
1147        let val = ValueDef::Variant(Variant {
1148            name: "Foo".into(),
1149            values: Composite::Unnamed(vec![
1150                Value::bool(true),
1151                Value::u128(123),
1152                Value::string("hello"),
1153            ]),
1154        });
1155        MyEnum::deserialize(val).expect_err("Wrong order shouldn't work");
1156
1157        // Wrong names won't work:
1158        let val = ValueDef::Variant(Variant {
1159            name: "Foo".into(),
1160            values: Composite::Named(vec![
1161                ("b".into(), Value::u128(123)),
1162                // Whoops; wrong name:
1163                ("c".into(), Value::bool(true)),
1164                ("hi".into(), Value::string("hello")),
1165            ]),
1166        });
1167        MyEnum::deserialize(val).expect_err("Wrong names shouldn't work");
1168
1169        // Too many names is OK; we can ignore fields we don't care about:
1170        let val = ValueDef::Variant(Variant {
1171            name: "Foo".into(),
1172            values: Composite::Named(vec![
1173                ("foo".into(), Value::u128(40)),
1174                ("b".into(), Value::u128(123)),
1175                ("a".into(), Value::bool(true)),
1176                ("bar".into(), Value::bool(false)),
1177                ("hi".into(), Value::string("hello")),
1178            ]),
1179        });
1180        assert_eq!(
1181            MyEnum::deserialize(val),
1182            Ok(MyEnum::Foo { hi: "hello".into(), a: true, b: 123 })
1183        );
1184    }
1185
1186    #[test]
1187    fn de_into_unit_variants() {
1188        let val = value!(Foo {});
1189
1190        let unwrapped_val = Variant::<()> { name: "Foo".into(), values: Composite::Named(vec![]) };
1191
1192        #[derive(Deserialize, Debug, PartialEq)]
1193        enum MyEnum {
1194            Foo,
1195        }
1196        assert_eq!(MyEnum::deserialize(val.clone()), Ok(MyEnum::Foo));
1197        assert_eq!(MyEnum::deserialize(unwrapped_val.clone()), Ok(MyEnum::Foo));
1198
1199        #[derive(Deserialize, Debug, PartialEq)]
1200        enum MyEnum2 {
1201            Foo(),
1202        }
1203        assert_eq!(MyEnum2::deserialize(val.clone()), Ok(MyEnum2::Foo()));
1204        assert_eq!(MyEnum2::deserialize(unwrapped_val.clone()), Ok(MyEnum2::Foo()));
1205
1206        #[derive(Deserialize, Debug, PartialEq)]
1207        enum MyEnum3 {
1208            Foo {},
1209        }
1210        assert_eq!(MyEnum3::deserialize(val), Ok(MyEnum3::Foo {}));
1211        assert_eq!(MyEnum3::deserialize(unwrapped_val), Ok(MyEnum3::Foo {}));
1212    }
1213}