Skip to content

Commit

Permalink
Add test of deserializing a &RawValue in map key position
Browse files Browse the repository at this point in the history
Currently fails with:

    ---- test_raw_value_in_map_key stdout ----
    thread 'test_borrowed_raw_value' panicked at 'called `Result::unwrap()`
    on an `Err` value: Error("invalid type: newtype struct, expected any
    valid JSON value", line: 1, column: 2)', tests/test.rs:2230:52
  • Loading branch information
dtolnay committed Jan 22, 2022
1 parent d8512af commit 6a3fb68
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
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
40 changes: 40 additions & 0 deletions tests/test.rs
Original file line number Diff line number Diff line change
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

0 comments on commit 6a3fb68

Please sign in to comment.