serde_qs 1.1.1

Querystrings for Serde
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! Deserialization support for querystrings.
//!
//! ## Design Overview
//!
//! The deserializer uses a two-pass approach to handle arbitrary parameter ordering:
//!
//! 1. **Parse phase**: The querystring is parsed into an intermediate tree structure
//!    (`ParsedValue`) that represents the nested data. This handles bracket notation
//!    and builds the appropriate hierarchy.
//!
//! 2. **Deserialize phase**: The parsed tree is traversed and deserialized into the
//!    target Rust types using serde's visitor pattern.
//!
//! ## Key Components
//!
//! - **`QsDeserializer`**: The top-level deserializer that handles structs and maps.
//!   It can only deserialize map-like structures (key-value pairs).
//!
//! - **`parse` module**: Converts raw querystrings into `ParsedValue` trees,
//!   handling URL decoding and bracket notation parsing.
//!
//! - **`ParsedValueDeserializer`**: Deserializes the intermediate `ParsedValue`
//!   representation into target types. Handles nested maps, sequences, and primitives.
//!
//! ## Example Flow
//!
//! Given `user[name]=John&user[ids][0]=1&user[ids][1]=2`, the parser creates:
//! ```text
//! Map {
//!   "user" => Map {
//!     "name" => String("John"),
//!     "ids" => Sequence [String("1"), String("2")]
//!   }
//! }
//! ```
//!
//! This intermediate structure is then deserialized into the target Rust types.
//!
//! ## Principles
//!
//! 1. First, always _try_ to deserialize into the type the caller expects.
//!
//!    For example, if they call `deserialize_u8` and we have a `String` value,
//!    we'll try to parse the string into a `u8`.
//!
//! 2. However, we'll draw the line at converting types that are fundamentally incompatible.
//!    If we cannot represent the type and coerce the value we have into the value
//!    they expect, and if we can't do that, forward to `deserialize_any`
//!
//!    For example, if they call `deserialize_string` and we have a `Map`, we won't
//!    try to convert the map into a string. Instead, we'll forward to
//!    `visit_map` (via `deserialize_any`) which ensures that (a) if the Visitor
//!    actually _can_ handle maps, it has an opportunity to do so, and (b)
//!    otherwise, we'll get reasonable errors about the type mismatch.
//!
//! 3. Avoid returning errors from the deserializer at all costs.
//!    Always forward to the visitor.
//!
//!    If the serialized content is invalid then that is an acceptable error,
//!    but never return an error for mismatched type vs expectations.
//!    We extend this to things like string parsing -- if we fail to parse it as
//!    the expected type, we will just forward to `deserialize_any`.
//!
//!
//! Thanks to [@TroyKomodo](https://github.com/TroyKomodo) for the suggestions!.

mod parse;
mod string_parser;

use crate::{
    Config,
    config::DuplicateKeyBehavior,
    error::{Error, Result},
};

use parse::{Key, ParsedValue};
use serde::de;
use serde::forward_to_deserialize_any;
use string_parser::StringParsingDeserializer;

use std::borrow::Cow;

/// Deserializes a querystring from a `&[u8]`.
///
/// ```
/// # use serde::{Deserialize, Serialize};
/// #[derive(Debug, Deserialize, PartialEq, Serialize)]
/// struct Query {
///     name: String,
///     age: u8,
///     occupation: String,
/// }
///
/// let q =  Query {
///     name: "Alice".to_owned(),
///     age: 24,
///     occupation: "Student".to_owned(),
/// };
///
/// assert_eq!(
///     serde_qs::from_bytes::<Query>(
///         "name=Alice&age=24&occupation=Student".as_bytes()
///     ).unwrap(), q);
/// ```
pub fn from_bytes<'de, T: de::Deserialize<'de>>(input: &'de [u8]) -> Result<T> {
    Config::default().deserialize_bytes(input)
}

/// Deserializes a querystring from a `&str`.
///
/// ```
/// # use serde::{Deserialize, Serialize};
/// #[derive(Debug, Deserialize, PartialEq, Serialize)]
/// struct Query {
///     name: String,
///     age: u8,
///     occupation: String,
/// }
///
/// let q =  Query {
///     name: "Alice".to_owned(),
///     age: 24,
///     occupation: "Student".to_owned(),
/// };
///
/// assert_eq!(
///     serde_qs::from_str::<Query>("name=Alice&age=24&occupation=Student").unwrap(),
///     q);
/// ```
pub fn from_str<'de, T: de::Deserialize<'de>>(input: &'de str) -> Result<T> {
    from_bytes(input.as_bytes())
}

