In any project, when a function is created for serialization, another function is created for unserialization.
Serialization by contract 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>>, std::wstring);
Then to serialize these data in std::vector<uint8_t> bytes
:
std::vector<uint8_t> bytes;
XYZ({{10, "ABC1"}, {11, "ABC2"}}, L"ABC3") >> bytes;
And to unserialize from std::vector<uint8_t> bytes
:
std::vector<std::tuple<int, std::string>> out1;
std::wstring out2;
XYZ(out1, out2) << bytes;
SerializationContract.h contains implementation of SERIALIZATION_CONTRACT macro.
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/DAcRSkRIuSTREAgi