Skip to main content

dbt_yaml/
de.rs

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