/// A deserializer for the querystring format.
///
/// Primarily useful if needing to use in combination with other
/// libraries, e.g. `serde_path_to_error`.
pub struct QsDeserializer<'a> {
    value: ParsedValue<'a>,
    config: Config,
}

impl<'a> QsDeserializer<'a> {
    pub fn new(input: &'a [u8]) -> Result<Self> {
        Self::with_config(Default::default(), input)
    }

    pub fn with_config(config: Config, input: &'a [u8]) -> Result<Self> {
        let parsed = parse::parse(input, config)?;

        Ok(Self {
            value: parsed,
            config,
        })
    }

    /// Creates a deserializer from a parsed value and config.
    fn from_value(value: ParsedValue<'a>, config: Config) -> Self {
        Self { value, config }
    }
}

struct MapDeserializer<'a, 'qs: 'a> {
    parsed: &'a mut parse::ParsedMap<'qs>,
    field_order: Option<&'static [&'static str]>,
    popped_value: Option<ParsedValue<'qs>>,
    config: Config,
}

impl<'a, 'de: 'a> de::MapAccess<'de> for MapDeserializer<'a, 'de> {
    type Error = Error;

    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
    where
        K: de::DeserializeSeed<'de>,
    {
        // we'll prefer to use the field order if it exists
        if let Some(field_order) = &mut self.field_order {
            while let Some((field, rem)) = field_order.split_first() {
                *field_order = rem;
                let field_key = (*field).into();
                if let Some(value) = crate::map::remove(self.parsed, &field_key) {
                    self.popped_value = Some(value);
                    return seed
                        .deserialize(StringParsingDeserializer::new_str(field))
                        .map(Some);
                }
            }
        }

        // once we've exhausted the field order, we can
        // just iterate remaining elements in the map
        if let Some((key, value)) = crate::map::pop_first(self.parsed) {
            self.popped_value = Some(value);
            let has_bracket = matches!(key, Key::String(ref s) if s.contains(&b'['));
            key.deserialize_seed(seed)
                .map(Some)
                .map_err(|e| {
                    if has_bracket {
                        Error::custom(
                            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")
                            , &self.parsed
                        )
                    } else {
                        e
                    }
                })
        } else {
            Ok(None)
        }
    }

    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
    where
        V: de::DeserializeSeed<'de>,
    {
        if let Some(v) = self.popped_value.take() {
            seed.deserialize(QsDeserializer::from_value(v, self.config))
        } else {
            Err(Error::custom(
                "Somehow the map was empty after a non-empty key was returned",
                &self.parsed,
            ))
        }
    }

    fn size_hint(&self) -> Option<usize> {
        if let Some(field_order) = self.field_order {
            Some(field_order.len())
        } else {
            Some(self.parsed.len())
        }
    }
}

impl<'a, 'de: 'a> de::EnumAccess<'de> for MapDeserializer<'a, 'de> {
    type Error = Error;
    type Variant = Self;

    fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, Self::Variant)>
    where
        V: de::DeserializeSeed<'de>,
    {
        if let Some((key, value)) = crate::map::pop_first(self.parsed) {
            self.popped_value = Some(value);
            Ok((key.deserialize_seed(seed)?, self))
        } else {
            Err(Error::custom("No more values", &self.parsed))
        }
    }
}

impl<'a, 'de: 'a> de::VariantAccess<'de> for MapDeserializer<'a, 'de> {
    type Error = Error;
    fn unit_variant(self) -> Result<()> {
        Ok(())
    }

    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
    where
        T: de::DeserializeSeed<'de>,
    {
        if let Some(value) = self.popped_value {
            seed.deserialize(QsDeserializer::from_value(value, self.config))
        } else {
            Err(Error::custom("no value to deserialize", &self.parsed))
        }
    }
    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        if let Some(value) = self.popped_value {
            de::Deserializer::deserialize_seq(
                QsDeserializer::from_value(value, self.config),
                visitor,
            )
        } else {
            Err(Error::custom("no value to deserialize", &self.parsed))
        }
    }
    fn struct_variant<V>(self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        if let Some(value) = self.popped_value {
            de::Deserializer::deserialize_map(
                QsDeserializer::from_value(value, self.config),
                visitor,
            )
        } else {
            Err(Error::custom("no value to deserialize", &self.parsed))
        }
    }
}

