R-Type
Distributed multiplayer game engine in C++
Loading...
Searching...
No Matches
ENetPacket.cpp
Go to the documentation of this file.
1/*
2** EPITECH PROJECT, 2025
3** Created by IamSwan on 06/12/2025.
4** File description:
5** ENetPacket.cpp
6*/
7
8#include "ENetPacket.hpp"
9#include <cstring>
10#include <stdexcept>
11
12ENetPacketWrapper::ENetPacketWrapper(ENetPacket *packet) : _packet(packet), _dataCacheValid(false) {
13 if (!_packet) {
14 throw std::invalid_argument("ENetPacket cannot be null");
15 }
16}
17
18ENetPacketWrapper::ENetPacketWrapper(const std::vector<uint8_t> &data, uint32_t flags)
19 : _packet(nullptr), _dataCacheValid(false) {
20 _packet = enet_packet_create(data.data(), data.size(), flags);
21 if (!_packet) {
22 throw std::runtime_error("Failed to create ENet packet");
23 }
24}
25
27 if (_packet) {
28 enet_packet_destroy(_packet);
29 }
30}
31
33 : _packet(other._packet),
34 _dataCache(std::move(other._dataCache)),
35 _dataCacheValid(other._dataCacheValid) {
36 other._packet = nullptr;
37 other._dataCacheValid = false;
38}
39
41 if (this != &other) {
42 if (_packet) {
43 enet_packet_destroy(_packet);
44 }
45 _packet = other._packet;
46 _dataCache = std::move(other._dataCache);
47 _dataCacheValid = other._dataCacheValid;
48
49 other._packet = nullptr;
50 other._dataCacheValid = false;
51 }
52 return *this;
53}
54
55const std::vector<uint8_t> &ENetPacketWrapper::getData() const {
56 if (!_dataCacheValid && _packet) {
57 _dataCache.assign(_packet->data, _packet->data + _packet->dataLength);
58 _dataCacheValid = true;
59 }
60 return _dataCache;
61}
62
64 return _packet ? _packet->dataLength : 0;
65}
66
68 return _packet ? _packet->flags : 0;
69}
70
71void ENetPacketWrapper::setData(const std::vector<uint8_t> &data) {
72 if (_packet) {
73 enet_packet_destroy(_packet);
74 }
75 _packet = enet_packet_create(data.data(), data.size(), ENET_PACKET_FLAG_RELIABLE);
76 if (!_packet) {
77 throw std::runtime_error("Failed to create ENet packet");
78 }
79 _dataCacheValid = false;
80}
81
83 return _packet;
84}
size_t getSize() const override
Get the size of the packet data in bytes.
const std::vector< uint8_t > & getData() const override
Get the packet data as a byte buffer.
std::vector< uint8_t > _dataCache
void setData(const std::vector< uint8_t > &data) override
Set new data for this packet.
ENetPacket * getNativePacket() const
~ENetPacketWrapper() override
ENetPacket * _packet
ENetPacketWrapper(ENetPacket *packet)
ENetPacketWrapper & operator=(const ENetPacketWrapper &)=delete
uint32_t getFlags() const override
Get the flags associated with this packet.