I have a project that does packet serialization of several different types(Packet1
, Packet2
...). They all extend a PacketHeader
class and does its own serialization
This approach seems very messy and error-prone, especially as the number of fields grows.
Is there a cleaner and more OOP & C++ way for serialization(without 3rd-party library)?
class PacketHeader {
uint8_t type;
uint32_t id;
uint32_t seqNum;
virtual void serialize(uint8_t *buf, size_t size) {
int offset = 0;
PacketHeader n;
n.type = type;
n.id = htonl(id);
n.seqNum = htonl(seqNum);
memcpy(buf + offset, &(n.type), sizeof(n.type));
offset += sizeof(n.type);
memcpy(buf + offset, &(n.id), sizeof(n.id));
offset += sizeof(n.id);
memcpy(buf + offset, &n.seqNum, sizeof(n.seqNum));
offset += sizeof(n.seqNum);
}
}
class Packet1 : public PacketHeader {
uint32_t payload;
virtual void serialize(uint8_t *buf, size_t size) {
int offset = PacketHeader::size();
PacketHeader::serialize(buf, size);
memcpy(buf + offset, &n.payload, sizeof(n.payload));
offset += sizeof(n.payload);
}
}