Packet.cpp 872 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 < packet->dataLength;
  11. }
  12. bool Packet::hasError() const {
  13. return error;
  14. }
  15. void Packet::read(void* buffer, uint length) {
  16. if(readIndex + length > packet->dataLength) {
  17. error = true;
  18. return;
  19. }
  20. memcpy(buffer, packet->data + readIndex, length);
  21. readIndex += length;
  22. }
  23. u8 Packet::readU8() {
  24. u8 uc;
  25. read(&uc, sizeof (u8));
  26. return uc;
  27. }
  28. u16 Packet::readU16() {
  29. u16 us;
  30. read(&us, sizeof (u16));
  31. us = ntohs(us);
  32. return us;
  33. }
  34. u32 Packet::readU32() {
  35. u32 ui;
  36. read(&ui, sizeof (u32));
  37. ui = ntohl(ui);
  38. return ui;
  39. }