Skip to main content

serde_yaml/
de.rs

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