Skip to main content

serde_qs/
de.rs

1//! Deserialization support for querystrings.
2//!
3//! ## Design Overview
4//!
5//! The deserializer uses a two-pass approach to handle arbitrary parameter ordering:
6//!
7//! 1. **Parse phase**: The querystring is parsed into an intermediate tree structure
8//!    (`ParsedValue`) that represents the nested data. This handles bracket notation
9//!    and builds the appropriate hierarchy.
10//!
11//! 2. **Deserialize phase**: The parsed tree is traversed and deserialized into the
12//!    target Rust types using serde's visitor pattern.
13//!
14//! ## Key Components
15//!
16//! - **`QsDeserializer`**: The top-level deserializer that handles structs and maps.
17//!   It can only deserialize map-like structures (key-value pairs).
18//!
19//! - **`parse` module**: Converts raw querystrings into `ParsedValue` trees,
20//!   handling URL decoding and bracket notation parsing.
21//!
22//! - **`ParsedValueDeserializer`**: Deserializes the intermediate `ParsedValue`
23//!   representation into target types. Handles nested maps, sequences, and primitives.
24//!
25//! ## Example Flow
26//!
27//! Given `user[name]=John&user[ids][0]=1&user[ids][1]=2`, the parser creates:
28//! ```text
29//! Map {
30//!   "user" => Map {
31//!     "name" => String("John"),
32//!     "ids" => Sequence [String("1"), String("2")]
33//!   }
34//! }
35//! ```
36//!
37//! This intermediate structure is then deserialized into the target Rust types.
38//!
39//! ## Principles
40//!
41//! 1. First, always _try_ to deserialize into the type the caller expects.
42//!
43//!    For example, if they call `deserialize_u8` and we have a `String` value,
44//!    we'll try to parse the string into a `u8`.
45//!
46//! 2. However, we'll draw the line at converting types that are fundamentally incompatible.
47//!    If we cannot represent the type and coerce the value we have into the value
48//!    they expect, and if we can't do that, forward to `deserialize_any`
49//!
50//!    For example, if they call `deserialize_string` and we have a `Map`, we won't
51//!    try to convert the map into a string. Instead, we'll forward to
52//!    `visit_map` (via `deserialize_any`) which ensures that (a) if the Visitor
53//!    actually _can_ handle maps, it has an opportunity to do so, and (b)
54//!    otherwise, we'll get reasonable errors about the type mismatch.
55//!
56//! 3. Avoid returning errors from the deserializer at all costs.
57//!    Always forward to the visitor.
58//!
59//!    If the serialized content is invalid then that is an acceptable error,
60//!    but never return an error for mismatched type vs expectations.
61//!    We extend this to things like string parsing -- if we fail to parse it as
62//!    the expected type, we will just forward to `deserialize_any`.
63//!
64//!
65//! Thanks to [@TroyKomodo](https://github.com/TroyKomodo) for the suggestions!.
66
67mod parse;
68mod string_parser;
69
70use crate::{
71    Config,
72    config::DuplicateKeyBehavior,
73    error::{Error, Result},
74};
75
76use parse::{Key, ParsedValue};
77use serde::de;
78use serde::forward_to_deserialize_any;
79use string_parser::StringParsingDeserializer;
80
81use std::borrow::Cow;
82
83/// Deserializes a querystring from a `&[u8]`.
84///
85/// ```
86/// # use serde::{Deserialize, Serialize};
87/// #[derive(Debug, Deserialize, PartialEq, Serialize)]
88/// struct Query {
89///     name: String,
90///     age: u8,
91///     occupation: String,
92/// }
93///
94/// let q =  Query {
95///     name: "Alice".to_owned(),
96///     age: 24,
97///     occupation: "Student".to_owned(),
98/// };
99///
100/// assert_eq!(
101///     serde_qs::from_bytes::<Query>(
102///         "name=Alice&age=24&occupation=Student".as_bytes()
103///     ).unwrap(), q);
104/// ```
105pub fn from_bytes<'de, T: de::Deserialize<'de>>(input: &'de [u8]) -> Result<T> {
106    Config::default().deserialize_bytes(input)
107}
108
109/// Deserializes a querystring from a `&str`.
110///
111/// ```
112/// # use serde::{Deserialize, Serialize};
113/// #[derive(Debug, Deserialize, PartialEq, Serialize)]
114/// struct Query {
115///     name: String,
116///     age: u8,
117///     occupation: String,
118/// }
119///
120/// let q =  Query {
121///     name: "Alice".to_owned(),
122///     age: 24,
123///     occupation: "Student".to_owned(),
124/// };
125///
126/// assert_eq!(
127///     serde_qs::from_str::<Query>("name=Alice&age=24&occupation=Student").unwrap(),
128///     q);
129/// ```
130pub fn from_str<'de, T: de::Deserialize<'de>>(input: &'de str) -> Result<T> {
131    from_bytes(input.as_bytes())
132}
133
134/// A deserializer for the querystring format.
135///
136/// Primarily useful if needing to use in combination with other
137/// libraries, e.g. `serde_path_to_error`.
138pub struct QsDeserializer<'a> {
139    value: ParsedValue<'a>,
140    config: Config,
141}
142
143impl<'a> QsDeserializer<'a> {
144    pub fn new(input: &'a [u8]) -> Result<Self> {
145        Self::with_config(Default::default(), input)
146    }
147
148    pub fn with_config(config: Config, input: &'a [u8]) -> Result<Self> {
149        let parsed = parse::parse(input, config)?;
150
151        Ok(Self {
152            value: parsed,
153            config,
154        })
155    }
156
157    /// Creates a deserializer from a parsed value and config.
158    fn from_value(value: ParsedValue<'a>, config: Config) -> Self {
159        Self { value, config }
160    }
161}
162
163struct MapDeserializer<'a, 'qs: 'a> {
164    parsed: &'a mut parse::ParsedMap<'qs>,
165    field_order: Option<&'static [&'static str]>,
166    popped_value: Option<ParsedValue<'qs>>,
167    config: Config,
168}
169
170impl<'a, 'de: 'a> de::MapAccess<'de> for MapDeserializer<'a, 'de> {
171    type Error = Error;
172
173    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
174    where
175        K: de::DeserializeSeed<'de>,
176    {
177        // we'll prefer to use the field order if it exists
178        if let Some(field_order) = &mut self.field_order {
179            while let Some((field, rem)) = field_order.split_first() {
180                *field_order = rem;
181                let field_key = (*field).into();
182                if let Some(value) = crate::map::remove(self.parsed, &field_key) {
183                    self.popped_value = Some(value);
184                    return seed
185                        .deserialize(StringParsingDeserializer::new_str(field))
186                        .map(Some);
187                }
188            }
189        }
190
191        // once we've exhausted the field order, we can
192        // just iterate remaining elements in the map
193        if let Some((key, value)) = crate::map::pop_first(self.parsed) {
194            self.popped_value = Some(value);
195            let has_bracket = matches!(key, Key::String(ref s) if s.contains(&b'['));
196            key.deserialize_seed(seed)
197                .map(Some)
198                .map_err(|e| {
199                    if has_bracket {
200                        Error::custom(
201                            format!("{e}\nInvalid field contains an encoded bracket -- consider using form encoding mode\n  https://docs.rs/serde_qs/latest/serde_qs/#query-string-vs-form-encoding")
202                            , &self.parsed
203                        )
204                    } else {
205                        e
206                    }
207                })
208        } else {
209            Ok(None)
210        }
211    }
212
213    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
214    where
215        V: de::DeserializeSeed<'de>,
216    {
217        if let Some(v) = self.popped_value.take() {
218            seed.deserialize(QsDeserializer::from_value(v, self.config))
219        } else {
220            Err(Error::custom(
221                "Somehow the map was empty after a non-empty key was returned",
222                &self.parsed,
223            ))
224        }
225    }
226
227    fn size_hint(&self) -> Option<usize> {
228        if let Some(field_order) = self.field_order {
229            Some(field_order.len())
230        } else {
231            Some(self.parsed.len())
232        }
233    }
234}
235
236impl<'a, 'de: 'a> de::EnumAccess<'de> for MapDeserializer<'a, 'de> {
237    type Error = Error;
238    type Variant = Self;
239
240    fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, Self::Variant)>
241    where
242        V: de::DeserializeSeed<'de>,
243    {
244        if let Some((key, value)) = crate::map::pop_first(self.parsed) {
245            self.popped_value = Some(value);
246            Ok((key.deserialize_seed(seed)?, self))
247        } else {
248            Err(Error::custom("No more values", &self.parsed))
249        }
250    }
251}
252
253impl<'a, 'de: 'a> de::VariantAccess<'de> for MapDeserializer<'a, 'de> {
254    type Error = Error;
255    fn unit_variant(self) -> Result<()> {
256        Ok(())
257    }
258
259    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
260    where
261        T: de::DeserializeSeed<'de>,
262    {
263        if let Some(value) = self.popped_value {
264            seed.deserialize(QsDeserializer::from_value(value, self.config))
265        } else {
266            Err(Error::custom("no value to deserialize", &self.parsed))
267        }
268    }
269    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value>
270    where
271        V: de::Visitor<'de>,
272    {
273        if let Some(value) = self.popped_value {
274            de::Deserializer::deserialize_seq(
275                QsDeserializer::from_value(value, self.config),
276                visitor,
277            )
278        } else {
279            Err(Error::custom("no value to deserialize", &self.parsed))
280        }
281    }
282    fn struct_variant<V>(self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
283    where
284        V: de::Visitor<'de>,
285    {
286        if let Some(value) = self.popped_value {
287            de::Deserializer::deserialize_map(
288                QsDeserializer::from_value(value, self.config),
289                visitor,
290            )
291        } else {
292            Err(Error::custom("no value to deserialize", &self.parsed))
293        }
294    }
295}
296
297struct Seq<'a, I: Iterator<Item = ParsedValue<'a>>> {
298    iter: I,
299    config: Config,
300}
301
302impl<'de, I: Iterator<Item = ParsedValue<'de>>> de::SeqAccess<'de> for Seq<'de, I> {
303    type Error = Error;
304    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
305    where
306        T: de::DeserializeSeed<'de>,
307    {
308        if let Some(v) = self.iter.next() {
309            seed.deserialize(QsDeserializer::from_value(v, self.config))
310                .map(Some)
311        } else {
312            Ok(None)
313        }
314    }
315
316    fn size_hint(&self) -> Option<usize> {
317        match self.iter.size_hint() {
318            (lower, Some(upper)) if lower == upper => Some(upper),
319            _ => None,
320        }
321    }
322}
323
324impl<'a, I> OrderedSeq<'a, I>
325where
326    I: Iterator<Item = (Key<'a>, ParsedValue<'a>)>,
327{
328    /// Creates a new `OrderedSeq` from an iterator.
329    pub fn new(iter: I, config: Config) -> Self {
330        Self {
331            iter,
332            counter: 0,
333            config,
334        }
335    }
336}
337
338struct OrderedSeq<'a, I: Iterator<Item = (Key<'a>, ParsedValue<'a>)>> {
339    iter: I,
340    counter: u32,
341    config: Config,
342}
343
344impl<'de, I: Iterator<Item = (Key<'de>, ParsedValue<'de>)>> de::SeqAccess<'de>
345    for OrderedSeq<'de, I>
346{
347    type Error = Error;
348    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
349    where
350        T: de::DeserializeSeed<'de>,
351    {
352        if let Some((k, v)) = self.iter.next() {
353            match k {
354                Key::Int(i) if i == self.counter => {
355                    self.counter = self.counter.checked_add(1).ok_or_else(|| {
356                        Error::custom("cannot deserialize more than u32::MAX elements", &(k, &v))
357                    })?;
358                    seed.deserialize(QsDeserializer::from_value(v, self.config))
359                        .map(Some)
360                }
361                Key::Int(i) => Err(Error::custom(
362                    format!("missing index, expected: {} got {i}", self.counter),
363                    &(k, v),
364                )),
365                Key::String(ref bytes) => {
366                    let key = std::str::from_utf8(bytes).unwrap_or("<non-utf8>");
367                    Err(Error::custom(
368                        format!("expected an integer index, found a string key `{key}`"),
369                        &(k, v),
370                    ))
371                }
372            }
373        } else {
374            Ok(None)
375        }
376    }
377
378    fn size_hint(&self) -> Option<usize> {
379        // cannot provide a size hint since we might have gaps
380        None
381    }
382}
383
384fn get_last_string_value<'a>(
385    seq: &mut Vec<ParsedValue<'a>>,
386    config: Config,
387) -> Result<Option<Cow<'a, [u8]>>> {
388    // Check for duplicates if configured to error
389    if config.duplicate_key_behavior == DuplicateKeyBehavior::Error && seq.len() > 1 {
390        return Err(Error::custom(
391            "multiple values provided for non-sequence field",
392            seq,
393        ));
394    }
395
396    Ok(match seq.last() {
397        None => None,
398        Some(ParsedValue::NoValue | ParsedValue::Null) => {
399            // if we have no value, we can just return an empty string
400            Some(Cow::Borrowed(b""))
401        }
402        Some(ParsedValue::String(_)) => {
403            if let Some(ParsedValue::String(s)) = seq.pop() {
404                Some(s)
405            } else {
406                // unreachable, since we checked the last value above
407                None
408            }
409        }
410        Some(_) => {
411            // if the last value is not a string, we cannot return it as a string
412            // so we just return None
413            None
414        }
415    })
416}
417
418macro_rules! forward_to_string_parser {
419    ($($ty:ident => $meth:ident,)*) => {
420        $(
421            fn $meth<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de> {
422                let s = match self.value {
423                    ParsedValue::String(s) => {
424                        s
425                    }
426                    ParsedValue::Sequence(mut seq) => {
427                        match get_last_string_value(&mut seq, self.config) {
428                            Ok(Some(v)) => v,
429                            Ok(None) => {
430                                return Self::from_value(ParsedValue::Sequence(seq), self.config)
431                                    .deserialize_any(visitor);
432                            }
433                            Err(e) => return Err(e),
434                        }
435                    }
436                    _ => {
437                        return self.deserialize_any(visitor);
438                    }
439                };
440                let deserializer = StringParsingDeserializer::new(s)?;
441                return deserializer.$meth(visitor);
442            }
443        )*
444    }
445}
446
447impl<'de> de::Deserializer<'de> for QsDeserializer<'de> {
448    type Error = Error;
449
450    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
451    where
452        V: de::Visitor<'de>,
453    {
454        match self.value {
455            ParsedValue::Map(mut parsed) => {
456                // scan the map to check if all keys are integers
457                // if so, we'll treat it as a sequence
458                if parsed.keys().all(|k| matches!(k, Key::Int(_))) {
459                    #[cfg(feature = "indexmap")]
460                    parsed.sort_unstable_keys();
461                    visitor.visit_seq(OrderedSeq::new(parsed.into_iter(), self.config))
462                } else {
463                    visitor.visit_map(MapDeserializer {
464                        parsed: &mut parsed,
465                        field_order: None,
466                        popped_value: None,
467                        config: self.config,
468                    })
469                }
470            }
471            ParsedValue::Sequence(seq) => visitor.visit_seq(Seq {
472                iter: seq.into_iter(),
473                config: self.config,
474            }),
475            ParsedValue::String(x) => StringParsingDeserializer::new(x)?.deserialize_any(visitor),
476            ParsedValue::Uninitialized => Err(Error::custom(
477                "internal error: attempted to deserialize unitialised \
478                 value",
479                &self.value,
480            )),
481
482            ParsedValue::Null => {
483                StringParsingDeserializer::new(Cow::Borrowed(b""))?.deserialize_any(visitor)
484            }
485            ParsedValue::NoValue => visitor.visit_unit(),
486        }
487    }
488
489    fn deserialize_seq<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
490    where
491        V: de::Visitor<'de>,
492    {
493        match self.value {
494            ParsedValue::Null | ParsedValue::NoValue => visitor.visit_seq(Seq {
495                iter: std::iter::empty(),
496                config: self.config,
497            }),
498            // if we have a single string key, but expect a sequence
499            // we'll treat it as a sequence of one
500            // this helps with cases like `a=1` where we have unindexed keys and only a single value
501            ParsedValue::String(s) => visitor.visit_seq(Seq {
502                iter: std::iter::once(ParsedValue::String(s)),
503                config: self.config,
504            }),
505            _ => self.deserialize_any(visitor),
506        }
507    }
508
509    fn deserialize_tuple<V>(
510        self,
511        _len: usize,
512        visitor: V,
513    ) -> std::result::Result<V::Value, Self::Error>
514    where
515        V: de::Visitor<'de>,
516    {
517        self.deserialize_seq(visitor)
518    }
519
520    fn deserialize_tuple_struct<V>(
521        self,
522        _name: &'static str,
523        _len: usize,
524        visitor: V,
525    ) -> std::result::Result<V::Value, Self::Error>
526    where
527        V: de::Visitor<'de>,
528    {
529        self.deserialize_seq(visitor)
530    }
531
532    fn deserialize_struct<V>(
533        self,
534        _name: &'static str,
535        fields: &'static [&'static str],
536        visitor: V,
537    ) -> std::result::Result<V::Value, Self::Error>
538    where
539        V: de::Visitor<'de>,
540    {
541        let mut map = match self.value {
542            ParsedValue::Map(map) => map,
543            ParsedValue::Null | ParsedValue::NoValue => {
544                // if we have no value, we can just return an empty map
545                parse::ParsedMap::default()
546            }
547            _ => return self.deserialize_any(visitor),
548        };
549
550        visitor.visit_map(MapDeserializer {
551            parsed: &mut map,
552            field_order: Some(fields),
553            popped_value: None,
554            config: self.config,
555        })
556    }
557
558    fn deserialize_newtype_struct<V>(
559        self,
560        _name: &'static str,
561        visitor: V,
562    ) -> std::result::Result<V::Value, Self::Error>
563    where
564        V: de::Visitor<'de>,
565    {
566        visitor.visit_newtype_struct(self)
567    }
568
569    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
570    where
571        V: de::Visitor<'de>,
572    {
573        match self.value {
574            ParsedValue::NoValue => visitor.visit_none(),
575            // `foo=` is explicitly used to represent a `Some` value
576            // where the inner value is empty
577            ParsedValue::Null => visitor.visit_some(QsDeserializer::from_value(
578                ParsedValue::NoValue,
579                self.config,
580            )),
581            _ => visitor.visit_some(self),
582        }
583    }
584
585    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
586    where
587        V: de::Visitor<'de>,
588    {
589        // we'll tolerate `x=` as a unit value
590        if matches!(self.value, ParsedValue::Null)
591            || matches!(self.value, ParsedValue::String(ref s) if s.is_empty())
592        {
593            visitor.visit_unit()
594        } else {
595            self.deserialize_any(visitor)
596        }
597    }
598
599    fn deserialize_unit_struct<V>(
600        self,
601        _name: &'static str,
602        visitor: V,
603    ) -> std::result::Result<V::Value, Self::Error>
604    where
605        V: de::Visitor<'de>,
606    {
607        self.deserialize_unit(visitor)
608    }
609
610    fn deserialize_enum<V>(
611        self,
612        _name: &'static str,
613        _variants: &'static [&'static str],
614        visitor: V,
615    ) -> Result<V::Value>
616    where
617        V: de::Visitor<'de>,
618    {
619        match self.value {
620            ParsedValue::Map(mut parsed) => visitor.visit_enum(MapDeserializer {
621                parsed: &mut parsed,
622                field_order: None,
623                popped_value: None,
624                config: self.config,
625            }),
626            ParsedValue::String(s) => visitor.visit_enum(StringParsingDeserializer::new(s)?),
627            _ => self.deserialize_any(visitor),
628        }
629    }
630
631    /// given the hint that this is a map, will first
632    /// attempt to deserialize ordered sequences into a map
633    /// otherwise, follows the any code path
634    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
635    where
636        V: de::Visitor<'de>,
637    {
638        match self.value {
639            ParsedValue::Map(mut parsed) => visitor.visit_map(MapDeserializer {
640                parsed: &mut parsed,
641                field_order: None,
642                popped_value: None,
643                config: self.config,
644            }),
645            ParsedValue::Null | ParsedValue::NoValue => {
646                let mut empty_map = parse::ParsedMap::default();
647                visitor.visit_map(MapDeserializer {
648                    parsed: &mut empty_map,
649                    field_order: None,
650                    popped_value: None,
651                    config: self.config,
652                })
653            }
654            ParsedValue::String(s) => {
655                // if we have a single string key, but expect a map
656                // we'll treat it as a map with one key
657                // this is for cases like `=foo` which we are currently using
658                // to represent flat data structures.
659                //
660                // This is not a great way to handle this. Would be preferable
661                // if simple String primitives has a different representation
662                let mut parsed = parse::ParsedMap::default();
663                parsed.insert(Key::String(Cow::Borrowed(b"")), ParsedValue::String(s));
664                visitor.visit_map(MapDeserializer {
665                    parsed: &mut parsed,
666                    field_order: None,
667                    popped_value: None,
668                    config: self.config,
669                })
670            }
671            _ => self.deserialize_any(visitor),
672        }
673    }
674
675    fn deserialize_str<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
676    where
677        V: de::Visitor<'de>,
678    {
679        let s = match self.value {
680            ParsedValue::String(s) => s,
681            ParsedValue::Sequence(mut seq) => match get_last_string_value(&mut seq, self.config) {
682                Ok(Some(v)) => v,
683                Ok(None) => {
684                    return Self::from_value(ParsedValue::Sequence(seq), self.config)
685                        .deserialize_any(visitor);
686                }
687                Err(e) => return Err(e),
688            },
689            ParsedValue::Null | ParsedValue::NoValue => {
690                return visitor.visit_str("");
691            }
692            _ => return self.deserialize_any(visitor),
693        };
694
695        match string_parser::decode_utf8(s)? {
696            Cow::Borrowed(string) => visitor.visit_borrowed_str(string),
697            Cow::Owned(string) => visitor.visit_string(string),
698        }
699    }
700
701    fn deserialize_string<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
702    where
703        V: de::Visitor<'de>,
704    {
705        self.deserialize_str(visitor)
706    }
707
708    fn deserialize_bytes<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
709    where
710        V: de::Visitor<'de>,
711    {
712        let s = match self.value {
713            ParsedValue::String(s) => s,
714            ParsedValue::Sequence(mut seq) => match get_last_string_value(&mut seq, self.config) {
715                Ok(Some(v)) => v,
716                Ok(None) => {
717                    return Self::from_value(ParsedValue::Sequence(seq), self.config)
718                        .deserialize_any(visitor);
719                }
720                Err(e) => return Err(e),
721            },
722            ParsedValue::Null | ParsedValue::NoValue => {
723                return visitor.visit_bytes(&[]);
724            }
725            _ => return self.deserialize_any(visitor),
726        };
727        match s {
728            Cow::Borrowed(s) => visitor.visit_borrowed_bytes(s),
729            Cow::Owned(s) => visitor.visit_byte_buf(s),
730        }
731    }
732
733    fn deserialize_byte_buf<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
734    where
735        V: de::Visitor<'de>,
736    {
737        self.deserialize_bytes(visitor)
738    }
739
740    fn deserialize_ignored_any<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
741    where
742        V: de::Visitor<'de>,
743    {
744        match self.value {
745            // for ignored values, we wont attempt to parse the value
746            // as a UTF8 string, but rather just pass the bytes along.
747            // since the value is ignored anyway, this is great since
748            // we'll just drop it and avoid raising UTF8 errors.
749            ParsedValue::String(cow) => match cow {
750                Cow::Borrowed(s) => visitor.visit_borrowed_bytes(s),
751                Cow::Owned(s) => visitor.visit_byte_buf(s),
752            },
753            _ => self.deserialize_any(visitor),
754        }
755    }
756
757    fn deserialize_bool<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
758    where
759        V: de::Visitor<'de>,
760    {
761        match self.value {
762            ParsedValue::String(s) => {
763                let deserializer = StringParsingDeserializer::new(s)?;
764                deserializer.deserialize_bool(visitor)
765            }
766            ParsedValue::Sequence(mut seq) => {
767                match get_last_string_value(&mut seq, self.config) {
768                    Ok(Some(last_value)) => {
769                        StringParsingDeserializer::new(last_value)?.deserialize_bool(visitor)
770                    }
771                    Ok(None) => {
772                        // if we have a sequence, but the last value is not a string,
773                        // we'll just forward to deserialize_any
774                        Self::from_value(ParsedValue::Sequence(seq), self.config)
775                            .deserialize_any(visitor)
776                    }
777                    Err(e) => Err(e),
778                }
779            }
780            // if the field is _present_ we'll treat it as a boolean true
781            ParsedValue::Null | ParsedValue::NoValue => visitor.visit_bool(true),
782            _ => self.deserialize_any(visitor),
783        }
784    }
785
786    forward_to_deserialize_any! {
787        char
788        identifier
789    }
790
791    forward_to_string_parser! {
792        u8 => deserialize_u8,
793        u16 => deserialize_u16,
794        u32 => deserialize_u32,
795        u64 => deserialize_u64,
796        i8 => deserialize_i8,
797        i16 => deserialize_i16,
798        i32 => deserialize_i32,
799        i64 => deserialize_i64,
800        f32 => deserialize_f32,
801        f64 => deserialize_f64,
802    }
803}