Hephaestus
Hephaestus

Reputation: 5113

Protobuf: how to rewrite a file

I'm using Protobuf3 as a file format. The PB API works great for serialization and deserialization. However I now want do a roundtrip: write a file, read it back, modify one field and rewrite the file back to storage.

In more detail: when creating a PB object, one first instantiates a Builder object, sets the field values in the object, and then Builds the binary object. However, after writing and reading back the binary object, how does one modify a field? One has to use a Builder object to generate the binary, but does one have to copy all the existing fields back into the Builder? Or does the Builder automatically populate itself from the binary form?

Ideally, I could load the binary, create a new builder, set the field that I wanted and expect both the original and new data to be merged together.

What is best practice?

Upvotes: 1

Views: 1127

Answers (1)

bazza
bazza

Reputation: 8434

When you deserialise you end up with an object that has fields set. You can modify these fields any which way you like. You can then serialise that object and write the new byte stream to a file.

You do not need to make a copy of the deserialised object to do this (however GPB implementations generally have a copy constructor if you wish to make a copy).

What you cannot do is edit the file in place; you have to completely rewrite the file. You have no sensible way of knowing what part of the byte stream has changed. It may have become longer, shorter, and the content itself will be different in any case (because you’ve changed fields in the object).

Upvotes: 1

Related Questions