Is there an easy way to have one struct that encodes Vec<u8> or &[u8] differently depending on the used (de)serializer, e.g., serde_json or serde_cbor?
The following example unfortunately doesn't work in rust playground (missing serde_cbor and serde_bytes crates):
You could make the case distinction based in the is_human_readable information that the Serializer and Deserializer provide. Use base a base 64 string for human readable and ordinary bytes sequence encoding for non-human-readable.
Thank you for the proposed solutions, is_human_readable seems like a viable solution at least for my use-case.
serde_bytes does work with Vec<u8> as well as with &'a [u8].
I'm struggling a bit to make either variant work with deserializing into structs containing &'a [u8].
Let alone having it work with both at the same time.
No matter what I do I'm always trying to return a reference to data owned by the current function.
I guess the problem is the call to base64::decode which allocates a new Vec<u8>.
But switching to base64::decode_config_slice also does not seem to be what I'm looking for.
Just doing the serde_bytes deserialization works with references just fine.