I want to serialize a C++ class Ramdomclass . Below is the serialization function.
std::vector<uint8_t> Serialize(Ramdomclass &Ramdom)
{
// First encode the dom content
std::vector<uint8_t> Buf;
// First Part
// Name: vec(byte)
// vec(byte): size:u32, bytes
auto EncodedSize = EncodeU32(Ramdom.getName().length());
Buf.insert(Buf.end(), EncodedSize.begin(), EncodedSize.end());
Buf.insert(Buf.end(), Ramdom.getName().cbegin(), Ramdom.getName().cend());
// Second Part
// Buf: vec(byte)
// vec(byte): size:u32, bytes
EncodedSize = EncodeU32(Ramdom.getContent().size());
Buf.insert(Buf.end(), EncodedSize.begin(), EncodedSize.end());
Buf.insert(Buf.end(), Ramdom.getContent().cbegin(), Ramdom.getContent().cend());
// dom ID
std::vector<uint8_t> Result;
Result.push_back(0x00U);
// The dom size.
EncodedSize = EncodeU32(Buf.size());
Result.insert(Result.end(), EncodedSize.begin(), EncodedSize.end());
// add dom content.
Result.insert(Result.end(), Buf.begin(), Buf.end());
// This is an bruteforce example. Can you do more fast ?.
return Result;
}
std::vector<uint8_t> EncodeU32(uint32_t d)
{
std::vector<uint8_t> encoded;
// unsigned LEB128 encoding
do
{
auto x = d & 0b01111111;
d >>= 7;
if (d)
x |= 0b10000000;
encoded.push_back(x);
} while (d);
return encoded; // this will be in bytes if we want to see it then unsigned(encoded[i]) will be a number betweern 0 to 255
}
I think I can improve in terms of the way I am appending different parts in std::vector<uint8_t> Buf;. I want to know is there any better way of doing this ? maybe instead of using insert can I used anyone other way
Note:: All the things I am appending to std::vector<uint8_t> Buf are in bytes(binary).
Randomclassand without the deserialisation code, it's difficult to be sure it's even correct. For a good review, I recommend you include both of those, and the unit-tests, too. \$\endgroup\$Serialize(Classes &AllClasses){ Serialize(Ramdomclass &Ramdom) ; Serialize(Ramclass &Ram) ; Serialize(Rodonclass &Rodan); .... }and every class contains same members . \$\endgroup\$