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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
use std::borrow::Cow;
use std::iter::Iterator;
use std::slice::Iter;
use std::{fmt, str};
use crate::error::{Error, Result};
use crate::map::{Entry, Map};
use super::string_parser::StringParsingDeserializer;
pub type ParsedMap<'qs> = Map<Key<'qs>, ParsedValue<'qs>>;
mod decode;
/// Represents a key in the parsed querystring.
///
/// Keys can be either integers (for array indices) or strings (for object keys).
/// This allows the parser to handle both `items[0]=foo` (integer key) and
/// `user[name]=bar` (string key) notations.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Key<'a> {
Int(u32),
String(Cow<'a, [u8]>),
}
impl<'a> Key<'a> {
/// In some cases, we would rather push an empty key
/// (e.g. if we have `foo=1&=2`, then we'll have a map `{ "foo": 1, "": 2 }`).
fn empty_key() -> Self {
Key::String(Cow::Borrowed(b""))
}
pub fn deserialize_seed<T>(self, seed: T) -> Result<T::Value>
where
T: serde::de::DeserializeSeed<'a>,
{
let s = match self {
// if the key is an integer, we'll convert it to a string
// before deserializing
// this is a _little_ wasteful in the case of maps
// with integer keys,
// but the tradeoff is that we can use the same deserializer
Key::Int(i) => {
let mut buffer = itoa::Buffer::new();
Cow::Owned(buffer.format(i).as_bytes().to_owned())
}
Key::String(s) => s,
};
seed.deserialize(StringParsingDeserializer::new(s)?)
}
}
impl fmt::Debug for Key<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}
impl fmt::Display for Key<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Key::Int(i) => write!(f, "{i}"),
Key::String(s) => write!(f, "\"{}\"", String::from_utf8_lossy(s)),
}
}
}
impl<'a> From<&'a str> for Key<'a> {
fn from(s: &'a str) -> Self {
Self::from(s.as_bytes())
}
}
impl<'a> From<&'a [u8]> for Key<'a> {
fn from(s: &'a [u8]) -> Self {
Key::String(Cow::Borrowed(s))
}
}
impl From<u32> for Key<'_> {
fn from(i: u32) -> Self {
Key::Int(i)
}
}
/// An intermediate representation of the parsed query string.
///
/// This enum represents the different types of values that can appear in a querystring.
/// The parser builds a tree of these values before the final deserialization step.
///
/// - `Map`: Nested objects like `user[name]=John&user[age]=30`
/// - `Sequence`: Arrays like `ids[0]=1&ids[1]=2`
/// - `String`: Leaf values containing the actual data
/// - `Null`: Empty values like `key=` or standalone keys like `flag`
/// - `Uninitialized`: Used internally during parsing for placeholder values
#[derive(PartialEq)]
pub enum ParsedValue<'qs> {
Map(ParsedMap<'qs>),
Sequence(Vec<ParsedValue<'qs>>),
String(Cow<'qs, [u8]>),
/// Null value means we have a key with an _empty_ value string
/// e.g. `"key"=`
Null,
/// NoValue means we have a key with no value at all, e.g. `"key"`
NoValue,
Uninitialized,
}
impl fmt::Debug for ParsedValue<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParsedValue::Map(m) => f.debug_map().entries(m.iter()).finish(),
ParsedValue::Sequence(s) => f.debug_list().entries(s.iter()).finish(),
ParsedValue::String(s) => write!(f, "String({})", String::from_utf8_lossy(s)),
ParsedValue::Null => write!(f, "Null"),
ParsedValue::NoValue => write!(f, "NoValue"),
ParsedValue::Uninitialized => write!(f, "Uninitialized"),
}
}
}
pub fn parse(encoded_string: &[u8], config: crate::Config) -> Result<ParsedValue<'_>> {
let mut parser = Parser::new(encoded_string, config);
let mut output = ParsedValue::Uninitialized;
parser.parse(&mut output)?;
#[cfg(feature = "debug_parsed")]
println!("[DEBUG] parsed: {output:#?}");
Ok(output)
}
/// The `Parser` struct is a stateful querystring parser.
///
/// It iterates over a slice of bytes, maintaining an accumulator range `(start, end)`
/// to track the current segment being parsed. This approach avoids allocations
/// by working directly with slices of the input string.
///
/// The parser handles bracket notation for nested structures and supports both
/// query-string encoding and form encoding modes.
struct Parser<'qs> {
inner: &'qs [u8],
iter: Iter<'qs, u8>,
index: usize,
acc: (usize, usize),
config: crate::Config,
}
impl Parser<'_> {
fn next(&mut self) -> Option<u8> {
self.acc.1 = self.index;
self.index += 1;
let mut next = self.iter.next().copied();
if self.config.use_form_encoding {
// in formencoding mode, we will eagerly decode any
// percent-encoded brackets
if matches!(next, Some(b'%')) {
let iter = self.iter.as_slice();
if iter.len() >= 2 {
match &self.iter.as_slice()[..2] {
b"5B" => {
// skip the next two characters
let _ = self.iter.next();
let _ = self.iter.next();
self.index += 2;
next = Some(b'[');
}
b"5D" => {
// skip the next two characters
let _ = self.iter.next();
let _ = self.iter.next();
self.index += 2;
next = Some(b']');
}
_ => {
// unknown percent encoding, leave it as is
}
}
}
}
}
next
}
}
impl<'qs> Parser<'qs> {
pub fn new(encoded: &'qs [u8], config: crate::Config) -> Self {
Parser {
inner: encoded,
iter: encoded.iter(),
acc: (0, 0),
index: 0,
config,
}
}
/// Resets the accumulator range by setting `(start, end)` to `(end, end)`.
fn clear_acc(&mut self) {
self.acc = (self.index, self.index);
}
/// Extracts a string from the internal byte slice from the range tracked by
/// the parser.
/// Avoids allocations when neither percent encoded, nor `'+'` values are
/// present.
fn collect_key(&mut self) -> Result<Option<Key<'qs>>> {
if self.acc.0 == self.acc.1 {
// no bytes to parse
return Ok(None);
}
let bytes = &self.inner[self.acc.0..self.acc.1];
if bytes.iter().all(|b| b.is_ascii_digit()) {
// if all bytes are digits, we can parse it as an integer
// SAFETY: we know that all bytes are ASCII digits
let key = unsafe { std::str::from_utf8_unchecked(bytes) };
if let Ok(key) = key.parse() {
self.clear_acc();
return Ok(Some(Key::Int(key)));
}
// if this fails, we'll just fall back to the string case
}
let string_key = Key::String(decode::decode(bytes));
self.clear_acc();
Ok(Some(string_key))
}
/// Extracts a string from the internal byte slice from the range tracked by
/// the parser.
/// Avoids allocations when neither percent encoded, nor `'+'` values are
/// present.
fn collect_value(&mut self) -> Result<ParsedValue<'qs>> {
// clear the accumulator to start fresh
self.clear_acc();
while !matches!(self.next(), None | Some(b'&')) {
// eat bytes up until the next '&' (or end of string) as the value
}
if self.acc.0 == self.acc.1 {
// no bytes to parse
return Ok(ParsedValue::Null);
}
let decoded = decode::decode(&self.inner[self.acc.0..self.acc.1]);
self.clear_acc();
Ok(ParsedValue::String(decoded))
}
/// Main parsing entry point that processes the querystring into a map structure.
///
/// This function handles the top-level parsing logic, identifying key-value pairs
/// and delegating to specialized parsing functions for nested structures.
/// It processes the input byte-by-byte, handling special characters like
/// `&` (pair separator), `=` (key-value separator), and `[`/`]` (nesting).
fn parse(&mut self, root: &mut ParsedValue<'qs>) -> Result<()> {
if self.inner.is_empty() {
// empty string -- nothing to parse
*root = ParsedValue::NoValue;
return Ok(());
}
let no_nesting = self.config.max_depth == 0;
loop {
let Some(x) = self.next() else {
// we reached the end of the string
if let Some(key) = self.collect_key()? {
// we have a single lone key
// which we'll treat as a key with no value
let root_map: &mut Map<Key<'_>, ParsedValue<'_>> =
expect_map(root, self.index)?;
self.insert_unique(root_map, key, ParsedValue::NoValue)?;
}
// we've finished parsing the string
return Ok(());
};
// process root key
match x {
b'&' => {
// we have a simple key with no value
// insert an empty node and continue
if let Some(key) = self.collect_key()? {
// if we have no key, we'll skip it entirely to avoid creating empty
// key, value pairs
let root_map: &mut Map<Key<'_>, ParsedValue<'_>> =
expect_map(root, self.index)?;
self.insert_unique(root_map, key, ParsedValue::NoValue)?;
}
}
b'=' => {
// we have a simple key with a value
// parse the value and insert it into the map
// if they key is empty, since we have an explicit `=` we'll use
// an empty key
let maybe_key = self.collect_key()?;
let value = self.collect_value()?;
if let Some(key) = maybe_key {
let root_map = expect_map(root, self.index)?;
self.insert_unique(root_map, key, value)?;
} else {
self.append_value(root, value)?;
}
}
b'[' if !no_nesting => {
// we have a nested key
// first get the first segment of the key
// and parse the rest of the key
let key_start = self.acc.0;
let node = if let Some(root_key) = self.collect_key()? {
let root_map = expect_map(root, self.index)?;
root_map
.entry(root_key)
.or_insert(ParsedValue::Uninitialized)
} else {
&mut *root
};
// parse the key and insert it into the map
self.parse_nested_key(node, 0, key_start)?;
}
_ => {
// for any other character
// do nothing, keep accumulating the key
continue;
}
}
// if we reached here we pushed a new value -- clear the accumulator
self.clear_acc();
}
}
fn parse_nested_key(
&mut self,
current_node: &mut ParsedValue<'qs>,
depth: usize,
input_start: usize,
) -> Result<()> {
let reached_max_depth = depth >= self.config.max_depth;
if !reached_max_depth {
// if we haven't reached the maximum depth yet, we can clear the accumulator
// otherwise, we want to keep the accumulated `[` character
self.clear_acc();
}
let Some(first_byte) = self.next() else {
return Err(super::Error::parse_err(
"query string ended before expected",
self.index,
));
};
if first_byte == b']' {
// empty key (e.g. "[]") -- parse as a sequence
match current_node {
ParsedValue::Sequence(seq) => {
self.parse_sequence_value(seq)?;
}
ParsedValue::Uninitialized => {
// initialize this node as a sequence
let mut seq = vec![];
self.parse_sequence_value(&mut seq)?;
*current_node = ParsedValue::Sequence(seq);
}
ParsedValue::Map(map) => {
let full_key = &self.inner[input_start..self.acc.0 - 1];
let key = std::str::from_utf8(full_key).unwrap_or("<invalid key>");
return Err(super::Error::parse_err(
format!(
"invalid input: the key `{key}` appears in the input as both a sequence and a map (with keys {})",
map.keys()
.map(|k| k.to_string())
.collect::<Vec<_>>()
.join(", ")
),
self.index,
));
}
ParsedValue::String(_) | ParsedValue::Null | ParsedValue::NoValue => {
return Err(super::Error::parse_err(
"invalid input: the same key is used for both a value and a sequence",
self.index,
));
}
}
} else {
// otherwise we have a key
// and this entry _must_ be a map
let map = expect_map(current_node, self.index)?;
if reached_max_depth {
// if we've reached the maximum depth already, we'll just parse the entire
// key as a string and insert it into the map
loop {
let Some(b) = self.next() else {
// we've reached the end of the string
// without encountering a terminating value (e.g. `=` or `&`)
let key = self.collect_key()?.expect("key cannot be empty");
self.insert_unique(map, key, ParsedValue::NoValue)?;
return Ok(());
};
match b {
b'&' => {
// no value
let key = self.collect_key()?.expect("key cannot be empty");
self.insert_unique(map, key, ParsedValue::NoValue)?;
}
b'=' => {
// we have a simple key with a value
// parse the value and insert it into the map
let key = self.collect_key()?.expect("key cannot be empty");
let value = self.collect_value()?;
self.insert_unique(map, key, value)?;
}
_ => {
// otherwise, continue parsing the key
continue;
}
}
break;
}
} else {
// parse until the closing bracket
loop {
let Some(b) = self.next() else {
return Err(super::Error::parse_err(
"unexpected end of input while parsing nested key",
self.index,
));
};
if b == b']' {
// finished parsing the key
let segment = self.collect_key()?.expect("key cannot be empty");
// get next byte to determine next step
let Some(x) = self.next() else {
// we reached the end of the string
// without encountering a terminating value (e.g. `=` or `&`)
// nor a nested key (e.g. `[`)
self.insert_unique(map, segment, ParsedValue::NoValue)?;
return Ok(());
};
match x {
b'&' => {
// no value
self.insert_unique(map, segment, ParsedValue::NoValue)?;
}
b'=' => {
// we have a simple key with a value
// parse the value and insert it into the map
let value = self.collect_value()?;
self.insert_unique(map, segment, value)?;
}
b'[' => {
// we have a nested key
let node = map.entry(segment).or_insert(ParsedValue::Uninitialized);
// parse the key and insert it into the map
self.parse_nested_key(node, depth + 1, input_start)?;
}
_ => {
let char = x as char;
return Err(super::Error::parse_err(
format!(
"unexpected character `{char}` while parsing nested key: expected `&`, `=` or `[`"
),
self.index,
));
}
}
break;
}
}
}
}
Ok(())
}
fn insert_unique(
&self,
map: &mut ParsedMap<'qs>,
key: Key<'qs>,
value: ParsedValue<'qs>,
) -> Result<()> {
match map.entry(key) {
Entry::Occupied(mut o) => {
let entry = o.get_mut();
self.append_value(entry, value)?;
}
Entry::Vacant(v) => {
v.insert(value);
}
}
Ok(())
}
/// Appends the parsed `value` onto the existing `entry`, returning an error if
/// this is not a compatible operation.
fn append_value(&self, entry: &mut ParsedValue<'qs>, value: ParsedValue<'qs>) -> Result<()> {
match entry {
ParsedValue::Map(m) => {
// if this is a map, we'll insert the value as a new map entry
// with an empty key
let entry = m
.entry(Key::empty_key())
.or_insert(ParsedValue::Uninitialized);
self.append_value(entry, value)?;
}
ParsedValue::Sequence(parsed_values) => {
// if the value is a sequence, we can just push the new value
parsed_values.push(value);
return Ok(());
}
ParsedValue::String(_) => {
// we'll support multiple values for the same key
// by converting the existing value into a sequence
// and pushing the new value into it
// later we'll handle this case by taking the last value of
// the sequence
let existing = std::mem::replace(entry, ParsedValue::Uninitialized);
let mut seq = vec![existing];
seq.push(value);
*entry = ParsedValue::Sequence(seq);
}
ParsedValue::NoValue | ParsedValue::Null => {
return Err(Error::parse_err(
"Multiple values for the same key".to_string(),
self.index,
));
}
ParsedValue::Uninitialized => {
// initialize it
*entry = value;
}
}
Ok(())
}
fn parse_sequence_value(&mut self, seq: &mut Vec<ParsedValue<'qs>>) -> Result<()> {
match self.next() {
Some(b'=') => {
// Key is finished, parse up until the '&' as the value
let value = self.collect_value()?;
seq.push(value);
}
Some(b'&') => {
// No value
seq.push(ParsedValue::NoValue);
}
Some(b'[') => {
// we cannot handle unindexed sequences of maps
// since we would have parsing ambiguity
// e.g. `abc[][x]=1&abc[][y]=2`
// could either be two entries with `x` and `y` set alternatively
// or a single entry with both set
return Err(super::Error::parse_err(
"unsupported: unable to parse nested maps of unindexed sequences ",
self.index,
));
}
None => {
// The string has ended, so the value is empty.
seq.push(ParsedValue::NoValue);
}
_ => {
return Err(super::Error::parse_err(
"unsupported: cannot mix unindexed sequences `abc[]=...` with indexed sequences `abc[0]=...`",
self.index,
));
}
}
Ok(())
}
}
fn expect_map<'qs, 'a>(
node: &'a mut ParsedValue<'qs>,
position: usize,
) -> Result<&'a mut ParsedMap<'qs>> {
match node {
ParsedValue::Map(map) => Ok(map),
ParsedValue::Uninitialized => {
*node = ParsedValue::Map(Map::default());
if let ParsedValue::Map(ref mut map) = *node {
Ok(map)
} else {
unreachable!()
}
}
ParsedValue::Sequence(_) => Err(super::Error::parse_err(
"invalid input: the same key is used for both a sequence and a nested map",
position,
)),
ParsedValue::String(_) => Err(super::Error::parse_err(
"invalid input: the same key is used for both a value and a nested map",
position,
)),
ParsedValue::NoValue | ParsedValue::Null => Err(super::Error::parse_err(
"invalid input: the same key is used for both a unit value and a nested map",
position,
)),
}
}
#[cfg(test)]
mod test {
use super::{ParsedMap, ParsedValue, parse};
use crate::Config;
use pretty_assertions::assert_eq;
use std::{borrow::Cow, iter::FromIterator};
type Map<'a> = super::ParsedMap<'a>;
static DEFAULT_CONFIG: Config = Config::new().max_depth(10).use_form_encoding(false);
static FORM_ENCODING_CONFIG: Config = Config::new().max_depth(10).use_form_encoding(true);
impl<'a> ParsedValue<'a> {
fn map_from_iter<K, V, I>(iter: I) -> Self
where
K: Into<super::super::Key<'a>>,
V: Into<ParsedValue<'a>>,
I: IntoIterator<Item = (K, V)>,
{
ParsedValue::Map(Map::from_iter(
iter.into_iter().map(|(k, v)| (k.into(), v.into())),
))
}
}
fn map<'a, K, V, I>(iter: I) -> ParsedValue<'a>
where
K: Into<super::super::Key<'a>>,
V: Into<ParsedValue<'a>>,
I: IntoIterator<Item = (K, V)>,
{
ParsedValue::map_from_iter(iter)
}
impl<'a> From<ParsedMap<'a>> for ParsedValue<'a> {
fn from(map: ParsedMap<'a>) -> Self {
ParsedValue::Map(map)
}
}
impl<'a, V: Into<ParsedValue<'a>>> From<Vec<V>> for ParsedValue<'a> {
fn from(vec: Vec<V>) -> Self {
ParsedValue::Sequence(vec.into_iter().map(|v| v.into()).collect())
}
}
impl<'a> From<&'a str> for ParsedValue<'a> {
fn from(s: &'a str) -> Self {
ParsedValue::String(Cow::Borrowed(s.as_bytes()))
}
}
#[test]
fn parse_empty() {
let parsed = parse(b"", DEFAULT_CONFIG).unwrap();
assert_eq!(parsed, ParsedValue::NoValue);
}
#[test]
fn parse_map() {
let parsed = parse(b"abc=def", DEFAULT_CONFIG).unwrap();
assert_eq!(parsed, map([("abc", "def")]));
}
#[test]
fn parse_map_no_value() {
let parsed = parse(b"abc", DEFAULT_CONFIG).unwrap();
assert_eq!(parsed, map([("abc", ParsedValue::NoValue)]));
}
#[test]
fn parse_map_null_value() {
let parsed = parse(b"abc=", DEFAULT_CONFIG).unwrap();
assert_eq!(parsed, map([("abc", ParsedValue::Null)]));
}
#[test]
fn parse_sequence() {
let parsed = parse(b"abc[]=1&abc[]=2", DEFAULT_CONFIG).unwrap();
assert_eq!(
parsed,
// NOTE: we cannot have a top-level sequence since we need a key to group
// the values by
map([("abc", vec!["1", "2"])])
);
}
#[test]
fn parse_ordered_sequence() {
let parsed = parse(b"abc[1]=1&abc[0]=0", DEFAULT_CONFIG).unwrap();
assert_eq!(parsed, map([("abc", map([(1, "1"), (0, "0")]))]));
}
#[test]
fn parse_nested_map() {
let parsed = parse(b"abc[def]=ghi", DEFAULT_CONFIG).unwrap();
assert_eq!(parsed, map([("abc", map([("def", "ghi")]))]));
}
#[test]
fn parse_empty_and_sequence() {
let parse_err = parse(b"abc&abc[]=1", DEFAULT_CONFIG).unwrap_err();
assert!(
parse_err
.to_string()
.contains("invalid input: the same key is used for both a value and a sequence"),
"got: {}",
parse_err
);
}
#[test]
fn parse_many() {
let parsed = parse(b"e[B]&v[V1][x]=12&v[V1][y]=300&u=12", DEFAULT_CONFIG).unwrap();
assert_eq!(
parsed,
map([
("e", map([("B", ParsedValue::NoValue)])),
("u", "12".into()),
("v", map([("V1", map([("x", "12"), ("y", "300")]))])),
])
);
}
#[test]
fn parse_max_depth() {
let parsed = parse(
b"a[b][c][d][e][f][g][h]=i",
Config {
max_depth: 5,
..Default::default()
},
)
.unwrap();
assert_eq!(
parsed,
map([(
"a",
map([(
"b",
map([(
"c",
map([("d", map([("e", map([("f", map([("[g][h]", "i")]))]))]))])
)])
)])
)])
);
}
#[test]
fn parse_formencoded_brackets() {
// encoded in the key
// in non-strict mode, the brackets are eagerly decoded
let parsed = parse(b"abc%5Bdef%5D=ghi", FORM_ENCODING_CONFIG).unwrap();
assert_eq!(parsed, map([("abc", map([("def", "ghi")]))]));
let parsed = parse(b"foo=%5BHello%5D", FORM_ENCODING_CONFIG).unwrap();
assert_eq!(parsed, map([("foo", "[Hello]")]));
}
#[test]
fn parse_encoded_brackets() {
// encoded in the key
// in strict mode, the brackets are not decoded, so we end up with a key containing
// brackets
let parsed = parse(b"abc%5Bdef%5D=ghi", DEFAULT_CONFIG).unwrap();
assert_eq!(parsed, map([("abc[def]", "ghi")]));
// encoded in the value
let parsed = parse(b"foo=%5BHello%5D", DEFAULT_CONFIG).unwrap();
assert_eq!(parsed, map([("foo", "[Hello]")]));
}
#[test]
fn extra_bracket() {
let err = parse(b"vec[[]=1&vec[]=2", DEFAULT_CONFIG).unwrap_err();
// I _think_ this is the best error message we can return in this case
// since `'['` is technically a valid key here (although should never be produced by `serde_qs`)
assert!(
err.to_string()
.contains("invalid input: the key `vec` appears in the input as both a sequence and a map (with keys \"[\")"),
"got: {}",
err
);
let err = parse(b"vec[foo][1][[]=1&vec[foo][1][]=2", DEFAULT_CONFIG).unwrap_err();
assert!(
err.to_string()
.contains("invalid input: the key `vec[foo][1]` appears in the input as both a sequence and a map (with keys \"[\")"),
"got: {}",
err
);
}
#[test]
fn parse_no_key() {
let parsed = parse(b"=foo", DEFAULT_CONFIG).unwrap();
assert_eq!(parsed, ParsedValue::String(Cow::Borrowed(b"foo")));
}
#[test]
fn adjacent_enums() {
let parsed = parse(b"unit[UnitVariant]&newtype[NewtypeVariant]=hello&tuple[TupleVariant][0]=42&tuple[TupleVariant][1]=true&tuple[struct_variant][StructVariant][x]=3.14&tuple[struct_variant][StructVariant][y]=test&tuple[struct_variant][vec_of_enums][0][UnitVariant]&tuple[struct_variant][vec_of_enums][1][NewtypeVariant]=in+vec", DEFAULT_CONFIG).unwrap();
assert_eq!(
parsed,
map([
("unit", map([("UnitVariant", ParsedValue::NoValue)])),
("newtype", map([("NewtypeVariant", "hello")])),
(
"tuple",
map([
("TupleVariant", map([(0, "42"), (1, "true")])),
(
"struct_variant",
map([
("StructVariant", map([("x", "3.14"), ("y", "test")])),
(
"vec_of_enums",
map([
(0, map([("UnitVariant", ParsedValue::NoValue)])),
(1, map([("NewtypeVariant", "in vec")]))
])
)
])
)
])
),
])
)
}
}