Skip to content

Commit

Permalink
Merge pull request #612 from epage/key
Browse files Browse the repository at this point in the history
fix(serde): Allow newtypes for keys
  • Loading branch information
epage authored Sep 26, 2023
2 parents cb3eed5 + a376cfd commit d3df1cf
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
19 changes: 19 additions & 0 deletions crates/toml/tests/testsuite/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -742,6 +742,25 @@ fn newtype_variant() {
}
}

#[test]
fn newtype_key() {
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Serialize, Deserialize)]
struct NewType(String);

type CustomKeyMap = std::collections::BTreeMap<NewType, u32>;

equivalent! {
[
(NewType("x".to_owned()), 1),
(NewType("y".to_owned()), 2),
].into_iter().collect::<CustomKeyMap>(),
map! {
x: Value::Integer(1),
y: Value::Integer(2)
},
}
}

#[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
struct CanBeEmpty {
a: Option<String>,
Expand Down
13 changes: 12 additions & 1 deletion crates/toml_edit/src/de/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,20 @@ impl<'de> serde::de::Deserializer<'de> for KeyDeserializer {
self.deserialize_any(visitor)
}

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

serde::forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq
bytes byte_buf map option unit newtype_struct
bytes byte_buf map option unit
ignored_any unit_struct tuple_struct tuple identifier
}
}
Expand Down

0 comments on commit d3df1cf

Please sign in to comment.