Packet.cpp 946 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #define ENET_IMPLEMENTATION
  2. #include "common/enet/enet.h"
  3. #include "common/network/Packet.h"
  4. Packet::Packet(ENetPacket* packet) : packet(packet), readIndex(0), error(false) {
  5. }
  6. Packet::~Packet() {
  7. enet_packet_destroy(packet);
  8. }
  9. bool Packet::hasData() const {
  10. return readIndex < static_cast<int>(packet->dataLength);
  11. }
  12. bool Packet::hasError() const {
  13. return error;
  14. }
  15. void Packet::read(void* buffer, int length) {
  16. if(readIndex + length > static_cast<int>(packet->dataLength)) {
  17. error = true;
  18. return;
  19. }
  20. memcpy(buffer, packet->data + readIndex, length);
  21. readIndex += length;
  22. }
  23. Packet::int8 Packet::read8() {
  24. int8 uc;
  25. read(&uc, sizeof (int8));
  26. return uc;
  27. }
  28. Packet::int16 Packet::read16() {
  29. int16 us;
  30. read(&us, sizeof (int16));
  31. us = ntohs(us);
  32. return us;
  33. }
  34. Packet::int32 Packet::read32() {
  35. int32 ui;
  36. read(&ui, sizeof (int32));
  37. ui = ntohl(ui);
  38. return ui;
  39. }