serde icon indicating copy to clipboard operation
serde copied to clipboard

Allow generic keys for serialization and deserialization

Open jrandolf opened this issue 1 year ago • 3 comments

Some data formats (such as CBOR and Protobuf) use types other than strings for keys. Currently, serde only allows struct serialization to contain string values for keys which prohibits this use case.

Scope

We are only attempting to solve this problem for homogeneous keys.

Proposed Solution

Other than adding an attribute (e.g. key = 1), the main concern comes from the signature of SerializeStruct::serialize_field which doesn't allow generics. Deserialization is trivial as it already uses MapAccess for deserializing which takes generics.

The solution we propose is adding the following methods to the SerializeMap trait:

fn serialize_key<T>(&mut self, key: &T) -> Result<(), Self::Error> 
  where T: Serialize + ?Sized;
fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
  where T: Serialize + ?Sized;

To make this non-breaking, the default implementation would just return Ok(()).

jrandolf avatar Feb 12 '24 03:02 jrandolf

Why #[serde(key = )] and not just extending #[serde(rename = …)] like https://github.com/serde-rs/serde/pull/2209?

sosthene-nitrokey avatar Mar 04 '24 08:03 sosthene-nitrokey

Why #[serde(key = )] and not just extending #[serde(rename = …)] like https://github.com/serde-rs/serde/pull/2209?

Good question! Perhaps because I didn't see that PR :D

It's probably better to use a new key though because it's often the case that self-describing formats still want the string key over the binary key. This wasn't implemented in my implementation, but it was something I came across while production testing this feature.

jrandolf avatar Mar 04 '24 15:03 jrandolf

One reason in favor of rename for integer keys is for enums, where even in JSON an integer or a boolean can work: https://github.com/serde-rs/serde/pull/2525

The advantage of using rename is that the interaction with alias is also pretty easy to understand (assuming that alias also supports non-string datatypes).

Anyway this is would be a great feature to have.

sosthene-nitrokey avatar Mar 04 '24 15:03 sosthene-nitrokey