serde icon indicating copy to clipboard operation
serde copied to clipboard

Name equality checking with `#[serde(name_eq = "..")]`

Open avitex opened this issue 3 years ago • 2 comments

I put this forward as an alternative to #1902 allowing for a generic method of checking a field name on deserialization over a specific implementation tied to ASCII.

The provided name_eq container attribute can be be used for case-insensitivity.

// Note in this example we use ASCII case-insensitivity,
// but we could just as well use unicode case-insensitivity.
//
// We require `value` to be a byte slice as the deserializer
// may or may not provide us validated UTF-8.
fn eq_ignore_case(name: &str, value: &[u8]) -> bool {
    name.as_bytes().eq_ignore_ascii_case(other)
}

#[derive(Deserialize)]
#[serde(name_eq = "eq_ignore_case")]
pub struct Foo {
    // ..
}

Notes

  • NameEq/name_eq might not be the best name for this, but I wanted to put forward this initial implementation before bikeshedding.
  • I have not implemented this also as a field attribute but I see no reason that could not be the case in a future PR.

avitex avatar Jan 22 '22 13:01 avitex

Now that I think about it, perhaps alias_with/alias_all_with could be a better name inline with deserialize_with and alias which is a loose idea of what this functionality actually provides.

#[derive(Deserialize)]
#[serde(alias_all_with = "case_insensitive")]
pub struct Foo {
    // ..
}

This could also provide a method of solving #1530

avitex avatar Jan 22 '22 14:01 avitex

@dtolnay Any thoughts on the initial implementation or comments?

avitex avatar Mar 21 '22 08:03 avitex

Case insensitive keys is exactly what I've been looking for. It would be really great to get this merged if all is fine.

0cv avatar Jan 22 '23 17:01 0cv