Jamona Mican
Jamona Mican

Reputation: 1654

Is it possible to hook into the protobuf-net serializer to add some custom logic?

This may be overkill, but I am trying to reduce the network consumption of a client/server protocol, by having both sides keep copies of previously transferred URIs, so as to use 2-4 byte placeholders instead of the full URIs on subsequent chatter.

Problem is I think it will be quite expensive to reflect through all the complex objects being transferred to locate the URIs that need processing, whereas the serializer is already visiting all these fields and probably using a mechanism much faster than reflection.

Can this be done in protobuf-net?

Upvotes: 1

Views: 597

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1064114

If this is part of a single call to Serialize/Deserialize (i.e. your data has the same uri repeated at multiple locations), then you can already do this, simply by telling it to treat those strings as references (it has special handling of strings, so two different references of the same string contents count as equal):

[ProtoMember(7, AsReference=true)]
public string Uri {get;set;}

During serialization, the first time it spots a new string value (decorated with AsReference=true) it will generate a unique token to represent the string; all subsequent usages of that same string will serialize only the token.

If this is in separate calls to Serialize/Deserialize, then no: you would have to do it manually. I can think of some ways of doing it, but I think this would be better handled outside of the serialization layer.

Upvotes: 2

Paul Farry
Paul Farry

Reputation: 4768

Could you possibly customise the Objects that you are using that you want to Tokenise your URIs and have them inherit or implement an interface that you can check to see if that particular object is a Tokenizer.

Then if that's the case you might be able to use the BeforeSerialization / AfterDeserialization to make your transformations.

Upvotes: 1

Related Questions