M2-PT-DRP/source/packets/base/PacketData.hpp

48 lines
1.3 KiB
C++

#pragma once
#include <cstring>
#include "PacketContent.hpp"
#include "../../events/types.hpp"
namespace drp::packet::base {
/**
* Represent the actual data contained inside a packet, with no header.
* Can be used to implement and communicate anything.
* @tparam eventType the event type associated with this type of packet data.
* Allow the receiver to redirect this packet to the correct handler.
*/
template<event::EventType eventType, class packetClass>
class PacketData {
public:
/**
* Convert this packet data to a generic packet content.
* @return a generic packet content.
*/
[[nodiscard]] PacketContent toGeneric() const {
// create an empty generic packet content
PacketContent content {};
// set its content
content.eventType = static_cast<std::uint8_t>(eventType);
std::memcpy(&content.data, this, sizeof(content));
return content;
}
/**
* Get the data from a generic packet data.
* @param content a generic packet content.
* @return the actual packet data.
*/
static packetClass fromGeneric(const PacketContent& content) {
packetClass data;
std::memcpy(&data, content.data.data(), sizeof(packetClass));
return data;
}
};
}