0

I'm converting some code that formerly wrote structs directly into storage, to use serialization. This is because it is pretty annoying having piles of code to unpack structs that were laid out differently in older versions of the code that have been upgraded.

At this stage I am hand-writing the serialization code, I'm not looking for automated serialization.

Pseudocode:

 struct S
 {
      int x;
      char ch; 
      short d;  
      struct { char a,b,c; } t;
 };

 void serialize_S(struct S const *s);   // ignore details about serialization buffer for now

Supposing I have written serialize_S correctly. The problem I am concerned about is that someone may add a field to struct S without updating the serialization function (and without updating any test suite). We may think the new field is being serialized when it isn't.

My question is: Is there anything I can do to generate a compilation error if a field exists in the struct but is not mentioned in the serialization function?

If necessary, the solution could require extra tags or something in the struct definition -- I am prepared to trust that if people are editing the struct definition and see something like a macro SERIALIZE_ME on the end of each field, they'll realize to add it to the other fields too (or at least, I'd catch this looking at diffs on code review).

1 Answer 1

5

I am hand-writing the serialization code, I'm not looking for automated serialization.

But that is exactly the point where you can solve your problem - create a code generator for the serialization code, which takes a meta description from a file (for example, an XML file) and generates the structs as well as the serialization code from this single source. Where needed, let the code generator provide some extension points for manually written code.

Another approach might be a size check in a generic unit test, but this depends heavily on the details of the serialization. If sizeof(S) should match the length of a binary string produced inside serialize_S function, factor this binary string creation out into a separate function and create a test which compares the two size values. When S is extended afterwards, but not the serialization code, this test will fail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.