Packet.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #ifndef PACKET_H
  2. #define PACKET_H
  3. #include "utils/Buffer.h"
  4. #include "utils/StringBuffer.h"
  5. #include "utils/Types.h"
  6. enum class PacketType { RELIABLE, SEQUENCED, UNSEQUENCED };
  7. class InPacket {
  8. const char* data;
  9. int size;
  10. int index;
  11. public:
  12. InPacket(const void* data, int size);
  13. bool readU8(uint8& u);
  14. bool readU16(uint16& u);
  15. bool readU32(uint32& u);
  16. bool readS8(int8& s);
  17. bool readS16(int16& s);
  18. bool readS32(int32& s);
  19. bool readFloat(float& f);
  20. template<int N>
  21. bool readString(StringBuffer<N>& s) {
  22. uint16 end;
  23. if(readU16(end)) {
  24. return true;
  25. }
  26. s.clear();
  27. for(unsigned int i = 0; i < end; i++) {
  28. int8 c;
  29. if(readS8(c)) {
  30. return true;
  31. }
  32. s.append(c);
  33. }
  34. return false;
  35. }
  36. private:
  37. bool read(void* buffer, int length);
  38. };
  39. struct OutPacket {
  40. Buffer buffer;
  41. OutPacket(int initialSize);
  42. OutPacket& writeU8(uint8 u);
  43. OutPacket& writeU16(uint16 u);
  44. OutPacket& writeU32(uint32 u);
  45. OutPacket& writeS8(int8 s);
  46. OutPacket& writeS16(int16 s);
  47. OutPacket& writeS32(int32 s);
  48. OutPacket& writeFloat(float f);
  49. template<int N>
  50. OutPacket& writeString(const StringBuffer<N>& s) {
  51. uint16 end = s.getLength() > 65535 ? 65535 : s.getLength();
  52. writeU16(end);
  53. for(unsigned int i = 0; i < end; i++) {
  54. writeS8(s[i]);
  55. }
  56. return *this;
  57. }
  58. };
  59. #endif