Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow generic keys for serialization and deserialization #2695

Open
jun-sheaf opened this issue Feb 12, 2024 · 3 comments · May be fixed by #2698
Open

Allow generic keys for serialization and deserialization #2695

jun-sheaf opened this issue Feb 12, 2024 · 3 comments · May be fixed by #2698

Comments

@jun-sheaf
Copy link

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

@jun-sheaf jun-sheaf changed the title Allow generic keys for serialization. Allow generic keys for serialization and deserialization Feb 12, 2024
@jun-sheaf jun-sheaf linked a pull request Feb 13, 2024 that will close this issue
@sosthene-nitrokey
Copy link

Why #[serde(key = )] and not just extending #[serde(rename = …)] like #2209?

@jun-sheaf
Copy link
Author

Why #[serde(key = )] and not just extending #[serde(rename = …)] like #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
Copy link

One reason in favor of rename for integer keys is for enums, where even in JSON an integer or a boolean can work: #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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging a pull request may close this issue.

2 participants