serde-rs / serde

Serialization framework for Rust
https://serde.rs/
Apache License 2.0
9.06k stars 767 forks source link

Allow generic keys for serialization and deserialization #2695

Open jrandolf opened 7 months ago

jrandolf commented 7 months ago

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(()).

sosthene-nitrokey commented 7 months ago

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

jrandolf commented 7 months ago

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.

sosthene-nitrokey commented 7 months ago

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.