Skip to content
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

Support deserializing map key as &RawValue #851

Merged
merged 2 commits into from Jan 22, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Expand Up @@ -20,6 +20,7 @@ ryu = "1.0"

[dev-dependencies]
automod = "1.0"
ref-cast = "1.0"
rustversion = "1.0"
serde_bytes = "0.11"
serde_derive = "1.0"
Expand Down
10 changes: 9 additions & 1 deletion src/de.rs
Expand Up @@ -2184,10 +2184,18 @@ where
}

#[inline]
fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
fn deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
#[cfg(feature = "raw_value")]
{
if name == crate::raw::TOKEN {
return self.de.deserialize_raw_value(visitor);
}
}

let _ = name;
visitor.visit_newtype_struct(self)
}

Expand Down
40 changes: 40 additions & 0 deletions tests/test.rs
Expand Up @@ -2193,6 +2193,46 @@ fn test_borrowed_raw_value() {
assert_eq!(r#"["a",42,{"foo": "bar"},null]"#, array_to_string);
}

#[cfg(feature = "raw_value")]
#[test]
fn test_raw_value_in_map_key() {
use ref_cast::RefCast;

#[derive(RefCast)]
#[repr(transparent)]
struct RawMapKey(RawValue);

impl<'de> Deserialize<'de> for &'de RawMapKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let raw_value = <&RawValue>::deserialize(deserializer)?;
Ok(RawMapKey::ref_cast(raw_value))
}
}

impl PartialEq for RawMapKey {
fn eq(&self, other: &Self) -> bool {
self.0.get() == other.0.get()
}
}

impl Eq for RawMapKey {}

impl Hash for RawMapKey {
fn hash<H: Hasher>(&self, hasher: &mut H) {
self.0.get().hash(hasher);
}
}

let map_from_str: std::collections::HashMap<&RawMapKey, &RawValue> =
serde_json::from_str(r#" {"\\k":"\\v"} "#).unwrap();
let (map_k, map_v) = map_from_str.into_iter().next().unwrap();
assert_eq!("\"\\\\k\"", map_k.0.get());
assert_eq!("\"\\\\v\"", map_v.get());
}

#[cfg(feature = "raw_value")]
#[test]
fn test_boxed_raw_value() {
Expand Down