8000 Fix maps with integer keys. by samscott89 · Pull Request #138 · samscott89/serde_qs · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Fix maps with integer keys. #138

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 20 additions & 15 deletions src/de/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ use std::iter::Iterator;
use std::slice::Iter;
use std::{fmt, str};

use serde::de::IntoDeserializer;

use crate::error::{Error, Result};
use crate::map::{Entry, Map};

Expand All @@ -25,12 +23,31 @@ pub enum Key<'a> {
String(Cow<'a, [u8]>),
}

impl Key<'_> {
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<'_> {
Expand Down Expand Up @@ -66,18 +83,6 @@ impl From<u32> for Key<'_> {
}
}

impl<'a> Key<'a> {
pub fn deserialize_seed<T>(self, seed: T) -> Result<T::Value>
where
T: serde::de::DeserializeSeed<'a>,
{
match self {
Key::Int(i) => seed.deserialize(i.into_deserializer()),
Key::String(s) => seed.deserialize(StringParsingDeserializer::new(s)?),
}
}
}

/// An intermediate representation of the parsed query string.
///
/// This enum represents the different types of values that can appear in a querystring.
Expand Down
85 changes: 70 additions & 15 deletions tests/test_deserialize.rs
8000 86B4
Original file line number Diff line number Diff line change
Expand Up @@ -1360,19 +1360,74 @@ fn empty_keys() {
&HashMap::<String, String>::from([("".to_string(), "foo".to_string())]),
);

// #[derive(Debug, Serialize, Deserialize, PartialEq)]
// struct Query {
// a: String,
// b: String,
// }

// // empty keys are not allowed
// deserialize_test_err::<Query>("=1&b=2", "invalid input: empty key");
// deserialize_test_err::<Query>("a=1&=2", "invalid input: empty key");

// // but we can have empty values
// deserialize_test("a=&b=2", &Query {
// a: "".to_string(),
// b: "2".to_string(),
// });
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Query {
a: String,
b: String,
}

// empty keys are not allowed
deserialize_test_err::<Query>(
"=1&b=2",
"invalid input: the same key is used for both a value and a nested ma",
);

// but we can have empty values
deserialize_test(
"a=&b=2",
&Query {
a: "".to_string(),
b: "2".to_string(),
},
);
}

#[test]
fn int_key_parsing() {
#[derive(Debug, Deserialize, PartialEq)]
struct Query<K: std::hash::Hash + Eq> {
a: HashMap<K, u32>,
}

// Test that we can parse integer keys correctly
deserialize_test(
"a[1]=2&a[3]=4",
&Query {
a: HashMap::from([(1, 2), (3, 4)]),
},
);

// errors if numbers are too larger
deserialize_test_err::<Query<u8>>("a[1000]=2", "number too large to fit in target type");

// Test that we can parse integer keys with leading zeros
deserialize_test(
"a[01]=2&a[03]=4",
&Query {
a: HashMap::from([(1, 2), (3, 4)]),
},
);

// if we use a string key, it should still work
// although we lose the leading zeros unfortunately
deserialize_test(
"a[01]=2&a[03]=4",
&Query {
a: HashMap::from([("1".to_string(), 2), ("3".to_string(), 4)]),
},
);

#[derive(Debug, Deserialize, PartialEq)]
struct VecQuery<K: std::hash::Hash + Eq> {
a: Vec<K>,
}

// Test that we can parse integer keys in a vector
deserialize_test("a[0]=1&a[1]=2", &VecQuery { a: vec![1, 2] });

// but if we use a string key, it will error
deserialize_test_err::<VecQuery<String>>(
"a[x]=1&a[0]=2",
"expected an integer index, found a string key `x`",
);
}
0