vdf_serde_format/
deserializer.rs

1use std::ops::{AddAssign, MulAssign, Neg};
2use std::str::FromStr;
3
4use serde::de::{
5    self, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess,
6    Visitor,
7};
8use serde::Deserialize;
9
10use crate::error::{Error, Result};
11use crate::preprocessor::{parse_string, peek_real_char};
12use crate::{peek_expect_char, preprocess};
13
14#[derive(Clone, Copy, PartialEq, PartialOrd, Debug)]
15#[allow(dead_code)]
16enum LogLevel {
17    Error = 0,
18    Warn = 1,
19    Info = 2,
20    Debug = 3,
21    Trace = 4,
22}
23
24#[cfg(debug_assertions)]
25static mut INDENTATION: usize = 0;
26
27#[cfg(debug_assertions)]
28static mut CURRENT_LEVEL: LogLevel = LogLevel::Debug;
29
30macro_rules! log {
31    ($level:expr, $($arg:tt)*) => ({
32        #[cfg(debug_assertions)]
33        {
34            let current_level = unsafe { CURRENT_LEVEL };
35            if $level <= current_level {
36                let indentation = unsafe { "\t".repeat(INDENTATION) };
37                println!("{}{}", indentation, format!($($arg)*));
38            }
39        }
40    });
41}
42
43macro_rules! adjust_indentation {
44    ($delta:expr) => {
45        #[cfg(debug_assertions)]
46        {
47            unsafe {
48                let delta: i32 = $delta;
49                if INDENTATION != 0 && delta < 0 {
50                    if delta < 0 {
51                        INDENTATION -= delta.abs() as usize;
52                    } else {
53                        INDENTATION += delta as usize;
54                    }
55                }
56            }
57        }
58    };
59}
60
61pub struct Deserializer<'de> {
62    // This string starts with the input data and characters are truncated off
63    // the beginning as data is parsed.
64    input: &'de str,
65    array_key: Option<String>,
66    beginning: bool,
67}
68
69impl<'de> Deserializer<'de> {
70    // By convention, `Deserializer` constructors are named like `from_xyz`.
71    // That way basic use cases are satisfied by something like
72    // `serde_json::from_str(...)` while advanced use cases that require a
73    // deserializer can make one with `serde_json::Deserializer::from_str(...)`.
74    pub fn from_str(input: &'de str) -> Self {
75        let is_properly_blocked = peek_expect_char(input, 0, '{').unwrap_or(false);
76        let starts_with_header = peek_expect_char(input, 0, '"').unwrap_or(false);
77        let mut parsed_input: String = input.to_string();
78        if is_properly_blocked || starts_with_header {
79            let mut block_preprocessor = false;
80            if starts_with_header {
81                let temp = parse_string(input).unwrap();
82                if !peek_expect_char(temp.1, 0, '{').unwrap_or(false) {
83                    block_preprocessor = true;
84                }
85            }
86            if !block_preprocessor {
87                parsed_input = preprocess(input, starts_with_header, true).unwrap();
88                if starts_with_header {
89                    let lines = parsed_input.lines().collect::<Vec<&str>>();
90                    let mut temp_parsed_input = String::new();
91                    for line in lines {
92                        temp_parsed_input += "\t";
93                        temp_parsed_input += line;
94                        temp_parsed_input += "\n";
95                    }
96                    parsed_input = format!("{{\n{}\n}}", temp_parsed_input);
97                }
98                log!(
99                    LogLevel::Debug,
100                    "Preprocessed input: {:?}\n{}",
101                    parsed_input,
102                    parsed_input
103                );
104                log!(LogLevel::Debug, "-------------------");
105            }
106        }
107        Deserializer {
108            input: Box::leak(parsed_input.into_boxed_str()),
109            array_key: None,
110            beginning: true,
111        }
112    }
113}
114
115// By convention, the public API of a Serde deserializer is one or more
116// `from_xyz` methods such as `from_str`, `from_bytes`, or `from_reader`
117// depending on what Rust types the deserializer is able to consume as input.
118//
119// This basic deserializer supports only `from_str`.
120pub fn from_str<'a, T>(input: &'a str) -> Result<T>
121where
122    T: Deserialize<'a>,
123{
124    let mut deserializer = Deserializer::from_str(input);
125    let t = T::deserialize(&mut deserializer)?;
126    deserializer.input = deserializer.input.trim();
127    if deserializer.input.is_empty() {
128        Ok(t)
129    } else {
130        log!(
131            LogLevel::Warn,
132            "Trailing characters: {:?}",
133            deserializer.input.chars()
134        );
135        Err(Error::TrailingCharacters)
136    }
137}
138
139// SERDE IS NOT A PARSING LIBRARY. This impl block defines a few basic parsing
140// functions from scratch. More complicated formats may wish to use a dedicated
141// parsing library to help implement their Serde deserializer.
142impl<'de> Deserializer<'de> {
143    // Look at the first character in the input without consuming it.
144    fn peek_char(&mut self) -> Result<char> {
145        self.input.chars().next().ok_or(Error::Eof)
146    }
147    // Look for the first character that is not a whitespace in the input.
148    fn peek_real_char(&mut self) -> Result<char> {
149        let mut temp_input = self.input;
150        let mut ch = temp_input.chars().next().ok_or(Error::Eof)?;
151        while ch.is_whitespace() {
152            temp_input = &temp_input[ch.len_utf8()..];
153            ch = temp_input.chars().next().ok_or(Error::Eof)?;
154        }
155        Ok(ch)
156    }
157
158    // Consume the first character in the input.
159    fn next_char(&mut self) -> Result<char> {
160        let ch = self.peek_char()?;
161        self.input = &self.input[ch.len_utf8()..];
162        Ok(ch)
163    }
164    // Look for the first character that is not a whitespace in the input.
165    fn next_real_char(&mut self) -> Result<char> {
166        let mut ch = self.next_char()?;
167        while ch.is_whitespace() {
168            ch = self.next_char()?;
169        }
170        Ok(ch)
171    }
172
173    fn peek_str(&mut self) -> Result<String> {
174        log!(LogLevel::Debug, "Peek str");
175        if !self.peek_expect_char('"')? {
176            return Err(Error::ExpectedString);
177        }
178
179        let start_index = self.input.find('"').ok_or(Error::Eof)? + 1;
180        let next_quote = self.input[start_index..].find('"').ok_or(Error::Eof)?;
181        let next_str = &self.input[start_index..start_index + next_quote];
182        Ok(next_str.to_string())
183    }
184
185    fn peek_expect_str(&mut self, expected: &str) -> Result<bool> {
186        log!(LogLevel::Debug, "Peek expect str");
187        let parsed_str = self.peek_str()?;
188        if parsed_str != expected {
189            log!(
190                LogLevel::Debug,
191                "Expected: {:?}, got: {:?}\n{:?}",
192                expected,
193                parsed_str,
194                self.input.chars()
195            );
196            return Ok(false);
197        }
198        Ok(true)
199    }
200    fn peek_expect_char(&mut self, expected: char) -> Result<bool> {
201        log!(LogLevel::Debug, "Peek expect char");
202        let ch = self.peek_real_char()?;
203        if ch != expected {
204            log!(
205                LogLevel::Debug,
206                "Expected: {:?}, got: {:?}\n{:?}",
207                expected,
208                ch,
209                self.input.chars()
210            );
211            return Ok(false);
212        }
213        Ok(true)
214    }
215    fn next_expect_char(&mut self, expected: char) -> Result<bool> {
216        let ch = self.next_real_char()?;
217        if ch != expected {
218            log!(
219                LogLevel::Debug,
220                "Expected: {:?}, got: {:?}\n{:?}",
221                expected,
222                ch,
223                self.input.chars()
224            );
225            return Ok(false);
226        }
227        Ok(true)
228    }
229    fn next_expect_string(&mut self, expected: &str) -> Result<bool> {
230        let parsed_str = self.parse_string()?;
231        if parsed_str != expected {
232            log!(
233                LogLevel::Debug,
234                "Expected: {:?}, got: {:?}\n{:?}",
235                expected,
236                parsed_str,
237                self.input.chars()
238            );
239            return Ok(false);
240        }
241        Ok(true)
242    }
243
244    // Parse the JSON identifier `true` or `false`.
245    fn parse_bool(&mut self) -> Result<bool> {
246        let input = match self.peek_real_char()? {
247            '"' => {
248                let parsed_str = self.parse_string()?;
249                match parsed_str.to_lowercase().as_str() {
250                    "false" | "no" | "0" | "true" | "yes" | "1" => Ok(parsed_str.to_lowercase()),
251                    _ => Err(Error::ExpectedBoolean),
252                }
253            }
254            _ => match self.input.to_lowercase().as_str() {
255                "false" | "no" | "0" | "true" | "yes" | "1" => Ok(self.input.to_lowercase()),
256                _ => Err(Error::ExpectedBoolean),
257            },
258        }?;
259
260        self.input = &self.input[input.len()..];
261
262        match input.as_str() {
263            "false" | "no" | "0" => Ok(false),
264            "true" | "yes" | "1" => Ok(true),
265            _ => Err(Error::ExpectedBoolean),
266        }
267    }
268
269    // Parse a integer from a string.
270    fn parse_integer<T>(&mut self) -> Result<T>
271    where
272        T: FromStr,
273    {
274        log!(LogLevel::Debug, "Parse integer");
275        let str = if self.input.contains('"') {
276            // Handle the normal parsing through the VDF format.
277            self.parse_string()?
278        } else {
279            // Handle one off cases where the integer is passed directly to the deserializer.
280            let s = self.input;
281            if s.parse::<T>().is_err() {
282                return Err(Error::ExpectedInteger);
283            }
284            self.input = "";
285            s
286        };
287        str.parse::<T>().map_err(|_| Error::ExpectedInteger)
288    }
289
290    // Parse a group of decimal digits as an unsigned integer of type T.
291    //
292    // This implementation is a bit too lenient, for example `001` is not
293    // allowed in JSON. Also the various arithmetic operations can overflow and
294    // panic or return bogus data. But it is good enough for example code!
295    fn parse_unsigned<T>(&mut self) -> Result<T>
296    where
297        T: AddAssign<T> + MulAssign<T> + From<u8> + FromStr,
298    {
299        self.parse_integer::<T>()
300    }
301
302    // Parse a possible minus sign followed by a group of decimal digits as a
303    // signed integer of type T.
304    fn parse_signed<T>(&mut self) -> Result<T>
305    where
306        T: Neg<Output = T> + AddAssign<T> + MulAssign<T> + From<i8> + FromStr,
307    {
308        self.parse_integer::<T>()
309    }
310
311    // Parse a string until the next '"' character.
312    //
313    // Makes no attempt to handle escape sequences. What did you expect? This is
314    // example code!
315    fn parse_string(&mut self) -> Result<&'de str> {
316        if !self.next_expect_char('"')? {
317            return Err(Error::ExpectedString);
318        }
319        match self.input.find('"') {
320            Some(len) => {
321                let s = &self.input[..len];
322                self.input = &self.input[len + 1..];
323                log!(LogLevel::Debug, "Parse string: {:?}", s);
324                Ok(s)
325            }
326            None => Err(Error::Eof),
327        }
328    }
329}
330
331impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
332    type Error = Error;
333
334    // Look at the input data to decide what Serde data model type to
335    // deserialize as. Not all data formats are able to support this operation.
336    // Formats that support `deserialize_any` are known as self-describing.
337    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
338    where
339        V: Visitor<'de>,
340    {
341        let peek_ch = self.peek_real_char()?;
342        log!(LogLevel::Debug, "Deserialize any = {:?}", peek_ch);
343        match peek_ch {
344            'n' => self.deserialize_unit(visitor),
345            't' | 'f' => self.deserialize_bool(visitor),
346            '"' => self.deserialize_str(visitor),
347            '0'..='9' => self.deserialize_u64(visitor),
348            '-' => self.deserialize_i64(visitor),
349            '[' => self.deserialize_seq(visitor),
350            '{' => self.deserialize_map(visitor),
351            _ => {
352                log!(LogLevel::Warn, "Deserialize any = {:?}", peek_ch);
353                Err(Error::Syntax)
354            }
355        }
356    }
357
358    // Uses the `parse_bool` parsing function defined above to read the JSON
359    // identifier `true` or `false` from the input.
360    //
361    // Parsing refers to looking at the input and deciding that it contains the
362    // JSON value `true` or `false`.
363    //
364    // Deserialization refers to mapping that JSON value into Serde's data
365    // model by invoking one of the `Visitor` methods. In the case of JSON and
366    // bool that mapping is straightforward so the distinction may seem silly,
367    // but in other cases Deserializers sometimes perform non-obvious mappings.
368    // For example the TOML format has a Datetime type and Serde's data model
369    // does not. In the `toml` crate, a Datetime in the input is deserialized by
370    // mapping it to a Serde data model "struct" type with a special name and a
371    // single field containing the Datetime represented as a string.
372    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
373    where
374        V: Visitor<'de>,
375    {
376        let value = self.parse_bool()?;
377        log!(LogLevel::Debug, "Deserialize bool = {:?}", value);
378        visitor.visit_bool(value)
379    }
380
381    // The `parse_signed` function is generic over the integer type `T` so here
382    // it is invoked with `T=i8`. The next 8 methods are similar.
383    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
384    where
385        V: Visitor<'de>,
386    {
387        let value = self.parse_signed()?;
388        log!(LogLevel::Debug, "Deserialize i8 = {:?}", value);
389        visitor.visit_i8(value)
390    }
391
392    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value>
393    where
394        V: Visitor<'de>,
395    {
396        let value = self.parse_signed()?;
397        log!(LogLevel::Debug, "Deserialize i16 = {:?}", value);
398        visitor.visit_i16(value)
399    }
400
401    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value>
402    where
403        V: Visitor<'de>,
404    {
405        let value = self.parse_signed()?;
406        log!(LogLevel::Debug, "Deserialize i32 = {:?}", value);
407        visitor.visit_i32(value)
408    }
409
410    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value>
411    where
412        V: Visitor<'de>,
413    {
414        let value = self.parse_signed()?;
415        log!(LogLevel::Debug, "Deserialize i64 = {:?}", value);
416        visitor.visit_i64(value)
417    }
418
419    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
420    where
421        V: Visitor<'de>,
422    {
423        let value = self.parse_unsigned()?;
424        log!(LogLevel::Debug, "Deserialize u8 = {:?}", value);
425        visitor.visit_u8(value)
426    }
427
428    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value>
429    where
430        V: Visitor<'de>,
431    {
432        let value = self.parse_unsigned()?;
433        log!(LogLevel::Debug, "Deserialize u16 = {:?}", value);
434        visitor.visit_u16(value)
435    }
436
437    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value>
438    where
439        V: Visitor<'de>,
440    {
441        let value = self.parse_unsigned()?;
442        log!(LogLevel::Debug, "Deserialize u32 = {:?}", value);
443        visitor.visit_u32(value)
444    }
445
446    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value>
447    where
448        V: Visitor<'de>,
449    {
450        let value = self.parse_unsigned()?;
451        log!(LogLevel::Debug, "Deserialize u64 = {:?}", value);
452        visitor.visit_u64(value)
453    }
454
455    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value>
456    where
457        V: Visitor<'de>,
458    {
459        log!(LogLevel::Debug, "Deserialize f32");
460        let value = self.parse_integer()?;
461        visitor.visit_f32(value)
462    }
463
464    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value>
465    where
466        V: Visitor<'de>,
467    {
468        log!(LogLevel::Debug, "Deserialize f64");
469        let value = self.parse_integer()?;
470        visitor.visit_f64(value)
471    }
472
473    // The `Serializer` implementation on the previous page serialized chars as
474    // single-character strings so handle that representation here.
475    fn deserialize_char<V>(self, _visitor: V) -> Result<V::Value>
476    where
477        V: Visitor<'de>,
478    {
479        let ch = self.parse_string()?.chars().next().ok_or(Error::Eof)?;
480        log!(LogLevel::Debug, "Deserialize char = {:?}", ch);
481        _visitor.visit_char(ch)
482    }
483
484    // Refer to the "Understanding deserializer lifetimes" page for information
485    // about the three deserialization flavors of strings in Serde.
486    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
487    where
488        V: Visitor<'de>,
489    {
490        let str = self.parse_string()?;
491        log!(LogLevel::Debug, "Deserialize str = {:?}", str);
492
493        self.array_key = Some(str.to_string());
494
495        visitor.visit_borrowed_str(str)
496    }
497
498    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
499    where
500        V: Visitor<'de>,
501    {
502        log!(LogLevel::Debug, "Deserialize string");
503        self.deserialize_str(visitor)
504    }
505
506    // The `Serializer` implementation on the previous page serialized byte
507    // arrays as JSON arrays of bytes. Handle that representation here.
508    fn deserialize_bytes<V>(self, _visitor: V) -> Result<V::Value>
509    where
510        V: Visitor<'de>,
511    {
512        log!(LogLevel::Debug, "Deserialize bytes");
513        unimplemented!()
514    }
515
516    fn deserialize_byte_buf<V>(self, _visitor: V) -> Result<V::Value>
517    where
518        V: Visitor<'de>,
519    {
520        log!(LogLevel::Debug, "Deserialize byte buf");
521        unimplemented!()
522    }
523
524    // An absent optional is represented as the JSON `null` and a present
525    // optional is represented as just the contained value.
526    //
527    // As commented in `Serializer` implementation, this is a lossy
528    // representation. For example the values `Some(())` and `None` both
529    // serialize as just `null`. Unfortunately this is typically what people
530    // expect when working with JSON. Other formats are encouraged to behave
531    // more intelligently if possible.
532    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
533    where
534        V: Visitor<'de>,
535    {
536        log!(LogLevel::Debug, "Deserialize option");
537        if self.input.starts_with("null") {
538            self.input = &self.input["null".len()..];
539            visitor.visit_none()
540        } else {
541            visitor.visit_some(self)
542        }
543    }
544
545    // In Serde, unit means an anonymous value containing no data.
546    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
547    where
548        V: Visitor<'de>,
549    {
550        log!(LogLevel::Debug, "Deserialize unit");
551        if self.input.starts_with("null") {
552            self.input = &self.input["null".len()..];
553            visitor.visit_unit()
554        } else {
555            Err(Error::ExpectedNull)
556        }
557    }
558
559    // Unit struct means a named value containing no data.
560    fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
561    where
562        V: Visitor<'de>,
563    {
564        log!(LogLevel::Debug, "Deserialize unit struct");
565        self.deserialize_unit(visitor)
566    }
567
568    // As is done here, serializers are encouraged to treat newtype structs as
569    // insignificant wrappers around the data they contain. That means not
570    // parsing anything other than the contained value.
571    fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
572    where
573        V: Visitor<'de>,
574    {
575        visitor.visit_newtype_struct(self)
576    }
577
578    // Deserialization of compound types like sequences and maps happens by
579    // passing the visitor an "Access" object that gives it the ability to
580    // iterate through the data contained in the sequence.
581    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
582    where
583        V: Visitor<'de>,
584    {
585        log!(LogLevel::Debug, "Deserialize seq");
586        adjust_indentation!(1);
587        if let Some(key) = &self.array_key {
588            let value = visitor.visit_seq(VDFSeq::new(self, key.clone()))?;
589            adjust_indentation!(-1);
590            log!(LogLevel::Debug, "Deserialize seq end");
591            return Ok(value);
592        }
593
594        Err(Error::ExpectedMapKey)
595    }
596
597    // Tuples look just like sequences in JSON. Some formats may be able to
598    // represent tuples more efficiently.
599    //
600    // As indicated by the length parameter, the `Deserialize` implementation
601    // for a tuple in the Serde data model is required to know the length of the
602    // tuple before even looking at the input data.
603    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value>
604    where
605        V: Visitor<'de>,
606    {
607        log!(LogLevel::Debug, "Deserialize tuple");
608        self.deserialize_seq(visitor)
609    }
610
611    // Tuple structs look just like sequences in JSON.
612    fn deserialize_tuple_struct<V>(
613        self,
614        _name: &'static str,
615        _len: usize,
616        visitor: V,
617    ) -> Result<V::Value>
618    where
619        V: Visitor<'de>,
620    {
621        log!(LogLevel::Debug, "Deserialize tuple struct");
622        self.deserialize_seq(visitor)
623    }
624
625    // Much like `deserialize_seq` but calls the visitors `visit_map` method
626    // with a `MapAccess` implementation, rather than the visitor's `visit_seq`
627    // method with a `SeqAccess` implementation.
628    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
629    where
630        V: Visitor<'de>,
631    {
632        log!(
633            LogLevel::Debug,
634            "Deserialize map start - {:?}\n{}",
635            self.beginning,
636            self.input
637        );
638
639        self.beginning = false;
640
641        // Parse the opening brace of the map.
642        if self.next_expect_char('{')? {
643            adjust_indentation!(1);
644            // Give the visitor access to each entry of the map.
645            let value = visitor.visit_map(VDFMap::new(self))?;
646            // Parse the closing brace of the map.
647            if self.next_expect_char('}')? {
648                adjust_indentation!(-1);
649                log!(LogLevel::Debug, "Deserialize map end");
650                Ok(value)
651            } else {
652                Err(Error::ExpectedMapEnd)
653            }
654        } else {
655            Err(Error::ExpectedMap)
656        }
657    }
658
659    // Structs look just like maps in JSON.
660    //
661    // Notice the `fields` parameter - a "struct" in the Serde data model means
662    // that the `Deserialize` implementation is required to know what the fields
663    // are before even looking at the input data. Any key-value pairing in which
664    // the fields cannot be known ahead of time is probably a map.
665    fn deserialize_struct<V>(
666        self,
667        _name: &'static str,
668        _fields: &'static [&'static str],
669        visitor: V,
670    ) -> Result<V::Value>
671    where
672        V: Visitor<'de>,
673    {
674        log!(
675            LogLevel::Debug,
676            "Deserialize struct start - {:?}",
677            self.beginning
678        );
679
680        self.beginning = false;
681
682        let result = self.deserialize_map(visitor);
683
684        log!(LogLevel::Debug, "Deserialize struct end");
685
686        result
687    }
688
689    fn deserialize_enum<V>(
690        self,
691        _name: &'static str,
692        _variants: &'static [&'static str],
693        visitor: V,
694    ) -> Result<V::Value>
695    where
696        V: Visitor<'de>,
697    {
698        log!(LogLevel::Debug, "Deserialize enum");
699
700        if self.beginning && peek_expect_char(&self.input, 0, '{').unwrap_or(false) {
701            // Trim the first and last characters out.
702            self.input = &self.input[1..self.input.len() - 2];
703        }
704
705        self.beginning = false;
706
707        let value = parse_string(&self.input);
708        if let Ok((parsed_str, _)) = value {
709            println!(
710                "{:?} - {:?}",
711                self.input.chars(),
712                peek_real_char(self.input, 0)
713            );
714            if peek_expect_char(self.input, 0, '{').unwrap_or(false)
715                || peek_expect_char(self.input, 0, '"').unwrap_or(false)
716            {
717                log!(
718                    LogLevel::Debug,
719                    "Deserializing - Enum NewType/Tuple/Struct variant"
720                );
721                // Visit a newtype variant, tuple variant, or struct variant.
722                let value = visitor.visit_enum(Enum::new(self))?;
723                Ok(value)
724            } else {
725                // Visit a unit variant.
726                log!(LogLevel::Debug, "Deserializing - Enum Unit variant");
727                visitor.visit_enum(parsed_str.into_deserializer())
728            }
729        } else {
730            Err(Error::ExpectedEnum)
731        }
732    }
733
734    // An identifier in Serde is the type that identifies a field of a struct or
735    // the variant of an enum. In JSON, struct fields and enum variants are
736    // represented as strings. In other formats they may be represented as
737    // numeric indices.
738    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value>
739    where
740        V: Visitor<'de>,
741    {
742        log!(
743            LogLevel::Debug,
744            "Deserialize identifier: {:?}",
745            self.peek_str()
746        );
747        self.deserialize_str(visitor)
748    }
749
750    // Like `deserialize_any` but indicates to the `Deserializer` that it makes
751    // no difference which `Visitor` method is called because the data is
752    // ignored.
753    //
754    // Some deserializers are able to implement this more efficiently than
755    // `deserialize_any`, for example by rapidly skipping over matched
756    // delimiters without paying close attention to the data in between.
757    //
758    // Some formats are not able to implement this at all. Formats that can
759    // implement `deserialize_any` and `deserialize_ignored_any` are known as
760    // self-describing.
761    fn deserialize_ignored_any<V>(self, _visitor: V) -> Result<V::Value>
762    where
763        V: Visitor<'de>,
764    {
765        // panic!("deserialize_ignored_any not supported");
766        Err(Error::UnsupportedSelfDiscribing)
767    }
768}
769
770// In order to handle commas correctly when deserializing a JSON array or map,
771// we need to track whether we are on the first element or past the first
772// element.
773struct VDFSeq<'a, 'de: 'a> {
774    de: &'a mut Deserializer<'de>,
775    first: bool,
776    key: String,
777}
778
779impl<'a, 'de> VDFSeq<'a, 'de> {
780    fn new(de: &'a mut Deserializer<'de>, key: String) -> Self {
781        Self {
782            de,
783            first: true,
784            key,
785        }
786    }
787}
788
789// `SeqAccess` is provided to the `Visitor` to give it the ability to iterate
790// through elements of the sequence.
791impl<'de, 'a> SeqAccess<'de> for VDFSeq<'a, 'de> {
792    type Error = Error;
793
794    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
795    where
796        T: DeserializeSeed<'de>,
797    {
798        log!(LogLevel::Debug, "--- Seq Access Element ---");
799        log!(LogLevel::Debug, "Next element seed");
800        if self.de.peek_real_char()? == '}' {
801            // End of the map.
802            log!(LogLevel::Debug, "End of Seq");
803            log!(LogLevel::Debug, "--- Seq Access Element End ---");
804            return Ok(None);
805        }
806        if !self.first && !self.de.peek_expect_str(&self.key)? {
807            log!(LogLevel::Debug, "End of Seq - {:?}", self.key);
808            log!(LogLevel::Debug, "--- Seq Access Element End ---");
809            return Ok(None);
810        }
811
812        // Strip the key out.
813        log!(
814            LogLevel::Debug,
815            "Stripping key: {:?} - {}",
816            self.key,
817            !self.first
818        );
819        if !self.first && !self.de.next_expect_string(&self.key)? {
820            return Err(Error::ExpectedString);
821        }
822
823        self.first = false;
824
825        // Deserialize an array element.
826        let result = seed.deserialize(&mut *self.de).map(Some);
827        log!(LogLevel::Debug, "--- Seq Access Element End ---");
828        result
829    }
830}
831
832// In order to handle commas correctly when deserializing a JSON array or map,
833// we need to track whether we are on the first element or past the first
834// element.
835struct VDFMap<'a, 'de: 'a> {
836    de: &'a mut Deserializer<'de>,
837    first: bool,
838}
839
840impl<'a, 'de> VDFMap<'a, 'de> {
841    fn new(de: &'a mut Deserializer<'de>) -> Self {
842        Self { de, first: true }
843    }
844}
845
846// `MapAccess` is provided to the `Visitor` to give it the ability to iterate
847// through entries of the map.
848impl<'de, 'a> MapAccess<'de> for VDFMap<'a, 'de> {
849    type Error = Error;
850
851    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
852    where
853        K: DeserializeSeed<'de>,
854    {
855        // Check if there are no more entries.
856        if self.de.peek_real_char()? == '}' {
857            return Ok(None);
858        }
859        log!(LogLevel::Debug, "Next key seed");
860        // Comma is required before every entry except the first.
861        self.first = false;
862        // Deserialize a map key.
863        seed.deserialize(&mut *self.de).map(Some)
864    }
865
866    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
867    where
868        V: DeserializeSeed<'de>,
869    {
870        log!(LogLevel::Debug, "Next value seed");
871        // Deserialize a map value.
872        seed.deserialize(&mut *self.de)
873    }
874}
875
876struct Enum<'a, 'de: 'a> {
877    de: &'a mut Deserializer<'de>,
878}
879
880impl<'a, 'de> Enum<'a, 'de> {
881    fn new(de: &'a mut Deserializer<'de>) -> Self {
882        Enum { de }
883    }
884}
885
886// `EnumAccess` is provided to the `Visitor` to give it the ability to determine
887// which variant of the enum is supposed to be deserialized.
888//
889// Note that all enum deserialization methods in Serde refer exclusively to the
890// "externally tagged" enum representation.
891impl<'de, 'a> EnumAccess<'de> for Enum<'a, 'de> {
892    type Error = Error;
893    type Variant = Self;
894
895    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
896    where
897        V: DeserializeSeed<'de>,
898    {
899        // Err(Error::UnsupportedEnums)
900        log!(LogLevel::Debug, "Variant seed");
901        // The `deserialize_enum` method parsed a `{` character so we are
902        // currently inside of a map. The seed will be deserializing itself from
903        // the key of the map.
904        let val = seed.deserialize(&mut *self.de);
905        match val {
906            Ok(val) => Ok((val, self)),
907            Err(_) => Err(Error::ExpectedEnum),
908        }
909    }
910}
911
912// `VariantAccess` is provided to the `Visitor` to give it the ability to see
913// the content of the single variant that it decided to deserialize.
914impl<'de, 'a> VariantAccess<'de> for Enum<'a, 'de> {
915    type Error = Error;
916
917    // If the `Visitor` expected this variant to be a unit variant, the input
918    // should have been the plain string case handled in `deserialize_enum`.
919    fn unit_variant(self) -> Result<()> {
920        log!(LogLevel::Error, "Unit variant");
921        Err(Error::UnsupportedEnums)
922    }
923
924    // Newtype variants are represented in JSON as `{ NAME: VALUE }` so
925    // deserialize the value here.
926    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
927    where
928        T: DeserializeSeed<'de>,
929    {
930        seed.deserialize(self.de)
931    }
932
933    // Tuple variants are represented in JSON as `{ NAME: [DATA...] }` so
934    // deserialize the sequence of data here.
935    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value>
936    where
937        V: Visitor<'de>,
938    {
939        de::Deserializer::deserialize_seq(self.de, visitor)
940    }
941
942    // Struct variants are represented in JSON as `{ NAME: { K: V, ... } }` so
943    // deserialize the inner map here.
944    fn struct_variant<V>(self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
945    where
946        V: Visitor<'de>,
947    {
948        de::Deserializer::deserialize_map(self.de, visitor)
949    }
950}
951
952////////////////////////////////////////////////////////////////////////////////
953
954#[cfg(test)]
955mod tests {
956    use super::*;
957    mod enums {
958        use super::*;
959
960        #[derive(Deserialize, PartialEq, Debug)]
961        enum UnitEnum {
962            A,
963            B,
964        }
965
966        #[derive(Deserialize, PartialEq, Debug)]
967        enum NewtypeEnum {
968            A(u32),
969            B(u32),
970        }
971
972        #[derive(Deserialize, PartialEq, Debug)]
973        enum TupleEnum {
974            A(u32, u32),
975            B(u32, u32),
976        }
977
978        #[derive(Deserialize, PartialEq, Debug)]
979        enum StructEnum {
980            A { a: u32, b: u32 },
981            B { a: u32, b: u32 },
982        }
983
984        #[test]
985        fn unsupported_unit_enum() {
986            let expected_str = r#""A""#;
987            let result = from_str::<UnitEnum>(expected_str).is_err();
988            assert!(result);
989        }
990
991        #[test]
992        fn supported_newtype_enum() {
993            let expected_str = r#""A" "1""#;
994            let expected = NewtypeEnum::A(1);
995            let result = from_str::<NewtypeEnum>(expected_str).unwrap();
996            assert_eq!(expected, result);
997        }
998
999        #[test]
1000        fn supported_tuple_enum() {
1001            let expected_str = r#""A" "1" "A" "2""#;
1002            let expected = TupleEnum::A(1, 2);
1003            let result = from_str::<TupleEnum>(expected_str).unwrap();
1004            log!(LogLevel::Debug, "{:?}", result);
1005            assert_eq!(expected, result);
1006        }
1007
1008        #[test]
1009        fn supported_struct_enum() {
1010            let expected_str = r#""A" { "a" "1" "b" "2" }"#;
1011            let expected = StructEnum::A { a: 1, b: 2 };
1012            let result = from_str::<StructEnum>(expected_str).unwrap();
1013            log!(LogLevel::Debug, "{:?}", result);
1014            assert_eq!(expected, result);
1015        }
1016    }
1017
1018    mod primitives {
1019        use super::*;
1020
1021        #[test]
1022        fn supported_string() {
1023            let expected_str = r#""Hello, World!""#;
1024            let expected = "Hello, World!";
1025            let result = from_str::<String>(expected_str).unwrap();
1026            assert_eq!(expected, result);
1027        }
1028
1029        #[test]
1030        fn support_char() {
1031            let expected_str = r#""a""#;
1032            let expected = 'a';
1033            let result = from_str::<char>(expected_str).unwrap();
1034            assert_eq!(expected, result);
1035        }
1036
1037        #[test]
1038        fn supported_bool_true() {
1039            assert_eq!(true, from_str("1").unwrap());
1040        }
1041
1042        #[test]
1043        fn supported_bool_false() {
1044            assert_eq!(false, from_str("0").unwrap());
1045        }
1046
1047        #[test]
1048        fn test_f32() {
1049            let input: f32 = from_str("127.24").unwrap();
1050            assert_eq!(127.24f32, input);
1051        }
1052
1053        #[test]
1054        fn test_f64() {
1055            let input: f64 = from_str("123.24").unwrap();
1056            assert_eq!(123.24f64, input);
1057        }
1058
1059        #[test]
1060        fn test_i8() {
1061            let input: i8 = from_str("127").unwrap();
1062            assert_eq!(127, input);
1063        }
1064
1065        #[test]
1066        fn test_i16() {
1067            let input: i16 = from_str("32767").unwrap();
1068            assert_eq!(32767, input);
1069        }
1070
1071        #[test]
1072        fn test_i32() {
1073            let input: i32 = from_str("2147483647").unwrap();
1074            assert_eq!(2147483647, input);
1075        }
1076
1077        #[test]
1078        fn test_i64() {
1079            let input: i64 = from_str("9223372036854775807").unwrap();
1080            assert_eq!(9223372036854775807, input);
1081        }
1082
1083        #[test]
1084        fn test_u8() {
1085            let input: u8 = from_str("255").unwrap();
1086            assert_eq!(255, input);
1087        }
1088
1089        #[test]
1090        fn test_u16() {
1091            let input: u16 = from_str("65535").unwrap();
1092            assert_eq!(65535, input);
1093        }
1094
1095        #[test]
1096        fn test_u32() {
1097            let input: u32 = from_str("4294967295").unwrap();
1098            assert_eq!(4294967295, input);
1099        }
1100
1101        #[test]
1102        fn test_u64() {
1103            let input: u64 = from_str("18446744073709551615").unwrap();
1104            assert_eq!(18446744073709551615, input);
1105        }
1106    }
1107
1108    mod structs {
1109        use super::*;
1110
1111        #[derive(Deserialize, PartialEq, Debug)]
1112        struct TestItem {
1113            name: String,
1114            value: u32,
1115        }
1116
1117        #[derive(Deserialize, PartialEq, Debug)]
1118        struct TestNestedData {
1119            int: u32,
1120            seq: Vec<TestItem>,
1121        }
1122
1123        #[derive(Deserialize, PartialEq, Debug)]
1124        struct TestData {
1125            int: u32,
1126            seq: Vec<String>,
1127        }
1128
1129        #[derive(Deserialize, PartialEq, Debug)]
1130        struct NestedContainer {
1131            test: TestNestedData,
1132        }
1133        #[derive(Deserialize, PartialEq, Debug)]
1134        struct Container {
1135            test: TestData,
1136        }
1137
1138        #[test]
1139        fn test_struct_perfect_order() {
1140            println!("Test 1 - Perfectly Ordered Data Set.");
1141            let expected_str = r#"
1142            "test"
1143            {
1144                "int"       "1"
1145                "seq"       "a"
1146                "seq"       "b"
1147            }"#;
1148            let expected = Container {
1149                test: TestData {
1150                    int: 1,
1151                    seq: vec!["a".to_owned(), "b".to_owned()],
1152                },
1153            };
1154            let result = from_str(expected_str).unwrap();
1155            log!(LogLevel::Debug, "{:?}", result);
1156            assert_eq!(expected, result);
1157        }
1158
1159        #[test]
1160        fn test_struct_unordered() {
1161            println!("Test 2 - Unordered Data Set.");
1162            let expected_str = r#"
1163            "test"
1164            {
1165                "seq"    "a"
1166                "seq"    "b"
1167                "int"    "1"
1168            }"#;
1169            let expected = Container {
1170                test: TestData {
1171                    int: 1,
1172                    seq: vec!["a".to_owned(), "b".to_owned()],
1173                },
1174            };
1175            let result = from_str(expected_str).unwrap();
1176            log!(LogLevel::Debug, "{:?}", result);
1177            assert_eq!(expected, result);
1178        }
1179
1180        #[test]
1181        fn test_struct_mixed() {
1182            println!("Test 3 - Mixed Data Set.");
1183            let expected_str = r#"
1184            "test"
1185            {
1186                "seq"    "a"
1187                "int"    "1"
1188                "seq"    "b"
1189            }"#;
1190            let expected = Container {
1191                test: TestData {
1192                    int: 1,
1193                    seq: vec!["a".to_owned(), "b".to_owned()],
1194                },
1195            };
1196            let result = from_str(expected_str).unwrap();
1197            log!(LogLevel::Debug, "{:?}", result);
1198            assert_eq!(expected, result);
1199        }
1200
1201        #[test]
1202        fn test_nested_struct_perfect_order() {
1203            println!("Test 1 - Perfectly Ordered Data Set.");
1204            let expected_str = r#"
1205            "test"
1206            {
1207                "int"    "1"
1208                "seq"
1209                {
1210                    "name"    "a"
1211                    "value"    "1"
1212                }
1213                "seq"
1214                {
1215                    "name"    "b"
1216                    "value"    "2"
1217                }
1218            }"#;
1219            let expected = NestedContainer {
1220                test: TestNestedData {
1221                    int: 1,
1222                    seq: vec![
1223                        TestItem {
1224                            name: "a".to_owned(),
1225                            value: 1,
1226                        },
1227                        TestItem {
1228                            name: "b".to_owned(),
1229                            value: 2,
1230                        },
1231                    ],
1232                },
1233            };
1234            let result: NestedContainer = from_str(expected_str).unwrap();
1235            log!(LogLevel::Debug, "{:?}", result);
1236            assert_eq!(expected, result);
1237        }
1238
1239        #[test]
1240        fn test_nested_struct_unordered() {
1241            println!("Test 2 - Unordered Data Set.");
1242            let expected_str = r#"
1243            "test"
1244            {
1245                "seq"
1246                {
1247                    "name"    "a"
1248                    "value"    "1"
1249                }
1250                "seq"
1251                {
1252                    "name"    "b"
1253                    "value"    "2"
1254                }
1255                "int"    "1"
1256            }"#;
1257            let expected = NestedContainer {
1258                test: TestNestedData {
1259                    int: 1,
1260                    seq: vec![
1261                        TestItem {
1262                            name: "a".to_owned(),
1263                            value: 1,
1264                        },
1265                        TestItem {
1266                            name: "b".to_owned(),
1267                            value: 2,
1268                        },
1269                    ],
1270                },
1271            };
1272            let result = from_str(expected_str).unwrap();
1273            log!(LogLevel::Debug, "{:?}", result);
1274            assert_eq!(expected, result);
1275        }
1276    }
1277}