#Generalize over multiple serde data formats.

4 messages · Page 1 of 1 (latest)

barren cave
#

I'm looking for an example which generalizes over multiple serde data formats. For example maybe accept a Serializer generic parameter somewhere.

However each of these Serializers require different things for being built.

I guess I'm asking for advice on how to design this.

What I'm trying to achieve: write code parameterized with serde data format, so that the invoker can use postcard or bincode or any other format they desire.

sinful wigeon
# barren cave I'm looking for an example which generalizes over multiple serde data formats. F...

The fact that serializers need different inputs to be built should not be a problem: Just accept a S: Serializer, then pass it to the type's serialize method as-is. Or in other words, constructing the serializer is your caller's problem.

The slightly more annoying part is that there is no general-purpose way to "extract" serialized data from a serializer, but if you're ok with making that the caller's problem as well, that should be fine. To be maximally versatile, you should also ensure that you return the return value of serialize, (at least the Ok variant) to the caller.

#

(I expect most serializers would wrap a reference to a buffer they're writing to, but just in case they instead prefer to return by value, that value will be in the Ok)

#

If you'd rather manage the serializer yourself, then you'll need to

  • create a custom trait, say, BuildSerializer
  • implement it for all the serializer types you want to support
  • use that trait both to have methods to construct the serializer and to have methods to extract the serialized data.