serde-rs / serde

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

Conditional selection of (De-)Serializer #2741

Open Ruhrpottpatriot opened 1 month ago

Ruhrpottpatriot commented 1 month ago

tl;dr: Is there a way to conditionally select which (de-)serialization function is used. Alternatively is there a way to pass parameters to the deserialization function during runtime?

I have the case where I receive a json string over the wire that contains Base64 encoded binary data. I can deserialize and serialize the data with no problems using serde and binrw. This is what I need as I have to send the data further along the wire and the target expects the data as the same Base64 encoded string. So basically I'm decoding the data, change the required values and then encode it and send it further along.

However, I also want to write the deserialized values to disk for logging. Since the logs have to be searchable, I can't just write the encoded representation back to disk and instead I want to write the contents of the data in plaintext as if I didn't have a custom serialization routine. Currently I'm using a second, almost identical, struct that doesn't have the custom serialization routine and I'm doing a manual conversion in the places where I have to handle/write the message to disk.

So my question would be: Can I either change the serialization method on the fly so that I can use an if statement to select the serializer. Alternatively, is there a way to pass parameters to the serialization method, so that I can handle my two cases inside the serialization method itself?

Thanks in advance.