serde_reflection/
value.rs

1// Copyright (c) Facebook, Inc. and its affiliates
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use crate::error::{Error, Result};
5use serde::de::{self, DeserializeSeed, IntoDeserializer, Visitor};
6
7/// A structured Serde value.
8/// Meant to be easily recorded while tracing serialization and easily used while tracing deserialization.
9#[derive(Debug, Clone, PartialEq)]
10pub enum Value {
11    Unit,
12    Bool(bool),
13
14    I8(i8),
15    I16(i16),
16    I32(i32),
17    I64(i64),
18    I128(i128),
19
20    U8(u8),
21    U16(u16),
22    U32(u32),
23    U64(u64),
24    U128(u128),
25
26    F32(f32),
27    F64(f64),
28
29    Char(char),
30    Str(String),
31    Bytes(Vec<u8>),
32
33    Option(Option<Box<Value>>),
34    Variant(u32, Box<Value>),
35    Seq(Vec<Value>),
36}
37
38/// Deserializer meant to reconstruct the Rust value behind a particular Serde value.
39pub struct Deserializer<'de> {
40    value: &'de Value,
41}
42
43impl<'de> Deserializer<'de> {
44    pub fn new(value: &'de Value) -> Self {
45        Self { value }
46    }
47}
48
49impl<'de> IntoDeserializer<'de, Error> for &'de Value {
50    type Deserializer = Deserializer<'de>;
51
52    fn into_deserializer(self) -> Self::Deserializer {
53        Deserializer::new(self)
54    }
55}
56
57impl Value {
58    pub(crate) fn seq_values(&self) -> Result<&Vec<Value>> {
59        match self {
60            Value::Seq(x) => Ok(x),
61            _ => Err(Error::DeserializationError("seq_values")),
62        }
63    }
64}
65
66macro_rules! declare_deserialize {
67    ($method:ident, $token:ident, $visit:ident, $str:expr) => {
68        fn $method<V>(self, visitor: V) -> Result<V::Value>
69        where
70            V: Visitor<'de>,
71        {
72            match self.value {
73                Value::$token(x) => visitor.$visit(x.clone()),
74                _ => Err(Error::DeserializationError($str)),
75            }
76        }
77    };
78}
79
80macro_rules! declare_deserialize_borrowed {
81    ($method:ident, $token:ident, $visit:ident, $str:expr) => {
82        fn $method<V>(self, visitor: V) -> Result<V::Value>
83        where
84            V: Visitor<'de>,
85        {
86            match self.value {
87                Value::$token(x) => visitor.$visit(x),
88                _ => Err(Error::DeserializationError($str)),
89            }
90        }
91    };
92}
93
94impl<'de> de::Deserializer<'de> for Deserializer<'de> {
95    type Error = Error;
96
97    fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value>
98    where
99        V: Visitor<'de>,
100    {
101        Err(Error::NotSupported("deserialize_any"))
102    }
103
104    declare_deserialize!(deserialize_bool, Bool, visit_bool, "bool");
105
106    declare_deserialize!(deserialize_i8, I8, visit_i8, "i8");
107    declare_deserialize!(deserialize_i16, I16, visit_i16, "i16");
108    declare_deserialize!(deserialize_i32, I32, visit_i32, "i32");
109    declare_deserialize!(deserialize_i64, I64, visit_i64, "i64");
110    declare_deserialize!(deserialize_i128, I128, visit_i128, "i128");
111
112    declare_deserialize!(deserialize_u8, U8, visit_u8, "u8");
113    declare_deserialize!(deserialize_u16, U16, visit_u16, "u16");
114    declare_deserialize!(deserialize_u32, U32, visit_u32, "u32");
115    declare_deserialize!(deserialize_u64, U64, visit_u64, "u64");
116    declare_deserialize!(deserialize_u128, U128, visit_u128, "u128");
117
118    declare_deserialize!(deserialize_f32, F32, visit_f32, "f32");
119    declare_deserialize!(deserialize_f64, F64, visit_f64, "f64");
120
121    declare_deserialize!(deserialize_char, Char, visit_char, "char");
122    declare_deserialize!(deserialize_string, Str, visit_string, "string");
123    declare_deserialize_borrowed!(deserialize_str, Str, visit_borrowed_str, "str");
124    declare_deserialize!(deserialize_byte_buf, Bytes, visit_byte_buf, "byte_buf");
125    declare_deserialize_borrowed!(deserialize_bytes, Bytes, visit_borrowed_bytes, "bytes");
126
127    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
128    where
129        V: Visitor<'de>,
130    {
131        match self.value {
132            Value::Option(None) => visitor.visit_none(),
133            Value::Option(Some(x)) => visitor.visit_some(x.into_deserializer()),
134            _ => Err(Error::DeserializationError("option")),
135        }
136    }
137
138    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
139    where
140        V: Visitor<'de>,
141    {
142        match self.value {
143            Value::Unit => visitor.visit_unit(),
144            _ => Err(Error::DeserializationError("unit")),
145        }
146    }
147
148    fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
149    where
150        V: Visitor<'de>,
151    {
152        match self.value {
153            Value::Unit => visitor.visit_unit(),
154            _ => Err(Error::DeserializationError("unit struct")),
155        }
156    }
157
158    fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
159    where
160        V: Visitor<'de>,
161    {
162        visitor.visit_newtype_struct(self)
163    }
164
165    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
166    where
167        V: Visitor<'de>,
168    {
169        match self.value {
170            Value::Seq(x) => visitor.visit_seq(x.into_seq_deserializer()),
171            _ => Err(Error::DeserializationError("seq")),
172        }
173    }
174
175    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value>
176    where
177        V: Visitor<'de>,
178    {
179        match self.value {
180            Value::Seq(x) => visitor.visit_seq(x.into_seq_deserializer()),
181            _ => Err(Error::DeserializationError("tuple")),
182        }
183    }
184
185    fn deserialize_tuple_struct<V>(
186        self,
187        _name: &'static str,
188        _len: usize,
189        visitor: V,
190    ) -> Result<V::Value>
191    where
192        V: Visitor<'de>,
193    {
194        match self.value {
195            Value::Seq(x) => visitor.visit_seq(x.into_seq_deserializer()),
196            _ => Err(Error::DeserializationError("tuple struct")),
197        }
198    }
199
200    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
201    where
202        V: Visitor<'de>,
203    {
204        match self.value {
205            Value::Seq(x) => visitor.visit_seq(x.into_seq_deserializer()),
206            _ => Err(Error::DeserializationError("map")),
207        }
208    }
209
210    fn deserialize_struct<V>(
211        self,
212        _name: &'static str,
213        _fields: &'static [&'static str],
214        visitor: V,
215    ) -> Result<V::Value>
216    where
217        V: Visitor<'de>,
218    {
219        match self.value {
220            Value::Seq(x) => visitor.visit_seq(x.into_seq_deserializer()),
221            _ => Err(Error::DeserializationError("tuple struct")),
222        }
223    }
224
225    fn deserialize_enum<V>(
226        self,
227        _name: &'static str,
228        _variants: &'static [&'static str],
229        visitor: V,
230    ) -> Result<V::Value>
231    where
232        V: Visitor<'de>,
233    {
234        match self.value {
235            Value::Variant(index, variant) => {
236                let inner = EnumDeserializer::new(*index, variant);
237                visitor.visit_enum(inner)
238            }
239            _ => Err(Error::DeserializationError("enum")),
240        }
241    }
242
243    // Not needed since we always deserialize structs as sequences.
244    fn deserialize_identifier<V>(self, _visitor: V) -> Result<V::Value>
245    where
246        V: Visitor<'de>,
247    {
248        Err(Error::NotSupported("deserialize_identifier"))
249    }
250
251    fn deserialize_ignored_any<V>(self, _visitor: V) -> Result<V::Value>
252    where
253        V: Visitor<'de>,
254    {
255        Err(Error::NotSupported("deserialize_ignored_any"))
256    }
257
258    fn is_human_readable(&self) -> bool {
259        false
260    }
261}
262
263pub(crate) struct SeqDeserializer<I> {
264    values: I,
265}
266
267pub(crate) trait IntoSeqDeserializer {
268    type SeqDeserializer;
269
270    fn into_seq_deserializer(self) -> Self::SeqDeserializer;
271}
272
273impl<I> SeqDeserializer<I> {
274    fn new(values: I) -> Self {
275        Self { values }
276    }
277}
278
279impl<'de> IntoSeqDeserializer for &'de Vec<Value> {
280    type SeqDeserializer = SeqDeserializer<std::slice::Iter<'de, Value>>;
281
282    fn into_seq_deserializer(self) -> Self::SeqDeserializer {
283        SeqDeserializer::new(self.iter())
284    }
285}
286
287impl<'de, I> de::SeqAccess<'de> for SeqDeserializer<I>
288where
289    I: Iterator<Item = &'de Value>,
290{
291    type Error = Error;
292
293    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
294    where
295        T: DeserializeSeed<'de>,
296    {
297        match self.values.next() {
298            Some(x) => seed.deserialize(x.into_deserializer()).map(Some),
299            None => Ok(None),
300        }
301    }
302
303    fn size_hint(&self) -> Option<usize> {
304        self.values.size_hint().1
305    }
306}
307
308impl<'de, I> de::MapAccess<'de> for SeqDeserializer<I>
309where
310    I: Iterator<Item = &'de Value>,
311{
312    type Error = Error;
313
314    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
315    where
316        K: DeserializeSeed<'de>,
317    {
318        match self.values.next() {
319            Some(x) => seed.deserialize(x.into_deserializer()).map(Some),
320            None => Ok(None),
321        }
322    }
323
324    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
325    where
326        V: DeserializeSeed<'de>,
327    {
328        match self.values.next() {
329            Some(x) => seed.deserialize(x.into_deserializer()),
330            None => Err(Error::DeserializationError("value in map")),
331        }
332    }
333
334    fn size_hint(&self) -> Option<usize> {
335        self.values.size_hint().1.map(|x| x / 2)
336    }
337}
338
339struct EnumDeserializer<'de> {
340    index: u32,
341    value: &'de Value,
342}
343
344impl<'de> EnumDeserializer<'de> {
345    fn new(index: u32, value: &'de Value) -> Self {
346        Self { index, value }
347    }
348}
349
350impl<'de> de::EnumAccess<'de> for EnumDeserializer<'de> {
351    type Error = Error;
352    type Variant = Self;
353
354    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
355    where
356        V: DeserializeSeed<'de>,
357    {
358        let value = seed.deserialize(self.index.into_deserializer())?;
359        Ok((value, self))
360    }
361}
362
363impl<'de> de::VariantAccess<'de> for EnumDeserializer<'de> {
364    type Error = Error;
365
366    fn unit_variant(self) -> Result<()> {
367        match self.value {
368            Value::Unit => Ok(()),
369            _ => Err(Error::DeserializationError("unit variant")),
370        }
371    }
372
373    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
374    where
375        T: DeserializeSeed<'de>,
376    {
377        seed.deserialize(self.value.into_deserializer())
378    }
379
380    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value>
381    where
382        V: Visitor<'de>,
383    {
384        match self.value {
385            Value::Seq(x) => visitor.visit_seq(x.into_seq_deserializer()),
386            _ => Err(Error::DeserializationError("tuple variant")),
387        }
388    }
389
390    fn struct_variant<V>(self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
391    where
392        V: Visitor<'de>,
393    {
394        match self.value {
395            Value::Seq(x) => visitor.visit_seq(x.into_seq_deserializer()),
396            _ => Err(Error::DeserializationError("struct variant")),
397        }
398    }
399}