1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 use crate::reader::{BytesReader, Cacheable, IoReader, SliceReader};
15 use serde::de;
16 use serde::de::{
17     DeserializeOwned, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess,
18     VariantAccess, Visitor,
19 };
20 use serde::Deserialize;
21 use std::io::Read;
22 
23 use crate::{consts::*, error::*, states::*, Number, ParseError::*};
24 
25 #[cfg(feature = "c_adapter")]
26 type JsonString = CString;
27 #[cfg(not(feature = "c_adapter"))]
28 type JsonString = String;
29 
30 impl Number {
visit<'de, V>(self, visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>,31     fn visit<'de, V>(self, visitor: V) -> Result<V::Value, Error>
32     where
33         V: Visitor<'de>,
34     {
35         match self {
36             Number::Unsigned(x) => visitor.visit_u64(x),
37             Number::Signed(x) => visitor.visit_i64(x),
38             Number::Float(x) => visitor.visit_f64(x),
39         }
40     }
41 }
42 
43 /// A struct that can deserialize JSON into Rust values of user's types.
44 pub(crate) struct Deserializer<R>
45 where
46     R: BytesReader + Cacheable,
47 {
48     pub(crate) reader: R,
49     pub(crate) recursion_depth: u32,
50 }
51 
52 impl<R> Deserializer<R>
53 where
54     R: BytesReader + Cacheable,
55 {
56     /// Creates a new instance of Deserializer.
57     /// This method is usually used in the following methods:
58     /// - Deserializer::new_from_reader
59     /// - Deserializer::new_from_slice
new(reader: R) -> Self60     pub fn new(reader: R) -> Self {
61         Deserializer {
62             reader,
63             recursion_depth: 0,
64         }
65     }
66 }
67 
68 /// Creates an instance of Deserializer from reader.
69 impl<R: Read> Deserializer<IoReader<R>> {
new_from_io(reader: R) -> Self70     pub fn new_from_io(reader: R) -> Self {
71         Deserializer::new(IoReader::new(reader))
72     }
73 }
74 
75 /// Creates an instance of Deserializer from slice.
76 impl<'a> Deserializer<SliceReader<'a>> {
new_from_slice(slice: &'a [u8]) -> Self77     pub fn new_from_slice(slice: &'a [u8]) -> Self {
78         Deserializer::new(SliceReader::new(slice))
79     }
80 }
81 
82 /// Deserializes an instance of type `T` from an IO stream of JSON.
83 /// # Example
84 /// ```not run
85 /// use serde::Deserialize;
86 /// use std::fs::File;
87 /// use ylong_json::from_reader;
88 ///
89 /// #[derive(Deserialize, PartialEq, Debug)]
90 /// struct Test {
91 ///     int: u32,
92 ///     seq: Vec<String>,
93 ///     tup: (i32, i32, i32),
94 /// }
95 ///
96 /// let expected = Test {
97 ///     int: 1,
98 ///     seq: vec![String::from("abcd"), String::from("efgh")],
99 ///     tup: (1, 2, 3),
100 /// };
101 /// let file = File::open("./test.txt").unwrap();
102 /// assert_eq!(expected, from_reader(file).unwrap());
103 /// ```
from_reader<R, T>(reader: R) -> Result<T, Error> where R: Read, T: DeserializeOwned,104 pub fn from_reader<R, T>(reader: R) -> Result<T, Error>
105 where
106     R: Read,
107     T: DeserializeOwned,
108 {
109     let mut deserializer = Deserializer::new_from_io(reader);
110     let t = T::deserialize(&mut deserializer)?;
111     match eat_whitespace_until_not!(deserializer) {
112         None => Ok(t),
113         _ => Err(Error::Parsing(ParsingUnfinished)),
114     }
115 }
116 
117 /// Deserializes an instance of type `T` from bytes.
118 /// # Example
119 /// ```
120 /// use serde::Deserialize;
121 /// use ylong_json::from_slice;
122 ///
123 /// #[derive(Deserialize, PartialEq, Debug)]
124 /// struct Test {
125 ///     int: u32,
126 ///     seq: Vec<String>,
127 ///     tup: (i32, i32, i32),
128 /// }
129 ///
130 /// let slice = r#"{"int":1,"seq":["abcd","efgh"],"tup":[1,2,3]}"#.as_bytes();
131 /// let expected = Test {
132 ///     int: 1,
133 ///     seq: vec![String::from("abcd"), String::from("efgh")],
134 ///     tup: (1, 2, 3),
135 /// };
136 /// assert_eq!(expected, from_slice(slice).unwrap())
137 /// ```
from_slice<'a, T>(slice: &'a [u8]) -> Result<T, Error> where T: Deserialize<'a>,138 pub fn from_slice<'a, T>(slice: &'a [u8]) -> Result<T, Error>
139 where
140     T: Deserialize<'a>,
141 {
142     let mut deserializer = Deserializer::new_from_slice(slice);
143     let t = T::deserialize(&mut deserializer)?;
144     match eat_whitespace_until_not!(deserializer) {
145         None => Ok(t),
146         _ => {
147             unexpected_character!(&mut deserializer)
148         }
149     }
150 }
151 
152 /// Deserializes an instance of type `T` from str.
153 /// # Example
154 /// ```
155 /// use serde::Deserialize;
156 /// use ylong_json::from_str;
157 ///
158 /// #[derive(Deserialize, PartialEq, Debug)]
159 /// struct Test {
160 ///     int: u32,
161 ///     seq: Vec<String>,
162 ///     tup: (i32, i32, i32),
163 /// }
164 ///
165 /// let str = r#"{"int":1,"seq":["abcd","efgh"],"tup":[1,2,3]}"#;
166 /// let expected = Test {
167 ///     int: 1,
168 ///     seq: vec![String::from("abcd"), String::from("efgh")],
169 ///     tup: (1, 2, 3),
170 /// };
171 /// assert_eq!(expected, from_str(str).unwrap())
172 /// ```
from_str<'a, T>(str: &'a str) -> Result<T, Error> where T: Deserialize<'a>,173 pub fn from_str<'a, T>(str: &'a str) -> Result<T, Error>
174 where
175     T: Deserialize<'a>,
176 {
177     from_slice(str.as_bytes())
178 }
179 
180 impl<R> Deserializer<R>
181 where
182     R: BytesReader + Cacheable,
183 {
184     // Look at the next character without moving cursor.
peek_char(&mut self) -> Result<Option<u8>, Error>185     fn peek_char(&mut self) -> Result<Option<u8>, Error> {
186         self.reader.peek().map_err(Error::new_reader)
187     }
188 
189     // Get the next character and move the cursor to the next place.
next_char(&mut self) -> Result<Option<u8>, Error>190     fn next_char(&mut self) -> Result<Option<u8>, Error> {
191         self.reader.next().map_err(Error::new_reader)
192     }
193 
194     // Discard the next character and move the cursor to the next place.
discard_char(&mut self)195     fn discard_char(&mut self) {
196         self.reader.discard();
197     }
198 
199     // Parse value of bool, `true` or `false`.
parse_bool(&mut self) -> Result<bool, Error>200     fn parse_bool(&mut self) -> Result<bool, Error> {
201         let peek_ch = match eat_whitespace_until_not!(self) {
202             Some(ch) => ch,
203             None => {
204                 return Err(Error::Parsing(ParsingUnfinished));
205             }
206         };
207 
208         match peek_ch {
209             b't' => {
210                 self.reader.discard();
211                 match_str!(self, b"rue");
212                 Ok(true)
213             }
214             b'f' => {
215                 self.reader.discard();
216                 match_str!(self, b"alse");
217                 Ok(false)
218             }
219             _ => {
220                 unexpected_character!(self)
221             }
222         }
223     }
224 
de_parse_number<'de, V>(&mut self, visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>,225     fn de_parse_number<'de, V>(&mut self, visitor: V) -> Result<V::Value, Error>
226     where
227         V: Visitor<'de>,
228     {
229         let peek_ch = match eat_whitespace_until_not!(self) {
230             Some(ch) => ch,
231             None => {
232                 return Err(Error::Parsing(ParsingUnfinished));
233             }
234         };
235 
236         match peek_ch {
237             b'-' => parse_number(self)?.visit(visitor),
238             b'0'..=b'9' => parse_number(self)?.visit(visitor),
239             _ => unexpected_character!(self),
240         }
241     }
242 
de_parse_string(&mut self) -> Result<JsonString, Error>243     fn de_parse_string(&mut self) -> Result<JsonString, Error> {
244         match self.peek_char()? {
245             Some(b'"') => self.discard_char(),
246             _ => return unexpected_character!(self),
247         }
248         parse_string(self)
249     }
250 }
251 
252 impl<'de, 'a, R> de::Deserializer<'de> for &'a mut Deserializer<R>
253 where
254     R: BytesReader + Cacheable,
255 {
256     type Error = Error;
257 
258     // Choose a parsing method to parse value based on the input data.
deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,259     fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
260     where
261         V: Visitor<'de>,
262     {
263         let peek_ch = match eat_whitespace_until_not!(self) {
264             Some(ch) => ch,
265             None => {
266                 return Err(Error::Parsing(ParsingUnfinished));
267             }
268         };
269 
270         match peek_ch {
271             b'n' => self.deserialize_unit(visitor),
272             b't' | b'f' => self.deserialize_bool(visitor),
273             b'"' => self.deserialize_str(visitor),
274             b'0'..=b'9' => self.deserialize_u64(visitor),
275             b'-' => self.deserialize_i64(visitor),
276             b'[' => self.deserialize_seq(visitor),
277             b'{' => self.deserialize_map(visitor),
278             _ => unexpected_character!(self),
279         }
280     }
281 
deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,282     fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
283     where
284         V: Visitor<'de>,
285     {
286         visitor.visit_bool(self.parse_bool()?)
287     }
288 
deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,289     fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
290     where
291         V: Visitor<'de>,
292     {
293         self.de_parse_number(visitor)
294     }
295 
deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,296     fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
297     where
298         V: Visitor<'de>,
299     {
300         self.de_parse_number(visitor)
301     }
302 
deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,303     fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
304     where
305         V: Visitor<'de>,
306     {
307         self.de_parse_number(visitor)
308     }
309 
deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,310     fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
311     where
312         V: Visitor<'de>,
313     {
314         self.de_parse_number(visitor)
315     }
316 
deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,317     fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
318     where
319         V: Visitor<'de>,
320     {
321         self.de_parse_number(visitor)
322     }
323 
deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,324     fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
325     where
326         V: Visitor<'de>,
327     {
328         self.de_parse_number(visitor)
329     }
330 
deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,331     fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
332     where
333         V: Visitor<'de>,
334     {
335         self.de_parse_number(visitor)
336     }
337 
deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,338     fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
339     where
340         V: Visitor<'de>,
341     {
342         self.de_parse_number(visitor)
343     }
344 
deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,345     fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
346     where
347         V: Visitor<'de>,
348     {
349         self.de_parse_number(visitor)
350     }
351 
deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,352     fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
353     where
354         V: Visitor<'de>,
355     {
356         self.de_parse_number(visitor)
357     }
358 
deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,359     fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
360     where
361         V: Visitor<'de>,
362     {
363         self.deserialize_str(visitor)
364     }
365 
deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,366     fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
367     where
368         V: Visitor<'de>,
369     {
370         let str = self.de_parse_string()?;
371         #[cfg(feature = "c_adapter")]
372         return visitor.visit_str(str.to_str()?);
373 
374         #[cfg(not(feature = "c_adapter"))]
375         visitor.visit_str(str.as_str())
376     }
377 
deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,378     fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
379     where
380         V: Visitor<'de>,
381     {
382         self.deserialize_str(visitor)
383     }
384 
deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,385     fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
386     where
387         V: Visitor<'de>,
388     {
389         let peek_ch = match eat_whitespace_until_not!(self) {
390             Some(ch) => ch,
391             None => {
392                 return Err(Error::Parsing(ParsingUnfinished));
393             }
394         };
395 
396         match peek_ch {
397             b'"' => {
398                 let v = parse_string_inner(self)?;
399                 visitor.visit_bytes(&v)
400             }
401             b'[' => self.deserialize_seq(visitor),
402             _ => unexpected_character!(self),
403         }
404     }
405 
deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,406     fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
407     where
408         V: Visitor<'de>,
409     {
410         self.deserialize_bytes(visitor)
411     }
412 
deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,413     fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
414     where
415         V: Visitor<'de>,
416     {
417         let peek_ch = match eat_whitespace_until_not!(self) {
418             Some(ch) => ch,
419             None => {
420                 return Err(Error::Parsing(ParsingUnfinished));
421             }
422         };
423 
424         match peek_ch {
425             b'n' => {
426                 self.discard_char();
427                 match_str!(self, b"ull");
428                 visitor.visit_none()
429             }
430             _ => visitor.visit_some(self),
431         }
432     }
433 
deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,434     fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
435     where
436         V: Visitor<'de>,
437     {
438         let peek_ch = match eat_whitespace_until_not!(self) {
439             Some(ch) => ch,
440             None => {
441                 return Err(Error::Parsing(ParsingUnfinished));
442             }
443         };
444 
445         match peek_ch {
446             b'n' => {
447                 self.discard_char();
448                 match_str!(self, b"ull");
449                 visitor.visit_unit()
450             }
451             _ => unexpected_character!(self),
452         }
453     }
454 
deserialize_unit_struct<V>( self, _name: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>,455     fn deserialize_unit_struct<V>(
456         self,
457         _name: &'static str,
458         visitor: V,
459     ) -> Result<V::Value, Self::Error>
460     where
461         V: Visitor<'de>,
462     {
463         self.deserialize_unit(visitor)
464     }
465 
deserialize_newtype_struct<V>( self, _name: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>,466     fn deserialize_newtype_struct<V>(
467         self,
468         _name: &'static str,
469         visitor: V,
470     ) -> Result<V::Value, Self::Error>
471     where
472         V: Visitor<'de>,
473     {
474         visitor.visit_newtype_struct(self)
475     }
476 
deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,477     fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
478     where
479         V: Visitor<'de>,
480     {
481         let peek_ch = match eat_whitespace_until_not!(self) {
482             Some(ch) => ch,
483             None => {
484                 return Err(Error::Parsing(ParsingUnfinished));
485             }
486         };
487 
488         match peek_ch {
489             b'[' => {
490                 self.discard_char();
491                 let value = visitor.visit_seq(SeqAssistant::new(self))?;
492 
493                 let peek_ch_inner = match eat_whitespace_until_not!(self) {
494                     Some(ch) => ch,
495                     None => {
496                         return Err(Error::Parsing(ParsingUnfinished));
497                     }
498                 };
499 
500                 match peek_ch_inner {
501                     b']' => {
502                         self.discard_char();
503                         Ok(value)
504                     }
505                     _ => unexpected_character!(self),
506                 }
507             }
508             _ => unexpected_character!(self),
509         }
510     }
511 
deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,512     fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
513     where
514         V: Visitor<'de>,
515     {
516         self.deserialize_seq(visitor)
517     }
518 
deserialize_tuple_struct<V>( self, _name: &'static str, _len: usize, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>,519     fn deserialize_tuple_struct<V>(
520         self,
521         _name: &'static str,
522         _len: usize,
523         visitor: V,
524     ) -> Result<V::Value, Self::Error>
525     where
526         V: Visitor<'de>,
527     {
528         self.deserialize_seq(visitor)
529     }
530 
deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,531     fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
532     where
533         V: Visitor<'de>,
534     {
535         let peek_ch = match eat_whitespace_until_not!(self) {
536             Some(ch) => ch,
537             None => {
538                 return Err(Error::Parsing(ParsingUnfinished));
539             }
540         };
541 
542         match peek_ch {
543             b'{' => {
544                 self.discard_char();
545                 let value = visitor.visit_map(SeqAssistant::new(self))?;
546 
547                 let peek_ch_inner = match eat_whitespace_until_not!(self) {
548                     Some(ch) => ch,
549                     None => {
550                         return Err(Error::Parsing(ParsingUnfinished));
551                     }
552                 };
553 
554                 match peek_ch_inner {
555                     b'}' => {
556                         self.discard_char();
557                         Ok(value)
558                     }
559                     _ => unexpected_character!(self),
560                 }
561             }
562             _ => unexpected_character!(self),
563         }
564     }
565 
deserialize_struct<V>( self, _name: &'static str, _fields: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>,566     fn deserialize_struct<V>(
567         self,
568         _name: &'static str,
569         _fields: &'static [&'static str],
570         visitor: V,
571     ) -> Result<V::Value, Self::Error>
572     where
573         V: Visitor<'de>,
574     {
575         self.deserialize_map(visitor)
576     }
577 
deserialize_enum<V>( self, _name: &'static str, _variants: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>,578     fn deserialize_enum<V>(
579         self,
580         _name: &'static str,
581         _variants: &'static [&'static str],
582         visitor: V,
583     ) -> Result<V::Value, Self::Error>
584     where
585         V: Visitor<'de>,
586     {
587         let peek_ch = match eat_whitespace_until_not!(self) {
588             Some(ch) => ch,
589             None => {
590                 return Err(Error::Parsing(ParsingUnfinished));
591             }
592         };
593 
594         match peek_ch {
595             b'"' => {
596                 #[cfg(feature = "c_adapter")]
597                 return visitor
598                     .visit_enum(self.de_parse_string()?.into_string()?.into_deserializer());
599 
600                 #[cfg(not(feature = "c_adapter"))]
601                 visitor.visit_enum(self.de_parse_string()?.into_deserializer())
602             }
603             _ => {
604                 if self.next_char()? == Some(b'{') {
605                     eat_whitespace_until_not!(self);
606                     let value = visitor.visit_enum(EnumAssistant::new(self))?;
607                     eat_whitespace_until_not!(self);
608 
609                     if self.next_char()? == Some(b'}') {
610                         Ok(value)
611                     } else {
612                         unexpected_character!(self)
613                     }
614                 } else {
615                     unexpected_character!(self)
616                 }
617             }
618         }
619     }
620 
deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,621     fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
622     where
623         V: Visitor<'de>,
624     {
625         self.deserialize_str(visitor)
626     }
627 
deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,628     fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
629     where
630         V: Visitor<'de>,
631     {
632         self.deserialize_any(visitor)
633     }
634 }
635 
636 struct SeqAssistant<'a, R: 'a>
637 where
638     R: BytesReader + Cacheable,
639 {
640     deserializer: &'a mut Deserializer<R>,
641     is_first: bool,
642 }
643 
644 impl<'a, R: 'a> SeqAssistant<'a, R>
645 where
646     R: BytesReader + Cacheable,
647 {
new(deserializer: &'a mut Deserializer<R>) -> Self648     fn new(deserializer: &'a mut Deserializer<R>) -> Self {
649         SeqAssistant {
650             deserializer,
651             is_first: true,
652         }
653     }
654 }
655 
656 impl<'de, 'a, R> SeqAccess<'de> for SeqAssistant<'a, R>
657 where
658     R: BytesReader + Cacheable,
659 {
660     type Error = Error;
661 
next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> where T: DeserializeSeed<'de>,662     fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
663     where
664         T: DeserializeSeed<'de>,
665     {
666         let peek_ch = match eat_whitespace_until_not!(self.deserializer) {
667             Some(b']') => return Ok(None),
668             Some(b',') if !self.is_first => {
669                 self.deserializer.discard_char();
670                 eat_whitespace_until_not!(self.deserializer)
671             }
672             Some(ch) => {
673                 if self.is_first {
674                     self.is_first = false;
675                     Some(ch)
676                 } else {
677                     let position = self.deserializer.reader.position();
678                     return Err(Error::Parsing(MissingComma(
679                         position.line(),
680                         position.column(),
681                     )));
682                 }
683             }
684             None => return Err(Error::Parsing(ParsingUnfinished)),
685         };
686 
687         match peek_ch {
688             Some(b']') => {
689                 let position = self.deserializer.reader.position();
690                 Err(Error::Parsing(TrailingComma(
691                     position.line(),
692                     position.column(),
693                 )))
694             }
695             Some(_) => Ok(Some(seed.deserialize(&mut *self.deserializer)?)),
696             None => Err(Error::Parsing(ParsingUnfinished)),
697         }
698     }
699 }
700 
701 impl<'de, 'a, R> MapAccess<'de> for SeqAssistant<'a, R>
702 where
703     R: BytesReader + Cacheable,
704 {
705     type Error = Error;
706 
next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> where K: DeserializeSeed<'de>,707     fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
708     where
709         K: DeserializeSeed<'de>,
710     {
711         let peek_ch = match eat_whitespace_until_not!(self.deserializer) {
712             Some(b'}') => return Ok(None),
713             Some(b',') if !self.is_first => {
714                 self.deserializer.discard_char();
715                 eat_whitespace_until_not!(self.deserializer)
716             }
717             Some(ch) => {
718                 if self.is_first {
719                     self.is_first = false;
720                     Some(ch)
721                 } else {
722                     let position = self.deserializer.reader.position();
723                     return Err(Error::Parsing(MissingComma(
724                         position.line(),
725                         position.column(),
726                     )));
727                 }
728             }
729             None => {
730                 return Err(Error::Parsing(ParsingUnfinished));
731             }
732         };
733 
734         match peek_ch {
735             Some(b'"') => Ok(Some(seed.deserialize(&mut *self.deserializer)?)),
736             Some(b'}') => {
737                 let position = self.deserializer.reader.position();
738                 Err(Error::Parsing(TrailingComma(
739                     position.line(),
740                     position.column(),
741                 )))
742             }
743             // Object key must be String.
744             _ => unexpected_character!(self.deserializer),
745         }
746     }
747 
next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error> where V: DeserializeSeed<'de>,748     fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
749     where
750         V: DeserializeSeed<'de>,
751     {
752         match eat_whitespace_until_not!(self.deserializer) {
753             Some(b':') => {
754                 self.deserializer.discard_char();
755                 eat_whitespace_until_not!(self.deserializer);
756                 seed.deserialize(&mut *self.deserializer)
757             }
758             Some(_ch) => {
759                 let position = self.deserializer.reader.position();
760                 Err(Error::Parsing(MissingColon(
761                     position.line(),
762                     position.column(),
763                 )))
764             }
765             None => Err(Error::Parsing(ParsingUnfinished)),
766         }
767     }
768 }
769 
770 struct EnumAssistant<'a, R: 'a>
771 where
772     R: BytesReader + Cacheable,
773 {
774     deserializer: &'a mut Deserializer<R>,
775 }
776 
777 impl<'a, R: 'a> EnumAssistant<'a, R>
778 where
779     R: BytesReader + Cacheable,
780 {
new(deserializer: &'a mut Deserializer<R>) -> Self781     fn new(deserializer: &'a mut Deserializer<R>) -> Self {
782         EnumAssistant { deserializer }
783     }
784 }
785 
786 impl<'de, 'a, R: 'a> EnumAccess<'de> for EnumAssistant<'a, R>
787 where
788     R: BytesReader + Cacheable,
789 {
790     type Error = Error;
791     type Variant = Self;
792 
variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> where V: DeserializeSeed<'de>,793     fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
794     where
795         V: DeserializeSeed<'de>,
796     {
797         let value = seed.deserialize(&mut *self.deserializer)?;
798 
799         match eat_whitespace_until_not!(self.deserializer) {
800             Some(b':') => {
801                 self.deserializer.discard_char();
802                 Ok((value, self))
803             }
804             _ => unexpected_character!(self.deserializer),
805         }
806     }
807 }
808 
809 impl<'de, 'a, R: 'a> VariantAccess<'de> for EnumAssistant<'a, R>
810 where
811     R: BytesReader + Cacheable,
812 {
813     type Error = Error;
814 
unit_variant(self) -> Result<(), Error>815     fn unit_variant(self) -> Result<(), Error> {
816         serde::de::Deserialize::deserialize(self.deserializer)
817     }
818 
newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error> where T: DeserializeSeed<'de>,819     fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
820     where
821         T: DeserializeSeed<'de>,
822     {
823         seed.deserialize(self.deserializer)
824     }
825 
tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>,826     fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
827     where
828         V: Visitor<'de>,
829     {
830         serde::de::Deserializer::deserialize_seq(self.deserializer, visitor)
831     }
832 
struct_variant<V>( self, _fields: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>,833     fn struct_variant<V>(
834         self,
835         _fields: &'static [&'static str],
836         visitor: V,
837     ) -> Result<V::Value, Self::Error>
838     where
839         V: Visitor<'de>,
840     {
841         serde::de::Deserializer::deserialize_map(self.deserializer, visitor)
842     }
843 }
844 
845 #[cfg(test)]
846 mod ut_test_for_deserializer {
847     use crate::deserializer::{from_slice, from_str};
848     use serde::Deserialize;
849     use std::borrow::Cow;
850     use std::collections::HashMap;
851     use std::option::Option;
852 
853     /// UT test to deserialize simple types
854     ///
855     /// # Title
856     /// ut_deserialize_simple
857     ///
858     /// # Brief
859     /// 1.Uses deserializer::from_slice method to deserialize simple types.
860     /// 2.Checks if the test results are correct.
861     #[test]
ut_deserialize_simple()862     fn ut_deserialize_simple() {
863         let slice_null = b"null";
864         let expected: Option<i32> = None;
865         assert_eq!(expected, from_slice(slice_null).unwrap());
866 
867         let slice_bool = b"true";
868         let expected = true;
869         assert_eq!(expected, from_slice(slice_bool).unwrap());
870 
871         let slice_bool = b"false";
872         let expected = false;
873         assert_eq!(expected, from_slice(slice_bool).unwrap());
874 
875         let slice_num = b"123";
876         let expected: u8 = 123;
877         assert_eq!(expected, from_slice(slice_num).unwrap());
878 
879         let slice_num = b"123";
880         let expected: u16 = 123;
881         assert_eq!(expected, from_slice(slice_num).unwrap());
882 
883         let slice_num = b"123";
884         let expected: u32 = 123;
885         assert_eq!(expected, from_slice(slice_num).unwrap());
886 
887         let slice_num = b"-12";
888         let expected: i8 = -12;
889         assert_eq!(expected, from_slice(slice_num).unwrap());
890 
891         let slice_num = b"-12";
892         let expected: i16 = -12;
893         assert_eq!(expected, from_slice(slice_num).unwrap());
894 
895         let slice_num = b"-321";
896         let expected: i32 = -321;
897         assert_eq!(expected, from_slice(slice_num).unwrap());
898 
899         let slice_num = b"-321.123";
900         let expected: f32 = -321.123;
901         assert_eq!(expected, from_slice(slice_num).unwrap());
902 
903         let slice_char = b"\"c\"";
904         let expected = 'c';
905         assert_eq!(expected, from_slice::<char>(slice_char).unwrap());
906 
907         let slice_str = b"\"string\"";
908         let expected = String::from("string");
909         assert_eq!(expected, from_slice::<String>(slice_str).unwrap());
910 
911         let slice_option = b"true";
912         let expected = Some(true);
913         assert_eq!(expected, from_slice::<Option<bool>>(slice_option).unwrap());
914 
915         let slice_option = b"null";
916         let expected = None;
917         assert_eq!(expected, from_slice::<Option<bool>>(slice_option).unwrap());
918 
919         let slice_seq = b"[1, 2, 3]";
920         let expected: Vec<u8> = vec![1, 2, 3];
921         assert_eq!(expected, from_slice::<Vec<u8>>(slice_seq).unwrap());
922 
923         let slice_map = r#"{ "apple" : 3 }"#.as_bytes();
924         let mut expected = HashMap::new();
925         expected.insert("appple", 3);
926         assert_eq!(
927             expected,
928             crate::from_slice::<HashMap<&str, i32>>(slice_map).unwrap()
929         );
930     }
931 
932     #[test]
de_map()933     fn de_map() {
934         use std::collections::HashMap;
935         let slice_map = r#"{ "apple" : 3 }"#.as_bytes();
936         let mut expected = HashMap::new();
937         expected.insert(String::from("apple"), 3);
938         assert_eq!(
939             expected,
940             from_slice::<HashMap<String, i32>>(slice_map).unwrap()
941         );
942     }
943 
944     /// UT test to deserialize simple types with abnormal input of JSON.
945     ///
946     /// # Title
947     /// ut_deserialize_simple_error
948     ///
949     /// # Brief
950     /// 1.Uses deserializer::from_slice method to deserialize simple types with abnormal input of JSON.
951     /// 2.Checks if the test results are correct.
952     #[test]
ut_deserialize_simple_error()953     fn ut_deserialize_simple_error() {
954         // The following is the test for abnormal input of JSON.
955         let incorrect_input = b"nul";
956         let res = from_slice::<i32>(incorrect_input);
957         assert!(res.is_err());
958 
959         let incorrect_input = b"  ";
960         let res = from_slice::<bool>(incorrect_input);
961         assert!(res.is_err());
962 
963         let incorrect_input = b"tru";
964         let res = from_slice::<bool>(incorrect_input);
965         assert!(res.is_err());
966 
967         let incorrect_input = b"fals";
968         let res = from_slice::<bool>(incorrect_input);
969         assert!(res.is_err());
970 
971         let incorrect_input = b"ruet";
972         let res = from_slice::<bool>(incorrect_input);
973         assert!(res.is_err());
974 
975         let incorrect_input = b"  ";
976         let res = from_slice::<u64>(incorrect_input);
977         assert!(res.is_err());
978 
979         let incorrect_input = b"12x";
980         let res = from_slice::<u64>(incorrect_input);
981         assert!(res.is_err());
982 
983         let incorrect_input = b"-12x";
984         let res = from_slice::<i64>(incorrect_input);
985         assert!(res.is_err());
986 
987         let incorrect_input = b"-12.21x";
988         let res = from_slice::<f64>(incorrect_input);
989         assert!(res.is_err());
990 
991         let incorrect_input = b"  ";
992         let res = from_slice::<String>(incorrect_input);
993         assert!(res.is_err());
994 
995         let incorrect_input = b"string";
996         let res = from_slice::<String>(incorrect_input);
997         assert!(res.is_err());
998 
999         let incorrect_input = b"\"string";
1000         let res = from_slice::<String>(incorrect_input);
1001         assert!(res.is_err());
1002 
1003         let incorrect_input = b"  ";
1004         let res = from_slice::<Option<bool>>(incorrect_input);
1005         assert!(res.is_err());
1006 
1007         let incorrect_input = b"  ";
1008         let res = from_slice::<Vec<u8>>(incorrect_input);
1009         assert!(res.is_err());
1010 
1011         let incorrect_input = b"  [";
1012         let res = from_slice::<Vec<u8>>(incorrect_input);
1013         assert!(res.is_err());
1014 
1015         let incorrect_input = b"  [ 1";
1016         let res = from_slice::<Vec<u8>>(incorrect_input);
1017         assert!(res.is_err());
1018 
1019         let incorrect_input = r#"  "#.as_bytes();
1020         let res = from_slice::<HashMap<bool, i32>>(incorrect_input);
1021         assert!(res.is_err());
1022 
1023         let incorrect_input = r#"{ true x: 1 }"#.as_bytes();
1024         let res = from_slice::<HashMap<bool, i32>>(incorrect_input);
1025         assert!(res.is_err());
1026 
1027         let incorrect_input = r#"{ : 1 }"#.as_bytes();
1028         let res = from_slice::<HashMap<bool, i32>>(incorrect_input);
1029         assert!(res.is_err());
1030     }
1031 
1032     /// UT test to deserialize struct
1033     ///
1034     /// # Title
1035     /// ut_deserialize_struct
1036     ///
1037     /// # Brief
1038     /// 1.Uses deserializer::from_str method to deserialize struct.
1039     /// 2.Checks if the test results are correct.
1040     #[test]
ut_deserialize_struct()1041     fn ut_deserialize_struct() {
1042         #[derive(Deserialize, PartialEq, Debug)]
1043         struct TestUnit;
1044         let str = "null";
1045         let expected = TestUnit;
1046         assert_eq!(expected, from_str(str).unwrap());
1047 
1048         #[derive(Deserialize, PartialEq, Debug)]
1049         struct TestNewtype(u32);
1050         let str = "123";
1051         let expected = TestNewtype(123);
1052         assert_eq!(expected, from_str(str).unwrap());
1053 
1054         #[derive(Deserialize, PartialEq, Debug)]
1055         struct TestTuple(u32, u32, bool);
1056         let str = "[123,321,true]";
1057         let expected = TestTuple(123, 321, true);
1058         assert_eq!(expected, from_str(str).unwrap());
1059 
1060         #[derive(Deserialize, PartialEq, Debug)]
1061         struct Test {
1062             int: u32,
1063             seq: Vec<String>,
1064             tup: (i32, i32, i32),
1065         }
1066 
1067         let str = r#"{"int":1,"seq":["abcd","efgh"],"tup":[1,2,3]}"#;
1068         let expected = Test {
1069             int: 1,
1070             seq: vec![String::from("abcd"), String::from("efgh")],
1071             tup: (1, 2, 3),
1072         };
1073         assert_eq!(expected, from_str(str).unwrap());
1074 
1075         let str = r#"{
1076             "int" : 1 ,
1077             "seq" : ["abcd" , "efgh" ],
1078             "tup" : [1, 2 ,3 ]
1079         }"#;
1080         let expected = Test {
1081             int: 1,
1082             seq: vec![String::from("abcd"), String::from("efgh")],
1083             tup: (1, 2, 3),
1084         };
1085         assert_eq!(expected, from_str(str).unwrap());
1086 
1087         // The following is the test for abnormal input of JSON.
1088         // Missing '}' at the end.
1089         let str_abnormal = r#"{"int":1,"seq":["abcd","efgh"],"tup":[1,2,3]"#;
1090         let res = from_str::<Test>(str_abnormal);
1091         assert!(res.is_err());
1092 
1093         // Missing ','.
1094         let str_abnormal = r#"{"int":1 "seq":["abcd","efgh"],"tup":[1,2,3]"#;
1095         let res = from_str::<Test>(str_abnormal);
1096         assert!(res.is_err());
1097 
1098         // Trailing ','.
1099         let str_abnormal = r#"{"int":1, "seq":["abcd","efgh",],"tup":[1,2,3]"#;
1100         let res = from_str::<Test>(str_abnormal);
1101         assert!(res.is_err());
1102 
1103         // Missing ':'.
1104         let str_abnormal = r#"{"int":1, "seq":["abcd","efgh"],"tup" [1,2,3]"#;
1105         let res = from_str::<Test>(str_abnormal);
1106         assert!(res.is_err());
1107 
1108         // Incorrect field name.
1109         let str_abnormal = r#"{"it":1, "sq" : ["abcd","efgh"],"tp": [1,2,3]"#;
1110         let res = from_str::<Test>(str_abnormal);
1111         assert!(res.is_err());
1112     }
1113 
1114     /// UT test to deserialize enum
1115     ///
1116     /// # Title
1117     /// ut_deserialize_enum
1118     ///
1119     /// # Brief
1120     /// 1.Uses deserializer::from_slice method to deserialize enum.
1121     /// 2.Checks if the test results are correct.
1122     #[test]
ut_deserialize_enum()1123     fn ut_deserialize_enum() {
1124         #[derive(Deserialize, PartialEq, Debug)]
1125         enum E<'a> {
1126             Unit,
1127             Newtype(u32),
1128             Tuple(u32, u32),
1129             Struct { a: u32 },
1130             Reference(Cow<'a, str>),
1131         }
1132 
1133         let u = r#""Unit""#.as_bytes();
1134         let expected = E::Unit;
1135         assert_eq!(expected, from_slice(u).unwrap());
1136 
1137         let n = r#"{"Newtype":1}"#.as_bytes();
1138         let expected = E::Newtype(1);
1139         assert_eq!(expected, from_slice(n).unwrap());
1140 
1141         let t = r#"{"Tuple":[1,2]}"#.as_bytes();
1142         let expected = E::Tuple(1, 2);
1143         assert_eq!(expected, from_slice(t).unwrap());
1144 
1145         let s = r#"{"Struct":{"a":1}}"#.as_bytes();
1146         let expected = E::Struct { a: 1 };
1147         assert_eq!(expected, from_slice(s).unwrap());
1148 
1149         let s = r#"{"Reference":"reference"}"#.as_bytes();
1150         let expected = E::Reference(Cow::from("reference"));
1151         assert_eq!(expected, from_slice(s).unwrap());
1152 
1153         // The following is the test for abnormal input of JSON.
1154         let slice_abnormal = r#"   "#.as_bytes();
1155         let res = from_slice::<E>(slice_abnormal);
1156         assert!(res.is_err());
1157 
1158         let slice_abnormal = r#"x"#.as_bytes();
1159         let res = from_slice::<E>(slice_abnormal);
1160         assert!(res.is_err());
1161 
1162         let slice_abnormal = r#""Unit"#.as_bytes();
1163         let res = from_slice::<E>(slice_abnormal);
1164         assert!(res.is_err());
1165 
1166         let slice_abnormal = r#"{"Newtype" 1"#.as_bytes();
1167         let res = from_slice::<E>(slice_abnormal);
1168         assert!(res.is_err());
1169 
1170         let slice_abnormal = r#"{"Newtype":1"#.as_bytes();
1171         let res = from_slice::<E>(slice_abnormal);
1172         assert!(res.is_err());
1173 
1174         let slice_abnormal = r#"{"Tuple":[1,2}"#.as_bytes();
1175         let res = from_slice::<E>(slice_abnormal);
1176         assert!(res.is_err());
1177     }
1178 }
1179