struct Seq<'a, I: Iterator<Item = ParsedValue<'a>>> {
    iter: I,
    config: Config,
}

impl<'de, I: Iterator<Item = ParsedValue<'de>>> de::SeqAccess<'de> for Seq<'de, I> {
    type Error = Error;
    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
    where
        T: de::DeserializeSeed<'de>,
    {
        if let Some(v) = self.iter.next() {
            seed.deserialize(QsDeserializer::from_value(v, self.config))
                .map(Some)
        } else {
            Ok(None)
        }
    }

    fn size_hint(&self) -> Option<usize> {
        match self.iter.size_hint() {
            (lower, Some(upper)) if lower == upper => Some(upper),
            _ => None,
        }
    }
}

impl<'a, I> OrderedSeq<'a, I>
where
    I: Iterator<Item = (Key<'a>, ParsedValue<'a>)>,
{
    /// Creates a new `OrderedSeq` from an iterator.
    pub fn new(iter: I, config: Config) -> Self {
        Self {
            iter,
            counter: 0,
            config,
        }
    }
}

struct OrderedSeq<'a, I: Iterator<Item = (Key<'a>, ParsedValue<'a>)>> {
    iter: I,
    counter: u32,
    config: Config,
}

impl<'de, I: Iterator<Item = (Key<'de>, ParsedValue<'de>)>> de::SeqAccess<'de>
    for OrderedSeq<'de, I>
{
    type Error = Error;
    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
    where
        T: de::DeserializeSeed<'de>,
    {
        if let Some((k, v)) = self.iter.next() {
            match k {
                Key::Int(i) if i == self.counter => {
                    self.counter = self.counter.checked_add(1).ok_or_else(|| {
                        Error::custom("cannot deserialize more than u32::MAX elements", &(k, &v))
                    })?;
                    seed.deserialize(QsDeserializer::from_value(v, self.config))
                        .map(Some)
                }
                Key::Int(i) => Err(Error::custom(
                    format!("missing index, expected: {} got {i}", self.counter),
                    &(k, v),
                )),
                Key::String(ref bytes) => {
                    let key = std::str::from_utf8(bytes).unwrap_or("<non-utf8>");
                    Err(Error::custom(
                        format!("expected an integer index, found a string key `{key}`"),
                        &(k, v),
                    ))
                }
            }
        } else {
            Ok(None)
        }
    }

    fn size_hint(&self) -> Option<usize> {
        // cannot provide a size hint since we might have gaps
        None
    }
}

fn get_last_string_value<'a>(
    seq: &mut Vec<ParsedValue<'a>>,
    config: Config,
) -> Result<Option<Cow<'a, [u8]>>> {
    // Check for duplicates if configured to error
    if config.duplicate_key_behavior == DuplicateKeyBehavior::Error && seq.len() > 1 {
        return Err(Error::custom(
            "multiple values provided for non-sequence field",
            seq,
        ));
    }

    Ok(match seq.last() {
        None => None,
        Some(ParsedValue::NoValue | ParsedValue::Null) => {
            // if we have no value, we can just return an empty string
            Some(Cow::Borrowed(b""))
        }
        Some(ParsedValue::String(_)) => {
            if let Some(ParsedValue::String(s)) = seq.pop() {
                Some(s)
            } else {
                // unreachable, since we checked the last value above
                None
            }
        }
        Some(_) => {
            // if the last value is not a string, we cannot return it as a string
            // so we just return None
            None
        }
    })
}

macro_rules! forward_to_string_parser {
    ($($ty:ident => $meth:ident,)*) => {
        $(
            fn $meth<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de> {
                let s = match self.value {
                    ParsedValue::String(s) => {
                        s
                    }
                    ParsedValue::Sequence(mut seq) => {
                        match get_last_string_value(&mut seq, self.config) {
                            Ok(Some(v)) => v,
                            Ok(None) => {
                                return Self::from_value(ParsedValue::Sequence(seq), self.config)
                                    .deserialize_any(visitor);
                            }
                            Err(e) => return Err(e),
                        }
                    }
                    _ => {
                        return self.deserialize_any(visitor);
                    }
                };
                let deserializer = StringParsingDeserializer::new(s)?;
                return deserializer.$meth(visitor);
            }
        )*
    }
}

