123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134 |
- #include "libs/enet/include/enet.h"
- #include "network/Packet.h"
- static_assert(sizeof(float) == sizeof(uint32),
- "sizeof(float) != sizeof(uint32)");
- InPacket::InPacket(const void* data, int size)
- : data(static_cast<const char*>(data)), size(size), index(0) {
- }
- bool InPacket::read(void* buffer, int length) {
- if(index + length > size) {
- return true;
- }
- memcpy(buffer, data + index, length);
- index += length;
- return false;
- }
- bool InPacket::readU8(uint8& u) {
- return read(&u, sizeof(u));
- }
- bool InPacket::readU16(uint16& u) {
- if(read(&u, sizeof(u))) {
- return true;
- }
- u = ntohs(u);
- return false;
- }
- bool InPacket::readU32(uint32& u) {
- if(read(&u, sizeof(u))) {
- return true;
- }
- u = ntohl(u);
- return false;
- }
- bool InPacket::readS8(int8& s) {
- uint8 u;
- if(readU8(u)) {
- return true;
- }
- if(u < 128) {
- s = static_cast<int8>(u) - 128;
- } else {
- s = u - 128;
- }
- return false;
- }
- bool InPacket::readS16(int16& s) {
- uint16 u;
- if(readU16(u)) {
- return true;
- }
- if(u < 32768) {
- s = static_cast<int16>(u) - 32768;
- } else {
- s = u - 32768;
- }
- return false;
- }
- bool InPacket::readS32(int32& s) {
- uint32 u;
- if(readU32(u)) {
- return true;
- }
- if(u < 2147483648) {
- s = static_cast<int32>(u) - 2147483648;
- } else {
- s = u - 2147483648;
- }
- return false;
- }
- bool InPacket::readFloat(float& f) {
- uint32 u;
- if(readU32(u)) {
- return true;
- }
- memcpy(&f, &u, sizeof(float));
- return false;
- }
- OutPacket::OutPacket(int initialSize) : buffer(initialSize) {
- }
- OutPacket& OutPacket::writeU8(uint8 u) {
- buffer.add(u);
- return *this;
- }
- OutPacket& OutPacket::writeU16(uint16 u) {
- u = htons(u);
- buffer.add(u);
- return *this;
- }
- OutPacket& OutPacket::writeU32(uint32 u) {
- u = htonl(u);
- buffer.add(u);
- return *this;
- }
- OutPacket& OutPacket::writeS8(int8 s) {
- if(s < 0) {
- return writeU8(s + 128);
- }
- return writeU8(static_cast<uint8>(s) + 128u);
- }
- OutPacket& OutPacket::writeS16(int16 s) {
- if(s < 0) {
- return writeU16(s + 32768);
- }
- return writeU16(static_cast<uint16>(s) + 32768u);
- }
- OutPacket& OutPacket::writeS32(int32 s) {
- if(s < 0) {
- return writeU32(s + 2147483648);
- }
- return writeU32(static_cast<uint32>(s) + 2147483648u);
- }
- OutPacket& OutPacket::writeFloat(float f) {
- uint32 u;
- memcpy(&u, &f, sizeof(float));
- return writeU32(u);
- }
|