1 use crate::error::{self, Error, ErrorImpl};
2 use crate::libyaml::error::Mark;
3 use crate::libyaml::parser::{MappingStart, Scalar, ScalarStyle, SequenceStart};
4 use crate::libyaml::tag::Tag;
5 use crate::loader::{Document, Loader};
6 use crate::path::Path;
7 use serde::de::value::StrDeserializer;
8 use serde::de::{
9     self, Deserialize, DeserializeOwned, DeserializeSeed, Expected, IgnoredAny, Unexpected, Visitor,
10 };
11 use std::fmt;
12 use std::io;
13 use std::mem;
14 use std::num::ParseIntError;
15 use std::str;
16 use std::sync::Arc;
17 
18 type Result<T, E = Error> = std::result::Result<T, E>;
19 
20 /// A structure that deserializes YAML into Rust values.
21 ///
22 /// # Examples
23 ///
24 /// Deserializing a single document:
25 ///
26 /// ```
27 /// use anyhow::Result;
28 /// use serde::Deserialize;
29 /// use serde_yaml::Value;
30 ///
31 /// fn main() -> Result<()> {
32 ///     let input = "k: 107\n";
33 ///     let de = serde_yaml::Deserializer::from_str(input);
34 ///     let value = Value::deserialize(de)?;
35 ///     println!("{:?}", value);
36 ///     Ok(())
37 /// }
38 /// ```
39 ///
40 /// Deserializing multi-doc YAML:
41 ///
42 /// ```
43 /// use anyhow::Result;
44 /// use serde::Deserialize;
45 /// use serde_yaml::Value;
46 ///
47 /// fn main() -> Result<()> {
48 ///     let input = "---\nk: 107\n...\n---\nj: 106\n";
49 ///
50 ///     for document in serde_yaml::Deserializer::from_str(input) {
51 ///         let value = Value::deserialize(document)?;
52 ///         println!("{:?}", value);
53 ///     }
54 ///
55 ///     Ok(())
56 /// }
57 /// ```
58 pub struct Deserializer<'de> {
59     progress: Progress<'de>,
60 }
61 
62 pub(crate) enum Progress<'de> {
63     Str(&'de str),
64     Slice(&'de [u8]),
65     Read(Box<dyn io::Read + 'de>),
66     Iterable(Loader<'de>),
67     Document(Document<'de>),
68     Fail(Arc<ErrorImpl>),
69 }
70 
71 impl<'de> Deserializer<'de> {
72     /// Creates a YAML deserializer from a `&str`.
from_str(s: &'de str) -> Self73     pub fn from_str(s: &'de str) -> Self {
74         let progress = Progress::Str(s);
75         Deserializer { progress }
76     }
77 
78     /// Creates a YAML deserializer from a `&[u8]`.
from_slice(v: &'de [u8]) -> Self79     pub fn from_slice(v: &'de [u8]) -> Self {
80         let progress = Progress::Slice(v);
81         Deserializer { progress }
82     }
83 
84     /// Creates a YAML deserializer from an `io::Read`.
85     ///
86     /// Reader-based deserializers do not support deserializing borrowed types
87     /// like `&str`, since the `std::io::Read` trait has no non-copying methods
88     /// -- everything it does involves copying bytes out of the data source.
from_reader<R>(rdr: R) -> Self where R: io::Read + 'de,89     pub fn from_reader<R>(rdr: R) -> Self
90     where
91         R: io::Read + 'de,
92     {
93         let progress = Progress::Read(Box::new(rdr));
94         Deserializer { progress }
95     }
96 
de<T>( self, f: impl for<'document> FnOnce(&mut DeserializerFromEvents<'de, 'document>) -> Result<T>, ) -> Result<T>97     fn de<T>(
98         self,
99         f: impl for<'document> FnOnce(&mut DeserializerFromEvents<'de, 'document>) -> Result<T>,
100     ) -> Result<T> {
101         let mut pos = 0;
102         let mut jumpcount = 0;
103 
104         match self.progress {
105             Progress::Iterable(_) => return Err(error::new(ErrorImpl::MoreThanOneDocument)),
106             Progress::Document(document) => {
107                 let t = f(&mut DeserializerFromEvents {
108                     document: &document,
109                     pos: &mut pos,
110                     jumpcount: &mut jumpcount,
111                     path: Path::Root,
112                     remaining_depth: 128,
113                     current_enum: None,
114                 })?;
115                 if let Some(parse_error) = document.error {
116                     return Err(error::shared(parse_error));
117                 }
118                 return Ok(t);
119             }
120             _ => {}
121         }
122 
123         let mut loader = Loader::new(self.progress)?;
124         let document = match loader.next_document() {
125             Some(document) => document,
126             None => return Err(error::new(ErrorImpl::EndOfStream)),
127         };
128         let t = f(&mut DeserializerFromEvents {
129             document: &document,
130             pos: &mut pos,
131             jumpcount: &mut jumpcount,
132             path: Path::Root,
133             remaining_depth: 128,
134             current_enum: None,
135         })?;
136         if let Some(parse_error) = document.error {
137             return Err(error::shared(parse_error));
138         }
139         if loader.next_document().is_none() {
140             Ok(t)
141         } else {
142             Err(error::new(ErrorImpl::MoreThanOneDocument))
143         }
144     }
145 }
146 
147 impl<'de> Iterator for Deserializer<'de> {
148     type Item = Self;
149 
next(&mut self) -> Option<Self>150     fn next(&mut self) -> Option<Self> {
151         match &mut self.progress {
152             Progress::Iterable(loader) => {
153                 let document = loader.next_document()?;
154                 return Some(Deserializer {
155                     progress: Progress::Document(document),
156                 });
157             }
158             Progress::Document(_) => return None,
159             Progress::Fail(err) => {
160                 return Some(Deserializer {
161                     progress: Progress::Fail(Arc::clone(err)),
162                 });
163             }
164             _ => {}
165         }
166 
167         let dummy = Progress::Str("");
168         let input = mem::replace(&mut self.progress, dummy);
169         match Loader::new(input) {
170             Ok(loader) => {
171                 self.progress = Progress::Iterable(loader);
172                 self.next()
173             }
174             Err(err) => {
175                 let fail = err.shared();
176                 self.progress = Progress::Fail(Arc::clone(&fail));
177                 Some(Deserializer {
178                     progress: Progress::Fail(fail),
179                 })
180             }
181         }
182     }
183 }
184 
185 impl<'de> de::Deserializer<'de> for Deserializer<'de> {
186     type Error = Error;
187 
deserialize_any<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,188     fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
189     where
190         V: Visitor<'de>,
191     {
192         self.de(|state| state.deserialize_any(visitor))
193     }
194 
deserialize_bool<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,195     fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
196     where
197         V: Visitor<'de>,
198     {
199         self.de(|state| state.deserialize_bool(visitor))
200     }
201 
deserialize_i8<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,202     fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
203     where
204         V: Visitor<'de>,
205     {
206         self.de(|state| state.deserialize_i8(visitor))
207     }
208 
deserialize_i16<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,209     fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value>
210     where
211         V: Visitor<'de>,
212     {
213         self.de(|state| state.deserialize_i16(visitor))
214     }
215 
deserialize_i32<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,216     fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value>
217     where
218         V: Visitor<'de>,
219     {
220         self.de(|state| state.deserialize_i32(visitor))
221     }
222 
deserialize_i64<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,223     fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value>
224     where
225         V: Visitor<'de>,
226     {
227         self.de(|state| state.deserialize_i64(visitor))
228     }
229 
deserialize_i128<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,230     fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value>
231     where
232         V: Visitor<'de>,
233     {
234         self.de(|state| state.deserialize_i128(visitor))
235     }
236 
deserialize_u8<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,237     fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
238     where
239         V: Visitor<'de>,
240     {
241         self.de(|state| state.deserialize_u8(visitor))
242     }
243 
deserialize_u16<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,244     fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value>
245     where
246         V: Visitor<'de>,
247     {
248         self.de(|state| state.deserialize_u16(visitor))
249     }
250 
deserialize_u32<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,251     fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value>
252     where
253         V: Visitor<'de>,
254     {
255         self.de(|state| state.deserialize_u32(visitor))
256     }
257 
deserialize_u64<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,258     fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value>
259     where
260         V: Visitor<'de>,
261     {
262         self.de(|state| state.deserialize_u64(visitor))
263     }
264 
deserialize_u128<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,265     fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value>
266     where
267         V: Visitor<'de>,
268     {
269         self.de(|state| state.deserialize_u128(visitor))
270     }
271 
deserialize_f32<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,272     fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value>
273     where
274         V: Visitor<'de>,
275     {
276         self.de(|state| state.deserialize_f32(visitor))
277     }
278 
deserialize_f64<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,279     fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value>
280     where
281         V: Visitor<'de>,
282     {
283         self.de(|state| state.deserialize_f64(visitor))
284     }
285 
deserialize_char<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,286     fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
287     where
288         V: Visitor<'de>,
289     {
290         self.de(|state| state.deserialize_char(visitor))
291     }
292 
deserialize_str<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,293     fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
294     where
295         V: Visitor<'de>,
296     {
297         self.de(|state| state.deserialize_str(visitor))
298     }
299 
deserialize_string<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,300     fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
301     where
302         V: Visitor<'de>,
303     {
304         self.de(|state| state.deserialize_string(visitor))
305     }
306 
deserialize_bytes<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,307     fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
308     where
309         V: Visitor<'de>,
310     {
311         self.de(|state| state.deserialize_bytes(visitor))
312     }
313 
deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,314     fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
315     where
316         V: Visitor<'de>,
317     {
318         self.de(|state| state.deserialize_byte_buf(visitor))
319     }
320 
deserialize_option<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,321     fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
322     where
323         V: Visitor<'de>,
324     {
325         self.de(|state| state.deserialize_option(visitor))
326     }
327 
deserialize_unit<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,328     fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
329     where
330         V: Visitor<'de>,
331     {
332         self.de(|state| state.deserialize_unit(visitor))
333     }
334 
deserialize_unit_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value> where V: Visitor<'de>,335     fn deserialize_unit_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value>
336     where
337         V: Visitor<'de>,
338     {
339         self.de(|state| state.deserialize_unit_struct(name, visitor))
340     }
341 
deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value> where V: Visitor<'de>,342     fn deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value>
343     where
344         V: Visitor<'de>,
345     {
346         self.de(|state| state.deserialize_newtype_struct(name, visitor))
347     }
348 
deserialize_seq<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,349     fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
350     where
351         V: Visitor<'de>,
352     {
353         self.de(|state| state.deserialize_seq(visitor))
354     }
355 
deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value> where V: Visitor<'de>,356     fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value>
357     where
358         V: Visitor<'de>,
359     {
360         self.de(|state| state.deserialize_tuple(len, visitor))
361     }
362 
deserialize_tuple_struct<V>( self, name: &'static str, len: usize, visitor: V, ) -> Result<V::Value> where V: Visitor<'de>,363     fn deserialize_tuple_struct<V>(
364         self,
365         name: &'static str,
366         len: usize,
367         visitor: V,
368     ) -> Result<V::Value>
369     where
370         V: Visitor<'de>,
371     {
372         self.de(|state| state.deserialize_tuple_struct(name, len, visitor))
373     }
374 
deserialize_map<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,375     fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
376     where
377         V: Visitor<'de>,
378     {
379         self.de(|state| state.deserialize_map(visitor))
380     }
381 
deserialize_struct<V>( self, name: &'static str, fields: &'static [&'static str], visitor: V, ) -> Result<V::Value> where V: Visitor<'de>,382     fn deserialize_struct<V>(
383         self,
384         name: &'static str,
385         fields: &'static [&'static str],
386         visitor: V,
387     ) -> Result<V::Value>
388     where
389         V: Visitor<'de>,
390     {
391         self.de(|state| state.deserialize_struct(name, fields, visitor))
392     }
393 
deserialize_enum<V>( self, name: &'static str, variants: &'static [&'static str], visitor: V, ) -> Result<V::Value> where V: Visitor<'de>,394     fn deserialize_enum<V>(
395         self,
396         name: &'static str,
397         variants: &'static [&'static str],
398         visitor: V,
399     ) -> Result<V::Value>
400     where
401         V: Visitor<'de>,
402     {
403         self.de(|state| state.deserialize_enum(name, variants, visitor))
404     }
405 
deserialize_identifier<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,406     fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value>
407     where
408         V: Visitor<'de>,
409     {
410         self.de(|state| state.deserialize_identifier(visitor))
411     }
412 
deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,413     fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>
414     where
415         V: Visitor<'de>,
416     {
417         self.de(|state| state.deserialize_ignored_any(visitor))
418     }
419 }
420 
421 #[derive(Debug)]
422 pub(crate) enum Event<'de> {
423     Alias(usize),
424     Scalar(Scalar<'de>),
425     SequenceStart(SequenceStart),
426     SequenceEnd,
427     MappingStart(MappingStart),
428     MappingEnd,
429     Void,
430 }
431 
432 struct DeserializerFromEvents<'de, 'document> {
433     document: &'document Document<'de>,
434     pos: &'document mut usize,
435     jumpcount: &'document mut usize,
436     path: Path<'document>,
437     remaining_depth: u8,
438     current_enum: Option<CurrentEnum<'document>>,
439 }
440 
441 #[derive(Copy, Clone)]
442 struct CurrentEnum<'document> {
443     name: Option<&'static str>,
444     tag: &'document str,
445 }
446 
447 impl<'de, 'document> DeserializerFromEvents<'de, 'document> {
peek_event(&self) -> Result<&'document Event<'de>>448     fn peek_event(&self) -> Result<&'document Event<'de>> {
449         self.peek_event_mark().map(|(event, _mark)| event)
450     }
451 
peek_event_mark(&self) -> Result<(&'document Event<'de>, Mark)>452     fn peek_event_mark(&self) -> Result<(&'document Event<'de>, Mark)> {
453         match self.document.events.get(*self.pos) {
454             Some((event, mark)) => Ok((event, *mark)),
455             None => Err(match &self.document.error {
456                 Some(parse_error) => error::shared(Arc::clone(parse_error)),
457                 None => error::new(ErrorImpl::EndOfStream),
458             }),
459         }
460     }
461 
next_event(&mut self) -> Result<&'document Event<'de>>462     fn next_event(&mut self) -> Result<&'document Event<'de>> {
463         self.next_event_mark().map(|(event, _mark)| event)
464     }
465 
next_event_mark(&mut self) -> Result<(&'document Event<'de>, Mark)>466     fn next_event_mark(&mut self) -> Result<(&'document Event<'de>, Mark)> {
467         self.peek_event_mark().map(|(event, mark)| {
468             *self.pos += 1;
469             self.current_enum = None;
470             (event, mark)
471         })
472     }
473 
jump<'anchor>( &'anchor mut self, pos: &'anchor mut usize, ) -> Result<DeserializerFromEvents<'de, 'anchor>>474     fn jump<'anchor>(
475         &'anchor mut self,
476         pos: &'anchor mut usize,
477     ) -> Result<DeserializerFromEvents<'de, 'anchor>> {
478         *self.jumpcount += 1;
479         if *self.jumpcount > self.document.events.len() * 100 {
480             return Err(error::new(ErrorImpl::RepetitionLimitExceeded));
481         }
482         match self.document.aliases.get(pos) {
483             Some(found) => {
484                 *pos = *found;
485                 Ok(DeserializerFromEvents {
486                     document: self.document,
487                     pos,
488                     jumpcount: self.jumpcount,
489                     path: Path::Alias { parent: &self.path },
490                     remaining_depth: self.remaining_depth,
491                     current_enum: None,
492                 })
493             }
494             None => panic!("unresolved alias: {}", *pos),
495         }
496     }
497 
ignore_any(&mut self) -> Result<()>498     fn ignore_any(&mut self) -> Result<()> {
499         enum Nest {
500             Sequence,
501             Mapping,
502         }
503 
504         let mut stack = Vec::new();
505 
506         loop {
507             match self.next_event()? {
508                 Event::Alias(_) | Event::Scalar(_) | Event::Void => {}
509                 Event::SequenceStart(_) => {
510                     stack.push(Nest::Sequence);
511                 }
512                 Event::MappingStart(_) => {
513                     stack.push(Nest::Mapping);
514                 }
515                 Event::SequenceEnd => match stack.pop() {
516                     Some(Nest::Sequence) => {}
517                     None | Some(Nest::Mapping) => {
518                         panic!("unexpected end of sequence");
519                     }
520                 },
521                 Event::MappingEnd => match stack.pop() {
522                     Some(Nest::Mapping) => {}
523                     None | Some(Nest::Sequence) => {
524                         panic!("unexpected end of mapping");
525                     }
526                 },
527             }
528             if stack.is_empty() {
529                 return Ok(());
530             }
531         }
532     }
533 
visit_sequence<V>(&mut self, visitor: V, mark: Mark) -> Result<V::Value> where V: Visitor<'de>,534     fn visit_sequence<V>(&mut self, visitor: V, mark: Mark) -> Result<V::Value>
535     where
536         V: Visitor<'de>,
537     {
538         let (value, len) = self.recursion_check(mark, |de| {
539             let mut seq = SeqAccess {
540                 empty: false,
541                 de,
542                 len: 0,
543             };
544             let value = visitor.visit_seq(&mut seq)?;
545             Ok((value, seq.len))
546         })?;
547         self.end_sequence(len)?;
548         Ok(value)
549     }
550 
visit_mapping<V>(&mut self, visitor: V, mark: Mark) -> Result<V::Value> where V: Visitor<'de>,551     fn visit_mapping<V>(&mut self, visitor: V, mark: Mark) -> Result<V::Value>
552     where
553         V: Visitor<'de>,
554     {
555         let (value, len) = self.recursion_check(mark, |de| {
556             let mut map = MapAccess {
557                 empty: false,
558                 de,
559                 len: 0,
560                 key: None,
561             };
562             let value = visitor.visit_map(&mut map)?;
563             Ok((value, map.len))
564         })?;
565         self.end_mapping(len)?;
566         Ok(value)
567     }
568 
end_sequence(&mut self, len: usize) -> Result<()>569     fn end_sequence(&mut self, len: usize) -> Result<()> {
570         let total = {
571             let mut seq = SeqAccess {
572                 empty: false,
573                 de: self,
574                 len,
575             };
576             while de::SeqAccess::next_element::<IgnoredAny>(&mut seq)?.is_some() {}
577             seq.len
578         };
579         match self.next_event()? {
580             Event::SequenceEnd | Event::Void => {}
581             _ => panic!("expected a SequenceEnd event"),
582         }
583         if total == len {
584             Ok(())
585         } else {
586             struct ExpectedSeq(usize);
587             impl Expected for ExpectedSeq {
588                 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
589                     if self.0 == 1 {
590                         write!(formatter, "sequence of 1 element")
591                     } else {
592                         write!(formatter, "sequence of {} elements", self.0)
593                     }
594                 }
595             }
596             Err(de::Error::invalid_length(total, &ExpectedSeq(len)))
597         }
598     }
599 
end_mapping(&mut self, len: usize) -> Result<()>600     fn end_mapping(&mut self, len: usize) -> Result<()> {
601         let total = {
602             let mut map = MapAccess {
603                 empty: false,
604                 de: self,
605                 len,
606                 key: None,
607             };
608             while de::MapAccess::next_entry::<IgnoredAny, IgnoredAny>(&mut map)?.is_some() {}
609             map.len
610         };
611         match self.next_event()? {
612             Event::MappingEnd | Event::Void => {}
613             _ => panic!("expected a MappingEnd event"),
614         }
615         if total == len {
616             Ok(())
617         } else {
618             struct ExpectedMap(usize);
619             impl Expected for ExpectedMap {
620                 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
621                     if self.0 == 1 {
622                         write!(formatter, "map containing 1 entry")
623                     } else {
624                         write!(formatter, "map containing {} entries", self.0)
625                     }
626                 }
627             }
628             Err(de::Error::invalid_length(total, &ExpectedMap(len)))
629         }
630     }
631 
recursion_check<F: FnOnce(&mut Self) -> Result<T>, T>( &mut self, mark: Mark, f: F, ) -> Result<T>632     fn recursion_check<F: FnOnce(&mut Self) -> Result<T>, T>(
633         &mut self,
634         mark: Mark,
635         f: F,
636     ) -> Result<T> {
637         let previous_depth = self.remaining_depth;
638         self.remaining_depth = match previous_depth.checked_sub(1) {
639             Some(depth) => depth,
640             None => return Err(error::new(ErrorImpl::RecursionLimitExceeded(mark))),
641         };
642         let result = f(self);
643         self.remaining_depth = previous_depth;
644         result
645     }
646 }
647 
648 struct SeqAccess<'de, 'document, 'seq> {
649     empty: bool,
650     de: &'seq mut DeserializerFromEvents<'de, 'document>,
651     len: usize,
652 }
653 
654 impl<'de, 'document, 'seq> de::SeqAccess<'de> for SeqAccess<'de, 'document, 'seq> {
655     type Error = Error;
656 
next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> where T: DeserializeSeed<'de>,657     fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
658     where
659         T: DeserializeSeed<'de>,
660     {
661         if self.empty {
662             return Ok(None);
663         }
664         match self.de.peek_event()? {
665             Event::SequenceEnd | Event::Void => Ok(None),
666             _ => {
667                 let mut element_de = DeserializerFromEvents {
668                     document: self.de.document,
669                     pos: self.de.pos,
670                     jumpcount: self.de.jumpcount,
671                     path: Path::Seq {
672                         parent: &self.de.path,
673                         index: self.len,
674                     },
675                     remaining_depth: self.de.remaining_depth,
676                     current_enum: None,
677                 };
678                 self.len += 1;
679                 seed.deserialize(&mut element_de).map(Some)
680             }
681         }
682     }
683 }
684 
685 struct MapAccess<'de, 'document, 'map> {
686     empty: bool,
687     de: &'map mut DeserializerFromEvents<'de, 'document>,
688     len: usize,
689     key: Option<&'document [u8]>,
690 }
691 
692 impl<'de, 'document, 'map> de::MapAccess<'de> for MapAccess<'de, 'document, 'map> {
693     type Error = Error;
694 
next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> where K: DeserializeSeed<'de>,695     fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
696     where
697         K: DeserializeSeed<'de>,
698     {
699         if self.empty {
700             return Ok(None);
701         }
702         match self.de.peek_event()? {
703             Event::MappingEnd | Event::Void => Ok(None),
704             Event::Scalar(scalar) => {
705                 self.len += 1;
706                 self.key = Some(&scalar.value);
707                 seed.deserialize(&mut *self.de).map(Some)
708             }
709             _ => {
710                 self.len += 1;
711                 self.key = None;
712                 seed.deserialize(&mut *self.de).map(Some)
713             }
714         }
715     }
716 
next_value_seed<V>(&mut self, seed: V) -> Result<V::Value> where V: DeserializeSeed<'de>,717     fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
718     where
719         V: DeserializeSeed<'de>,
720     {
721         let mut value_de = DeserializerFromEvents {
722             document: self.de.document,
723             pos: self.de.pos,
724             jumpcount: self.de.jumpcount,
725             path: if let Some(key) = self.key.and_then(|key| str::from_utf8(key).ok()) {
726                 Path::Map {
727                     parent: &self.de.path,
728                     key,
729                 }
730             } else {
731                 Path::Unknown {
732                     parent: &self.de.path,
733                 }
734             },
735             remaining_depth: self.de.remaining_depth,
736             current_enum: None,
737         };
738         seed.deserialize(&mut value_de)
739     }
740 }
741 
742 struct EnumAccess<'de, 'document, 'variant> {
743     de: &'variant mut DeserializerFromEvents<'de, 'document>,
744     name: Option<&'static str>,
745     tag: &'document str,
746 }
747 
748 impl<'de, 'document, 'variant> de::EnumAccess<'de> for EnumAccess<'de, 'document, 'variant> {
749     type Error = Error;
750     type Variant = DeserializerFromEvents<'de, 'variant>;
751 
variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)> where V: DeserializeSeed<'de>,752     fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
753     where
754         V: DeserializeSeed<'de>,
755     {
756         let str_de = StrDeserializer::<Error>::new(self.tag);
757         let variant = seed.deserialize(str_de)?;
758         let visitor = DeserializerFromEvents {
759             document: self.de.document,
760             pos: self.de.pos,
761             jumpcount: self.de.jumpcount,
762             path: self.de.path,
763             remaining_depth: self.de.remaining_depth,
764             current_enum: Some(CurrentEnum {
765                 name: self.name,
766                 tag: self.tag,
767             }),
768         };
769         Ok((variant, visitor))
770     }
771 }
772 
773 impl<'de, 'document> de::VariantAccess<'de> for DeserializerFromEvents<'de, 'document> {
774     type Error = Error;
775 
unit_variant(mut self) -> Result<()>776     fn unit_variant(mut self) -> Result<()> {
777         Deserialize::deserialize(&mut self)
778     }
779 
newtype_variant_seed<T>(mut self, seed: T) -> Result<T::Value> where T: DeserializeSeed<'de>,780     fn newtype_variant_seed<T>(mut self, seed: T) -> Result<T::Value>
781     where
782         T: DeserializeSeed<'de>,
783     {
784         seed.deserialize(&mut self)
785     }
786 
tuple_variant<V>(mut self, _len: usize, visitor: V) -> Result<V::Value> where V: Visitor<'de>,787     fn tuple_variant<V>(mut self, _len: usize, visitor: V) -> Result<V::Value>
788     where
789         V: Visitor<'de>,
790     {
791         de::Deserializer::deserialize_seq(&mut self, visitor)
792     }
793 
struct_variant<V>(mut self, fields: &'static [&'static str], visitor: V) -> Result<V::Value> where V: Visitor<'de>,794     fn struct_variant<V>(mut self, fields: &'static [&'static str], visitor: V) -> Result<V::Value>
795     where
796         V: Visitor<'de>,
797     {
798         de::Deserializer::deserialize_struct(&mut self, "", fields, visitor)
799     }
800 }
801 
802 struct UnitVariantAccess<'de, 'document, 'variant> {
803     de: &'variant mut DeserializerFromEvents<'de, 'document>,
804 }
805 
806 impl<'de, 'document, 'variant> de::EnumAccess<'de> for UnitVariantAccess<'de, 'document, 'variant> {
807     type Error = Error;
808     type Variant = Self;
809 
variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)> where V: DeserializeSeed<'de>,810     fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
811     where
812         V: DeserializeSeed<'de>,
813     {
814         Ok((seed.deserialize(&mut *self.de)?, self))
815     }
816 }
817 
818 impl<'de, 'document, 'variant> de::VariantAccess<'de>
819     for UnitVariantAccess<'de, 'document, 'variant>
820 {
821     type Error = Error;
822 
unit_variant(self) -> Result<()>823     fn unit_variant(self) -> Result<()> {
824         Ok(())
825     }
826 
newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value> where T: DeserializeSeed<'de>,827     fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value>
828     where
829         T: DeserializeSeed<'de>,
830     {
831         Err(de::Error::invalid_type(
832             Unexpected::UnitVariant,
833             &"newtype variant",
834         ))
835     }
836 
tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value> where V: Visitor<'de>,837     fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value>
838     where
839         V: Visitor<'de>,
840     {
841         Err(de::Error::invalid_type(
842             Unexpected::UnitVariant,
843             &"tuple variant",
844         ))
845     }
846 
struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value> where V: Visitor<'de>,847     fn struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value>
848     where
849         V: Visitor<'de>,
850     {
851         Err(de::Error::invalid_type(
852             Unexpected::UnitVariant,
853             &"struct variant",
854         ))
855     }
856 }
857 
visit_scalar<'de, V>(visitor: V, scalar: &Scalar<'de>, tagged_already: bool) -> Result<V::Value> where V: Visitor<'de>,858 fn visit_scalar<'de, V>(visitor: V, scalar: &Scalar<'de>, tagged_already: bool) -> Result<V::Value>
859 where
860     V: Visitor<'de>,
861 {
862     let v = match str::from_utf8(&scalar.value) {
863         Ok(v) => v,
864         Err(_) => {
865             return Err(de::Error::invalid_type(
866                 Unexpected::Bytes(&scalar.value),
867                 &visitor,
868             ))
869         }
870     };
871     if let (Some(tag), false) = (&scalar.tag, tagged_already) {
872         if tag == Tag::BOOL {
873             return match parse_bool(v) {
874                 Some(v) => visitor.visit_bool(v),
875                 None => Err(de::Error::invalid_value(Unexpected::Str(v), &"a boolean")),
876             };
877         } else if tag == Tag::INT {
878             return match visit_int(visitor, v) {
879                 Ok(result) => result,
880                 Err(_) => Err(de::Error::invalid_value(Unexpected::Str(v), &"an integer")),
881             };
882         } else if tag == Tag::FLOAT {
883             return match parse_f64(v) {
884                 Some(v) => visitor.visit_f64(v),
885                 None => Err(de::Error::invalid_value(Unexpected::Str(v), &"a float")),
886             };
887         } else if tag == Tag::NULL {
888             return match parse_null(v.as_bytes()) {
889                 Some(()) => visitor.visit_unit(),
890                 None => Err(de::Error::invalid_value(Unexpected::Str(v), &"null")),
891             };
892         } else if tag.starts_with("!") && scalar.style == ScalarStyle::Plain {
893             return visit_untagged_scalar(visitor, v, scalar.repr, scalar.style);
894         }
895     } else if scalar.style == ScalarStyle::Plain {
896         return visit_untagged_scalar(visitor, v, scalar.repr, scalar.style);
897     }
898     if let Some(borrowed) = parse_borrowed_str(v, scalar.repr, scalar.style) {
899         visitor.visit_borrowed_str(borrowed)
900     } else {
901         visitor.visit_str(v)
902     }
903 }
904 
parse_borrowed_str<'de>( utf8_value: &str, repr: Option<&'de [u8]>, style: ScalarStyle, ) -> Option<&'de str>905 fn parse_borrowed_str<'de>(
906     utf8_value: &str,
907     repr: Option<&'de [u8]>,
908     style: ScalarStyle,
909 ) -> Option<&'de str> {
910     let borrowed_repr = repr?;
911     let expected_offset = match style {
912         ScalarStyle::Plain => 0,
913         ScalarStyle::SingleQuoted | ScalarStyle::DoubleQuoted => 1,
914         ScalarStyle::Literal | ScalarStyle::Folded => return None,
915     };
916     let expected_end = borrowed_repr.len().checked_sub(expected_offset)?;
917     let expected_start = expected_end.checked_sub(utf8_value.len())?;
918     let borrowed_bytes = borrowed_repr.get(expected_start..expected_end)?;
919     if borrowed_bytes == utf8_value.as_bytes() {
920         return Some(unsafe { str::from_utf8_unchecked(borrowed_bytes) });
921     }
922     None
923 }
924 
parse_null(scalar: &[u8]) -> Option<()>925 fn parse_null(scalar: &[u8]) -> Option<()> {
926     match scalar {
927         b"null" | b"Null" | b"NULL" | b"~" => Some(()),
928         _ => None,
929     }
930 }
931 
parse_bool(scalar: &str) -> Option<bool>932 fn parse_bool(scalar: &str) -> Option<bool> {
933     match scalar {
934         "true" | "True" | "TRUE" => Some(true),
935         "false" | "False" | "FALSE" => Some(false),
936         _ => None,
937     }
938 }
939 
parse_unsigned_int<T>( scalar: &str, from_str_radix: fn(&str, radix: u32) -> Result<T, ParseIntError>, ) -> Option<T>940 fn parse_unsigned_int<T>(
941     scalar: &str,
942     from_str_radix: fn(&str, radix: u32) -> Result<T, ParseIntError>,
943 ) -> Option<T> {
944     let unpositive = scalar.strip_prefix('+').unwrap_or(scalar);
945     if let Some(rest) = unpositive.strip_prefix("0x") {
946         if rest.starts_with(['+', '-']) {
947             return None;
948         }
949         if let Ok(int) = from_str_radix(rest, 16) {
950             return Some(int);
951         }
952     }
953     if let Some(rest) = unpositive.strip_prefix("0o") {
954         if rest.starts_with(['+', '-']) {
955             return None;
956         }
957         if let Ok(int) = from_str_radix(rest, 8) {
958             return Some(int);
959         }
960     }
961     if let Some(rest) = unpositive.strip_prefix("0b") {
962         if rest.starts_with(['+', '-']) {
963             return None;
964         }
965         if let Ok(int) = from_str_radix(rest, 2) {
966             return Some(int);
967         }
968     }
969     if unpositive.starts_with(['+', '-']) {
970         return None;
971     }
972     if digits_but_not_number(scalar) {
973         return None;
974     }
975     from_str_radix(unpositive, 10).ok()
976 }
977 
parse_signed_int<T>( scalar: &str, from_str_radix: fn(&str, radix: u32) -> Result<T, ParseIntError>, ) -> Option<T>978 fn parse_signed_int<T>(
979     scalar: &str,
980     from_str_radix: fn(&str, radix: u32) -> Result<T, ParseIntError>,
981 ) -> Option<T> {
982     let unpositive = if let Some(unpositive) = scalar.strip_prefix('+') {
983         if unpositive.starts_with(['+', '-']) {
984             return None;
985         }
986         unpositive
987     } else {
988         scalar
989     };
990     if let Some(rest) = unpositive.strip_prefix("0x") {
991         if rest.starts_with(['+', '-']) {
992             return None;
993         }
994         if let Ok(int) = from_str_radix(rest, 16) {
995             return Some(int);
996         }
997     }
998     if let Some(rest) = scalar.strip_prefix("-0x") {
999         let negative = format!("-{}", rest);
1000         if let Ok(int) = from_str_radix(&negative, 16) {
1001             return Some(int);
1002         }
1003     }
1004     if let Some(rest) = unpositive.strip_prefix("0o") {
1005         if rest.starts_with(['+', '-']) {
1006             return None;
1007         }
1008         if let Ok(int) = from_str_radix(rest, 8) {
1009             return Some(int);
1010         }
1011     }
1012     if let Some(rest) = scalar.strip_prefix("-0o") {
1013         let negative = format!("-{}", rest);
1014         if let Ok(int) = from_str_radix(&negative, 8) {
1015             return Some(int);
1016         }
1017     }
1018     if let Some(rest) = unpositive.strip_prefix("0b") {
1019         if rest.starts_with(['+', '-']) {
1020             return None;
1021         }
1022         if let Ok(int) = from_str_radix(rest, 2) {
1023             return Some(int);
1024         }
1025     }
1026     if let Some(rest) = scalar.strip_prefix("-0b") {
1027         let negative = format!("-{}", rest);
1028         if let Ok(int) = from_str_radix(&negative, 2) {
1029             return Some(int);
1030         }
1031     }
1032     if digits_but_not_number(scalar) {
1033         return None;
1034     }
1035     from_str_radix(unpositive, 10).ok()
1036 }
1037 
parse_negative_int<T>( scalar: &str, from_str_radix: fn(&str, radix: u32) -> Result<T, ParseIntError>, ) -> Option<T>1038 fn parse_negative_int<T>(
1039     scalar: &str,
1040     from_str_radix: fn(&str, radix: u32) -> Result<T, ParseIntError>,
1041 ) -> Option<T> {
1042     if let Some(rest) = scalar.strip_prefix("-0x") {
1043         let negative = format!("-{}", rest);
1044         if let Ok(int) = from_str_radix(&negative, 16) {
1045             return Some(int);
1046         }
1047     }
1048     if let Some(rest) = scalar.strip_prefix("-0o") {
1049         let negative = format!("-{}", rest);
1050         if let Ok(int) = from_str_radix(&negative, 8) {
1051             return Some(int);
1052         }
1053     }
1054     if let Some(rest) = scalar.strip_prefix("-0b") {
1055         let negative = format!("-{}", rest);
1056         if let Ok(int) = from_str_radix(&negative, 2) {
1057             return Some(int);
1058         }
1059     }
1060     if digits_but_not_number(scalar) {
1061         return None;
1062     }
1063     from_str_radix(scalar, 10).ok()
1064 }
1065 
parse_f64(scalar: &str) -> Option<f64>1066 pub(crate) fn parse_f64(scalar: &str) -> Option<f64> {
1067     let unpositive = if let Some(unpositive) = scalar.strip_prefix('+') {
1068         if unpositive.starts_with(['+', '-']) {
1069             return None;
1070         }
1071         unpositive
1072     } else {
1073         scalar
1074     };
1075     if let ".inf" | ".Inf" | ".INF" = unpositive {
1076         return Some(f64::INFINITY);
1077     }
1078     if let "-.inf" | "-.Inf" | "-.INF" = scalar {
1079         return Some(f64::NEG_INFINITY);
1080     }
1081     if let ".nan" | ".NaN" | ".NAN" = scalar {
1082         return Some(f64::NAN.copysign(1.0));
1083     }
1084     if let Ok(float) = unpositive.parse::<f64>() {
1085         if float.is_finite() {
1086             return Some(float);
1087         }
1088     }
1089     None
1090 }
1091 
digits_but_not_number(scalar: &str) -> bool1092 pub(crate) fn digits_but_not_number(scalar: &str) -> bool {
1093     // Leading zero(s) followed by numeric characters is a string according to
1094     // the YAML 1.2 spec. https://yaml.org/spec/1.2/spec.html#id2761292
1095     let scalar = scalar.strip_prefix(['-', '+']).unwrap_or(scalar);
1096     scalar.len() > 1 && scalar.starts_with('0') && scalar[1..].bytes().all(|b| b.is_ascii_digit())
1097 }
1098 
visit_int<'de, V>(visitor: V, v: &str) -> Result<Result<V::Value>, V> where V: Visitor<'de>,1099 pub(crate) fn visit_int<'de, V>(visitor: V, v: &str) -> Result<Result<V::Value>, V>
1100 where
1101     V: Visitor<'de>,
1102 {
1103     if let Some(int) = parse_unsigned_int(v, u64::from_str_radix) {
1104         return Ok(visitor.visit_u64(int));
1105     }
1106     if let Some(int) = parse_negative_int(v, i64::from_str_radix) {
1107         return Ok(visitor.visit_i64(int));
1108     }
1109     if let Some(int) = parse_unsigned_int(v, u128::from_str_radix) {
1110         return Ok(visitor.visit_u128(int));
1111     }
1112     if let Some(int) = parse_negative_int(v, i128::from_str_radix) {
1113         return Ok(visitor.visit_i128(int));
1114     }
1115     Err(visitor)
1116 }
1117 
visit_untagged_scalar<'de, V>( visitor: V, v: &str, repr: Option<&'de [u8]>, style: ScalarStyle, ) -> Result<V::Value> where V: Visitor<'de>,1118 pub(crate) fn visit_untagged_scalar<'de, V>(
1119     visitor: V,
1120     v: &str,
1121     repr: Option<&'de [u8]>,
1122     style: ScalarStyle,
1123 ) -> Result<V::Value>
1124 where
1125     V: Visitor<'de>,
1126 {
1127     if v.is_empty() || parse_null(v.as_bytes()) == Some(()) {
1128         return visitor.visit_unit();
1129     }
1130     if let Some(boolean) = parse_bool(v) {
1131         return visitor.visit_bool(boolean);
1132     }
1133     let visitor = match visit_int(visitor, v) {
1134         Ok(result) => return result,
1135         Err(visitor) => visitor,
1136     };
1137     if !digits_but_not_number(v) {
1138         if let Some(float) = parse_f64(v) {
1139             return visitor.visit_f64(float);
1140         }
1141     }
1142     if let Some(borrowed) = parse_borrowed_str(v, repr, style) {
1143         visitor.visit_borrowed_str(borrowed)
1144     } else {
1145         visitor.visit_str(v)
1146     }
1147 }
1148 
is_plain_or_tagged_literal_scalar( expected: &str, scalar: &Scalar, tagged_already: bool, ) -> bool1149 fn is_plain_or_tagged_literal_scalar(
1150     expected: &str,
1151     scalar: &Scalar,
1152     tagged_already: bool,
1153 ) -> bool {
1154     match (scalar.style, &scalar.tag, tagged_already) {
1155         (ScalarStyle::Plain, _, _) => true,
1156         (ScalarStyle::Literal, Some(tag), false) => tag == expected,
1157         _ => false,
1158     }
1159 }
1160 
invalid_type(event: &Event, exp: &dyn Expected) -> Error1161 fn invalid_type(event: &Event, exp: &dyn Expected) -> Error {
1162     enum Void {}
1163 
1164     struct InvalidType<'a> {
1165         exp: &'a dyn Expected,
1166     }
1167 
1168     impl<'de, 'a> Visitor<'de> for InvalidType<'a> {
1169         type Value = Void;
1170 
1171         fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1172             self.exp.fmt(formatter)
1173         }
1174     }
1175 
1176     match event {
1177         Event::Alias(_) => unreachable!(),
1178         Event::Scalar(scalar) => {
1179             let get_type = InvalidType { exp };
1180             match visit_scalar(get_type, scalar, false) {
1181                 Ok(void) => match void {},
1182                 Err(invalid_type) => invalid_type,
1183             }
1184         }
1185         Event::SequenceStart(_) => de::Error::invalid_type(Unexpected::Seq, exp),
1186         Event::MappingStart(_) => de::Error::invalid_type(Unexpected::Map, exp),
1187         Event::SequenceEnd => panic!("unexpected end of sequence"),
1188         Event::MappingEnd => panic!("unexpected end of mapping"),
1189         Event::Void => error::new(ErrorImpl::EndOfStream),
1190     }
1191 }
1192 
parse_tag(libyaml_tag: &Option<Tag>) -> Option<&str>1193 fn parse_tag(libyaml_tag: &Option<Tag>) -> Option<&str> {
1194     let mut bytes: &[u8] = libyaml_tag.as_ref()?;
1195     if let (b'!', rest) = bytes.split_first()? {
1196         if !rest.is_empty() {
1197             bytes = rest;
1198         }
1199         str::from_utf8(bytes).ok()
1200     } else {
1201         None
1202     }
1203 }
1204 
1205 impl<'de, 'document> de::Deserializer<'de> for &mut DeserializerFromEvents<'de, 'document> {
1206     type Error = Error;
1207 
deserialize_any<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1208     fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
1209     where
1210         V: Visitor<'de>,
1211     {
1212         let tagged_already = self.current_enum.is_some();
1213         let (next, mark) = self.next_event_mark()?;
1214         fn enum_tag(tag: &Option<Tag>, tagged_already: bool) -> Option<&str> {
1215             if tagged_already {
1216                 return None;
1217             }
1218             parse_tag(tag)
1219         }
1220         loop {
1221             match next {
1222                 Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_any(visitor),
1223                 Event::Scalar(scalar) => {
1224                     if let Some(tag) = enum_tag(&scalar.tag, tagged_already) {
1225                         *self.pos -= 1;
1226                         break visitor.visit_enum(EnumAccess {
1227                             de: self,
1228                             name: None,
1229                             tag,
1230                         });
1231                     }
1232                     break visit_scalar(visitor, scalar, tagged_already);
1233                 }
1234                 Event::SequenceStart(sequence) => {
1235                     if let Some(tag) = enum_tag(&sequence.tag, tagged_already) {
1236                         *self.pos -= 1;
1237                         break visitor.visit_enum(EnumAccess {
1238                             de: self,
1239                             name: None,
1240                             tag,
1241                         });
1242                     }
1243                     break self.visit_sequence(visitor, mark);
1244                 }
1245                 Event::MappingStart(mapping) => {
1246                     if let Some(tag) = enum_tag(&mapping.tag, tagged_already) {
1247                         *self.pos -= 1;
1248                         break visitor.visit_enum(EnumAccess {
1249                             de: self,
1250                             name: None,
1251                             tag,
1252                         });
1253                     }
1254                     break self.visit_mapping(visitor, mark);
1255                 }
1256                 Event::SequenceEnd => panic!("unexpected end of sequence"),
1257                 Event::MappingEnd => panic!("unexpected end of mapping"),
1258                 Event::Void => break visitor.visit_none(),
1259             }
1260         }
1261         // The de::Error impl creates errors with unknown line and column. Fill
1262         // in the position here by looking at the current index in the input.
1263         .map_err(|err| error::fix_mark(err, mark, self.path))
1264     }
1265 
deserialize_bool<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1266     fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
1267     where
1268         V: Visitor<'de>,
1269     {
1270         let tagged_already = self.current_enum.is_some();
1271         let (next, mark) = self.next_event_mark()?;
1272         loop {
1273             match next {
1274                 Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_bool(visitor),
1275                 Event::Scalar(scalar)
1276                     if is_plain_or_tagged_literal_scalar(Tag::BOOL, scalar, tagged_already) =>
1277                 {
1278                     if let Ok(value) = str::from_utf8(&scalar.value) {
1279                         if let Some(boolean) = parse_bool(value) {
1280                             break visitor.visit_bool(boolean);
1281                         }
1282                     }
1283                 }
1284                 _ => {}
1285             }
1286             break Err(invalid_type(next, &visitor));
1287         }
1288         .map_err(|err| error::fix_mark(err, mark, self.path))
1289     }
1290 
deserialize_i8<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1291     fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
1292     where
1293         V: Visitor<'de>,
1294     {
1295         self.deserialize_i64(visitor)
1296     }
1297 
deserialize_i16<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1298     fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value>
1299     where
1300         V: Visitor<'de>,
1301     {
1302         self.deserialize_i64(visitor)
1303     }
1304 
deserialize_i32<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1305     fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value>
1306     where
1307         V: Visitor<'de>,
1308     {
1309         self.deserialize_i64(visitor)
1310     }
1311 
deserialize_i64<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1312     fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value>
1313     where
1314         V: Visitor<'de>,
1315     {
1316         let tagged_already = self.current_enum.is_some();
1317         let (next, mark) = self.next_event_mark()?;
1318         loop {
1319             match next {
1320                 Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_i64(visitor),
1321                 Event::Scalar(scalar)
1322                     if is_plain_or_tagged_literal_scalar(Tag::INT, scalar, tagged_already) =>
1323                 {
1324                     if let Ok(value) = str::from_utf8(&scalar.value) {
1325                         if let Some(int) = parse_signed_int(value, i64::from_str_radix) {
1326                             break visitor.visit_i64(int);
1327                         }
1328                     }
1329                 }
1330                 _ => {}
1331             }
1332             break Err(invalid_type(next, &visitor));
1333         }
1334         .map_err(|err| error::fix_mark(err, mark, self.path))
1335     }
1336 
deserialize_i128<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1337     fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value>
1338     where
1339         V: Visitor<'de>,
1340     {
1341         let tagged_already = self.current_enum.is_some();
1342         let (next, mark) = self.next_event_mark()?;
1343         loop {
1344             match next {
1345                 Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_i128(visitor),
1346                 Event::Scalar(scalar)
1347                     if is_plain_or_tagged_literal_scalar(Tag::INT, scalar, tagged_already) =>
1348                 {
1349                     if let Ok(value) = str::from_utf8(&scalar.value) {
1350                         if let Some(int) = parse_signed_int(value, i128::from_str_radix) {
1351                             break visitor.visit_i128(int);
1352                         }
1353                     }
1354                 }
1355                 _ => {}
1356             }
1357             break Err(invalid_type(next, &visitor));
1358         }
1359         .map_err(|err| error::fix_mark(err, mark, self.path))
1360     }
1361 
deserialize_u8<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1362     fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
1363     where
1364         V: Visitor<'de>,
1365     {
1366         self.deserialize_u64(visitor)
1367     }
1368 
deserialize_u16<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1369     fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value>
1370     where
1371         V: Visitor<'de>,
1372     {
1373         self.deserialize_u64(visitor)
1374     }
1375 
deserialize_u32<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1376     fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value>
1377     where
1378         V: Visitor<'de>,
1379     {
1380         self.deserialize_u64(visitor)
1381     }
1382 
deserialize_u64<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1383     fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value>
1384     where
1385         V: Visitor<'de>,
1386     {
1387         let tagged_already = self.current_enum.is_some();
1388         let (next, mark) = self.next_event_mark()?;
1389         loop {
1390             match next {
1391                 Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_u64(visitor),
1392                 Event::Scalar(scalar)
1393                     if is_plain_or_tagged_literal_scalar(Tag::INT, scalar, tagged_already) =>
1394                 {
1395                     if let Ok(value) = str::from_utf8(&scalar.value) {
1396                         if let Some(int) = parse_unsigned_int(value, u64::from_str_radix) {
1397                             break visitor.visit_u64(int);
1398                         }
1399                     }
1400                 }
1401                 _ => {}
1402             }
1403             break Err(invalid_type(next, &visitor));
1404         }
1405         .map_err(|err| error::fix_mark(err, mark, self.path))
1406     }
1407 
deserialize_u128<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1408     fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value>
1409     where
1410         V: Visitor<'de>,
1411     {
1412         let tagged_already = self.current_enum.is_some();
1413         let (next, mark) = self.next_event_mark()?;
1414         loop {
1415             match next {
1416                 Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_u128(visitor),
1417                 Event::Scalar(scalar)
1418                     if is_plain_or_tagged_literal_scalar(Tag::INT, scalar, tagged_already) =>
1419                 {
1420                     if let Ok(value) = str::from_utf8(&scalar.value) {
1421                         if let Some(int) = parse_unsigned_int(value, u128::from_str_radix) {
1422                             break visitor.visit_u128(int);
1423                         }
1424                     }
1425                 }
1426                 _ => {}
1427             }
1428             break Err(invalid_type(next, &visitor));
1429         }
1430         .map_err(|err| error::fix_mark(err, mark, self.path))
1431     }
1432 
deserialize_f32<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1433     fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value>
1434     where
1435         V: Visitor<'de>,
1436     {
1437         self.deserialize_f64(visitor)
1438     }
1439 
deserialize_f64<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1440     fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value>
1441     where
1442         V: Visitor<'de>,
1443     {
1444         let tagged_already = self.current_enum.is_some();
1445         let (next, mark) = self.next_event_mark()?;
1446         loop {
1447             match next {
1448                 Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_f64(visitor),
1449                 Event::Scalar(scalar)
1450                     if is_plain_or_tagged_literal_scalar(Tag::FLOAT, scalar, tagged_already) =>
1451                 {
1452                     if let Ok(value) = str::from_utf8(&scalar.value) {
1453                         if let Some(float) = parse_f64(value) {
1454                             break visitor.visit_f64(float);
1455                         }
1456                     }
1457                 }
1458                 _ => {}
1459             }
1460             break Err(invalid_type(next, &visitor));
1461         }
1462         .map_err(|err| error::fix_mark(err, mark, self.path))
1463     }
1464 
deserialize_char<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1465     fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
1466     where
1467         V: Visitor<'de>,
1468     {
1469         self.deserialize_str(visitor)
1470     }
1471 
deserialize_str<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1472     fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
1473     where
1474         V: Visitor<'de>,
1475     {
1476         let (next, mark) = self.next_event_mark()?;
1477         match next {
1478             Event::Scalar(scalar) => {
1479                 if let Ok(v) = str::from_utf8(&scalar.value) {
1480                     if let Some(borrowed) = parse_borrowed_str(v, scalar.repr, scalar.style) {
1481                         visitor.visit_borrowed_str(borrowed)
1482                     } else {
1483                         visitor.visit_str(v)
1484                     }
1485                 } else {
1486                     Err(invalid_type(next, &visitor))
1487                 }
1488             }
1489             Event::Alias(mut pos) => self.jump(&mut pos)?.deserialize_str(visitor),
1490             other => Err(invalid_type(other, &visitor)),
1491         }
1492         .map_err(|err: Error| error::fix_mark(err, mark, self.path))
1493     }
1494 
deserialize_string<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1495     fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
1496     where
1497         V: Visitor<'de>,
1498     {
1499         self.deserialize_str(visitor)
1500     }
1501 
deserialize_bytes<V>(self, _visitor: V) -> Result<V::Value> where V: Visitor<'de>,1502     fn deserialize_bytes<V>(self, _visitor: V) -> Result<V::Value>
1503     where
1504         V: Visitor<'de>,
1505     {
1506         Err(error::new(ErrorImpl::BytesUnsupported))
1507     }
1508 
deserialize_byte_buf<V>(self, _visitor: V) -> Result<V::Value> where V: Visitor<'de>,1509     fn deserialize_byte_buf<V>(self, _visitor: V) -> Result<V::Value>
1510     where
1511         V: Visitor<'de>,
1512     {
1513         Err(error::new(ErrorImpl::BytesUnsupported))
1514     }
1515 
1516     /// Parses `null` as None and any other values as `Some(...)`.
deserialize_option<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1517     fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
1518     where
1519         V: Visitor<'de>,
1520     {
1521         let is_some = match self.peek_event()? {
1522             Event::Alias(mut pos) => {
1523                 *self.pos += 1;
1524                 return self.jump(&mut pos)?.deserialize_option(visitor);
1525             }
1526             Event::Scalar(scalar) => {
1527                 let tagged_already = self.current_enum.is_some();
1528                 if scalar.style != ScalarStyle::Plain {
1529                     true
1530                 } else if let (Some(tag), false) = (&scalar.tag, tagged_already) {
1531                     if tag == Tag::NULL {
1532                         if let Some(()) = parse_null(&scalar.value) {
1533                             false
1534                         } else if let Ok(v) = str::from_utf8(&scalar.value) {
1535                             return Err(de::Error::invalid_value(Unexpected::Str(v), &"null"));
1536                         } else {
1537                             return Err(de::Error::invalid_value(
1538                                 Unexpected::Bytes(&scalar.value),
1539                                 &"null",
1540                             ));
1541                         }
1542                     } else {
1543                         true
1544                     }
1545                 } else {
1546                     !scalar.value.is_empty() && parse_null(&scalar.value).is_none()
1547                 }
1548             }
1549             Event::SequenceStart(_) | Event::MappingStart(_) => true,
1550             Event::SequenceEnd => panic!("unexpected end of sequence"),
1551             Event::MappingEnd => panic!("unexpected end of mapping"),
1552             Event::Void => false,
1553         };
1554         if is_some {
1555             visitor.visit_some(self)
1556         } else {
1557             *self.pos += 1;
1558             self.current_enum = None;
1559             visitor.visit_none()
1560         }
1561     }
1562 
deserialize_unit<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1563     fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
1564     where
1565         V: Visitor<'de>,
1566     {
1567         let tagged_already = self.current_enum.is_some();
1568         let (next, mark) = self.next_event_mark()?;
1569         match next {
1570             Event::Scalar(scalar) => {
1571                 let is_null = if scalar.style != ScalarStyle::Plain {
1572                     false
1573                 } else if let (Some(tag), false) = (&scalar.tag, tagged_already) {
1574                     tag == Tag::NULL && parse_null(&scalar.value).is_some()
1575                 } else {
1576                     scalar.value.is_empty() || parse_null(&scalar.value).is_some()
1577                 };
1578                 if is_null {
1579                     visitor.visit_unit()
1580                 } else if let Ok(v) = str::from_utf8(&scalar.value) {
1581                     Err(de::Error::invalid_value(Unexpected::Str(v), &"null"))
1582                 } else {
1583                     Err(de::Error::invalid_value(
1584                         Unexpected::Bytes(&scalar.value),
1585                         &"null",
1586                     ))
1587                 }
1588             }
1589             Event::Alias(mut pos) => self.jump(&mut pos)?.deserialize_unit(visitor),
1590             Event::Void => visitor.visit_unit(),
1591             other => Err(invalid_type(other, &visitor)),
1592         }
1593         .map_err(|err| error::fix_mark(err, mark, self.path))
1594     }
1595 
deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1596     fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
1597     where
1598         V: Visitor<'de>,
1599     {
1600         self.deserialize_unit(visitor)
1601     }
1602 
1603     /// Parses a newtype struct as the underlying value.
deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1604     fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
1605     where
1606         V: Visitor<'de>,
1607     {
1608         let (_event, mark) = self.peek_event_mark()?;
1609         self.recursion_check(mark, |de| visitor.visit_newtype_struct(de))
1610     }
1611 
deserialize_seq<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1612     fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
1613     where
1614         V: Visitor<'de>,
1615     {
1616         let (next, mark) = self.next_event_mark()?;
1617         match next {
1618             Event::Alias(mut pos) => self.jump(&mut pos)?.deserialize_seq(visitor),
1619             Event::SequenceStart(_) => self.visit_sequence(visitor, mark),
1620             other => {
1621                 if match other {
1622                     Event::Void => true,
1623                     Event::Scalar(scalar) => {
1624                         scalar.value.is_empty() && scalar.style == ScalarStyle::Plain
1625                     }
1626                     _ => false,
1627                 } {
1628                     visitor.visit_seq(SeqAccess {
1629                         empty: true,
1630                         de: self,
1631                         len: 0,
1632                     })
1633                 } else {
1634                     Err(invalid_type(other, &visitor))
1635                 }
1636             }
1637         }
1638         .map_err(|err| error::fix_mark(err, mark, self.path))
1639     }
1640 
deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1641     fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value>
1642     where
1643         V: Visitor<'de>,
1644     {
1645         self.deserialize_seq(visitor)
1646     }
1647 
deserialize_tuple_struct<V>( self, _name: &'static str, _len: usize, visitor: V, ) -> Result<V::Value> where V: Visitor<'de>,1648     fn deserialize_tuple_struct<V>(
1649         self,
1650         _name: &'static str,
1651         _len: usize,
1652         visitor: V,
1653     ) -> Result<V::Value>
1654     where
1655         V: Visitor<'de>,
1656     {
1657         self.deserialize_seq(visitor)
1658     }
1659 
deserialize_map<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1660     fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
1661     where
1662         V: Visitor<'de>,
1663     {
1664         let (next, mark) = self.next_event_mark()?;
1665         match next {
1666             Event::Alias(mut pos) => self.jump(&mut pos)?.deserialize_map(visitor),
1667             Event::MappingStart(_) => self.visit_mapping(visitor, mark),
1668             other => {
1669                 if match other {
1670                     Event::Void => true,
1671                     Event::Scalar(scalar) => {
1672                         scalar.value.is_empty() && scalar.style == ScalarStyle::Plain
1673                     }
1674                     _ => false,
1675                 } {
1676                     visitor.visit_map(MapAccess {
1677                         empty: true,
1678                         de: self,
1679                         len: 0,
1680                         key: None,
1681                     })
1682                 } else {
1683                     Err(invalid_type(other, &visitor))
1684                 }
1685             }
1686         }
1687         .map_err(|err| error::fix_mark(err, mark, self.path))
1688     }
1689 
deserialize_struct<V>( self, _name: &'static str, _fields: &'static [&'static str], visitor: V, ) -> Result<V::Value> where V: Visitor<'de>,1690     fn deserialize_struct<V>(
1691         self,
1692         _name: &'static str,
1693         _fields: &'static [&'static str],
1694         visitor: V,
1695     ) -> Result<V::Value>
1696     where
1697         V: Visitor<'de>,
1698     {
1699         self.deserialize_map(visitor)
1700     }
1701 
1702     /// Parses an enum as a single key:value pair where the key identifies the
1703     /// variant and the value gives the content. A String will also parse correctly
1704     /// to a unit enum value.
deserialize_enum<V>( self, name: &'static str, variants: &'static [&'static str], visitor: V, ) -> Result<V::Value> where V: Visitor<'de>,1705     fn deserialize_enum<V>(
1706         self,
1707         name: &'static str,
1708         variants: &'static [&'static str],
1709         visitor: V,
1710     ) -> Result<V::Value>
1711     where
1712         V: Visitor<'de>,
1713     {
1714         let (next, mark) = self.peek_event_mark()?;
1715         loop {
1716             if let Some(current_enum) = self.current_enum {
1717                 if let Event::Scalar(scalar) = next {
1718                     if !scalar.value.is_empty() {
1719                         break visitor.visit_enum(UnitVariantAccess { de: self });
1720                     }
1721                 }
1722                 let message = if let Some(name) = current_enum.name {
1723                     format!(
1724                         "deserializing nested enum in {}::{} from YAML is not supported yet",
1725                         name, current_enum.tag,
1726                     )
1727                 } else {
1728                     format!(
1729                         "deserializing nested enum in !{} from YAML is not supported yet",
1730                         current_enum.tag,
1731                     )
1732                 };
1733                 break Err(error::new(ErrorImpl::Message(message, None)));
1734             }
1735             break match next {
1736                 Event::Alias(mut pos) => {
1737                     *self.pos += 1;
1738                     self.jump(&mut pos)?
1739                         .deserialize_enum(name, variants, visitor)
1740                 }
1741                 Event::Scalar(scalar) => {
1742                     if let Some(tag) = parse_tag(&scalar.tag) {
1743                         return visitor.visit_enum(EnumAccess {
1744                             de: self,
1745                             name: Some(name),
1746                             tag,
1747                         });
1748                     }
1749                     visitor.visit_enum(UnitVariantAccess { de: self })
1750                 }
1751                 Event::MappingStart(mapping) => {
1752                     if let Some(tag) = parse_tag(&mapping.tag) {
1753                         return visitor.visit_enum(EnumAccess {
1754                             de: self,
1755                             name: Some(name),
1756                             tag,
1757                         });
1758                     }
1759                     let err =
1760                         de::Error::invalid_type(Unexpected::Map, &"a YAML tag starting with '!'");
1761                     Err(error::fix_mark(err, mark, self.path))
1762                 }
1763                 Event::SequenceStart(sequence) => {
1764                     if let Some(tag) = parse_tag(&sequence.tag) {
1765                         return visitor.visit_enum(EnumAccess {
1766                             de: self,
1767                             name: Some(name),
1768                             tag,
1769                         });
1770                     }
1771                     let err =
1772                         de::Error::invalid_type(Unexpected::Seq, &"a YAML tag starting with '!'");
1773                     Err(error::fix_mark(err, mark, self.path))
1774                 }
1775                 Event::SequenceEnd => panic!("unexpected end of sequence"),
1776                 Event::MappingEnd => panic!("unexpected end of mapping"),
1777                 Event::Void => Err(error::new(ErrorImpl::EndOfStream)),
1778             };
1779         }
1780         .map_err(|err| error::fix_mark(err, mark, self.path))
1781     }
1782 
deserialize_identifier<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1783     fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value>
1784     where
1785         V: Visitor<'de>,
1786     {
1787         self.deserialize_str(visitor)
1788     }
1789 
deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>,1790     fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>
1791     where
1792         V: Visitor<'de>,
1793     {
1794         self.ignore_any()?;
1795         visitor.visit_unit()
1796     }
1797 }
1798 
1799 /// Deserialize an instance of type `T` from a string of YAML text.
1800 ///
1801 /// This conversion can fail if the structure of the Value does not match the
1802 /// structure expected by `T`, for example if `T` is a struct type but the Value
1803 /// contains something other than a YAML map. It can also fail if the structure
1804 /// is correct but `T`'s implementation of `Deserialize` decides that something
1805 /// is wrong with the data, for example required struct fields are missing from
1806 /// the YAML map or some number is too big to fit in the expected primitive
1807 /// type.
from_str<'de, T>(s: &'de str) -> Result<T> where T: Deserialize<'de>,1808 pub fn from_str<'de, T>(s: &'de str) -> Result<T>
1809 where
1810     T: Deserialize<'de>,
1811 {
1812     T::deserialize(Deserializer::from_str(s))
1813 }
1814 
1815 /// Deserialize an instance of type `T` from an IO stream of YAML.
1816 ///
1817 /// This conversion can fail if the structure of the Value does not match the
1818 /// structure expected by `T`, for example if `T` is a struct type but the Value
1819 /// contains something other than a YAML map. It can also fail if the structure
1820 /// is correct but `T`'s implementation of `Deserialize` decides that something
1821 /// is wrong with the data, for example required struct fields are missing from
1822 /// the YAML map or some number is too big to fit in the expected primitive
1823 /// type.
from_reader<R, T>(rdr: R) -> Result<T> where R: io::Read, T: DeserializeOwned,1824 pub fn from_reader<R, T>(rdr: R) -> Result<T>
1825 where
1826     R: io::Read,
1827     T: DeserializeOwned,
1828 {
1829     T::deserialize(Deserializer::from_reader(rdr))
1830 }
1831 
1832 /// Deserialize an instance of type `T` from bytes of YAML text.
1833 ///
1834 /// This conversion can fail if the structure of the Value does not match the
1835 /// structure expected by `T`, for example if `T` is a struct type but the Value
1836 /// contains something other than a YAML map. It can also fail if the structure
1837 /// is correct but `T`'s implementation of `Deserialize` decides that something
1838 /// is wrong with the data, for example required struct fields are missing from
1839 /// the YAML map or some number is too big to fit in the expected primitive
1840 /// type.
from_slice<'de, T>(v: &'de [u8]) -> Result<T> where T: Deserialize<'de>,1841 pub fn from_slice<'de, T>(v: &'de [u8]) -> Result<T>
1842 where
1843     T: Deserialize<'de>,
1844 {
1845     T::deserialize(Deserializer::from_slice(v))
1846 }
1847