impl<'de> de::Deserializer<'de> for QsDeserializer<'de> {
    type Error = Error;

    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        match self.value {
            ParsedValue::Map(mut parsed) => {
                // scan the map to check if all keys are integers
                // if so, we'll treat it as a sequence
                if parsed.keys().all(|k| matches!(k, Key::Int(_))) {
                    #[cfg(feature = "indexmap")]
                    parsed.sort_unstable_keys();
                    visitor.visit_seq(OrderedSeq::new(parsed.into_iter(), self.config))
                } else {
                    visitor.visit_map(MapDeserializer {
                        parsed: &mut parsed,
                        field_order: None,
                        popped_value: None,
                        config: self.config,
                    })
                }
            }
            ParsedValue::Sequence(seq) => visitor.visit_seq(Seq {
                iter: seq.into_iter(),
                config: self.config,
            }),
            ParsedValue::String(x) => StringParsingDeserializer::new(x)?.deserialize_any(visitor),
            ParsedValue::Uninitialized => Err(Error::custom(
                "internal error: attempted to deserialize unitialised \
                 value",
                &self.value,
            )),

            ParsedValue::Null => {
                StringParsingDeserializer::new(Cow::Borrowed(b""))?.deserialize_any(visitor)
            }
            ParsedValue::NoValue => visitor.visit_unit(),
        }
    }

    fn deserialize_seq<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        match self.value {
            ParsedValue::Null | ParsedValue::NoValue => visitor.visit_seq(Seq {
                iter: std::iter::empty(),
                config: self.config,
            }),
            // if we have a single string key, but expect a sequence
            // we'll treat it as a sequence of one
            // this helps with cases like `a=1` where we have unindexed keys and only a single value
            ParsedValue::String(s) => visitor.visit_seq(Seq {
                iter: std::iter::once(ParsedValue::String(s)),
                config: self.config,
            }),
            _ => self.deserialize_any(visitor),
        }
    }

    fn deserialize_tuple<V>(
        self,
        _len: usize,
        visitor: V,
    ) -> std::result::Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        self.deserialize_seq(visitor)
    }

    fn deserialize_tuple_struct<V>(
        self,
        _name: &'static str,
        _len: usize,
        visitor: V,
    ) -> std::result::Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        self.deserialize_seq(visitor)
    }

    fn deserialize_struct<V>(
        self,
        _name: &'static str,
        fields: &'static [&'static str],
        visitor: V,
    ) -> std::result::Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        let mut map = match self.value {
            ParsedValue::Map(map) => map,
            ParsedValue::Null | ParsedValue::NoValue => {
                // if we have no value, we can just return an empty map
                parse::ParsedMap::default()
            }
            _ => return self.deserialize_any(visitor),
        };

        visitor.visit_map(MapDeserializer {
            parsed: &mut map,
            field_order: Some(fields),
            popped_value: None,
            config: self.config,
        })
    }

    fn deserialize_newtype_struct<V>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> std::result::Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        visitor.visit_newtype_struct(self)
    }

    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        match self.value {
            ParsedValue::NoValue => visitor.visit_none(),
            // `foo=` is explicitly used to represent a `Some` value
            // where the inner value is empty
            ParsedValue::Null => visitor.visit_some(QsDeserializer::from_value(
                ParsedValue::NoValue,
                self.config,
            )),
            _ => visitor.visit_some(self),
        }
    }

    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        // we'll tolerate `x=` as a unit value
        if matches!(self.value, ParsedValue::Null)
            || matches!(self.value, ParsedValue::String(ref s) if s.is_empty())
        {
            visitor.visit_unit()
        } else {
            self.deserialize_any(visitor)
        }
    }

    fn deserialize_unit_struct<V>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> std::result::Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        self.deserialize_unit(visitor)
    }

    fn deserialize_enum<V>(
        self,
        _name: &'static str,
        _variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        match self.value {
            ParsedValue::Map(mut parsed) => visitor.visit_enum(MapDeserializer {
                parsed: &mut parsed,
                field_order: None,
                popped_value: None,
                config: self.config,
            }),
            ParsedValue::String(s) => visitor.visit_enum(StringParsingDeserializer::new(s)?),
            _ => self.deserialize_any(visitor),
        }
    }

    /// given the hint that this is a map, will first
    /// attempt to deserialize ordered sequences into a map
    /// otherwise, follows the any code path
    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        match self.value {
            ParsedValue::Map(mut parsed) => visitor.visit_map(MapDeserializer {
                parsed: &mut parsed,
                field_order: None,
                popped_value: None,
                config: self.config,
            }),
            ParsedValue::Null | ParsedValue::NoValue => {
                let mut empty_map = parse::ParsedMap::default();
                visitor.visit_map(MapDeserializer {
                    parsed: &mut empty_map,
                    field_order: None,
                    popped_value: None,
                    config: self.config,
                })
            }
            ParsedValue::String(s) => {
                // if we have a single string key, but expect a map
                // we'll treat it as a map with one key
                // this is for cases like `=foo` which we are currently using
                // to represent flat data structures.
                //
                // This is not a great way to handle this. Would be preferable
                // if simple String primitives has a different representation
                let mut parsed = parse::ParsedMap::default();
                parsed.insert(Key::String(Cow::Borrowed(b"")), ParsedValue::String(s));
                visitor.visit_map(MapDeserializer {
                    parsed: &mut parsed,
                    field_order: None,
                    popped_value: None,
                    config: self.config,
                })
            }
            _ => self.deserialize_any(visitor),
        }
    }

    fn deserialize_str<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        let s = match self.value {
            ParsedValue::String(s) => s,
            ParsedValue::Sequence(mut seq) => match get_last_string_value(&mut seq, self.config) {
                Ok(Some(v)) => v,
                Ok(None) => {
                    return Self::from_value(ParsedValue::Sequence(seq), self.config)
                        .deserialize_any(visitor);
                }
                Err(e) => return Err(e),
            },
            ParsedValue::Null | ParsedValue::NoValue => {
                return visitor.visit_str("");
            }
            _ => return self.deserialize_any(visitor),
        };

        match string_parser::decode_utf8(s)? {
            Cow::Borrowed(string) => visitor.visit_borrowed_str(string),
            Cow::Owned(string) => visitor.visit_string(string),
        }
    }

    fn deserialize_string<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        self.deserialize_str(visitor)
    }

    fn deserialize_bytes<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        let s = match self.value {
            ParsedValue::String(s) => s,
            ParsedValue::Sequence(mut seq) => match get_last_string_value(&mut seq, self.config) {
                Ok(Some(v)) => v,
                Ok(None) => {
                    return Self::from_value(ParsedValue::Sequence(seq), self.config)
                        .deserialize_any(visitor);
                }
                Err(e) => return Err(e),
            },
            ParsedValue::Null | ParsedValue::NoValue => {
                return visitor.visit_bytes(&[]);
            }
            _ => return self.deserialize_any(visitor),
        };
        match s {
            Cow::Borrowed(s) => visitor.visit_borrowed_bytes(s),
            Cow::Owned(s) => visitor.visit_byte_buf(s),
        }
    }

    fn deserialize_byte_buf<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        self.deserialize_bytes(visitor)
    }

    fn deserialize_ignored_any<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        match self.value {
            // for ignored values, we wont attempt to parse the value
            // as a UTF8 string, but rather just pass the bytes along.
            // since the value is ignored anyway, this is great since
            // we'll just drop it and avoid raising UTF8 errors.
            ParsedValue::String(cow) => match cow {
                Cow::Borrowed(s) => visitor.visit_borrowed_bytes(s),
                Cow::Owned(s) => visitor.visit_byte_buf(s),
            },
            _ => self.deserialize_any(visitor),
        }
    }

    fn deserialize_bool<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        match self.value {
            ParsedValue::String(s) => {
                let deserializer = StringParsingDeserializer::new(s)?;
                deserializer.deserialize_bool(visitor)
            }
            ParsedValue::Sequence(mut seq) => {
                match get_last_string_value(&mut seq, self.config) {
                    Ok(Some(last_value)) => {
                        StringParsingDeserializer::new(last_value)?.deserialize_bool(visitor)
                    }
                    Ok(None) => {
                        // if we have a sequence, but the last value is not a string,
                        // we'll just forward to deserialize_any
                        Self::from_value(ParsedValue::Sequence(seq), self.config)
                            .deserialize_any(visitor)
                    }
                    Err(e) => Err(e),
                }
            }
            // if the field is _present_ we'll treat it as a boolean true
            ParsedValue::Null | ParsedValue::NoValue => visitor.visit_bool(true),
            _ => self.deserialize_any(visitor),
        }
    }

    forward_to_deserialize_any! {
        char
        identifier
    }

    forward_to_string_parser! {
        u8 => deserialize_u8,
        u16 => deserialize_u16,
        u32 => deserialize_u32,
        u64 => deserialize_u64,
        i8 => deserialize_i8,
        i16 => deserialize_i16,
        i32 => deserialize_i32,
        i64 => deserialize_i64,
        f32 => deserialize_f32,
        f64 => deserialize_f64,
    }
}