In any project, when a function is created for serialization, another function is created for unserialization.
Serialization by contrast uses another approach - a contract with name and data structures is declared, and then serialization and unserialization of the data are automatic.
For instance contract XYZ
:
SERIALIZATION_CONTRACT(XYZ)(std::vector<std::tuple<int, std::string>> par1, std::wstring par2);
Then to serialize these data in std::vector<uint8_t> bytes
:
std::vector<uint8_t> bytes;
SERIALIZE(XYZ)(bytes)({{10, "ABC1"}, {11, "ABC2"}}, L"ABC3");
And to unserialize from std::vector<uint8_t> bytes
:
std::vector<std::tuple<int, std::string>> out1;
std::wstring out2;
UNSERIALIZE(XYZ)(bytes)(out1, out2);
SerializationContract.h contains implementation of SERIALIZATION_CONTRACT, SERIALIZE, UNSERIALIZE macros.
SerializationContractData.h contains implementation for serialization, and unserialization for most STL data structures.
Serialization, and unserialization of a custom struct Data
can be implemented like:
struct Data {
std::wstring _str;
};
// 'Data' serialization and unserialization.
namespace SerializationContract {
Serializer& operator << (Serializer& serializer, const Data& data) {
return serializer << data._str;
}
Unserializer& operator >> (Unserializer& unserializer, Data& data) {
return unserializer >> data._str;
}
}
Then Data
can be used like any other STL data structure that is implemented in SerializationContractData.h
An example of a contract XYZ
and its serialization and unserialization is in main.cpp
The framework can be tested on https://wandbox.org/permlink/C5mXEEAsVHgf6mnt