Use a generic template read for PacketReader

This commit is contained in:
Joshua Ashton 2020-07-28 05:51:42 +01:00
parent 8dabf013ef
commit 6bef4cb4dc
2 changed files with 9 additions and 26 deletions

View File

@ -20,9 +20,12 @@ namespace Feather::Network
{ {
} }
inline uint8_t ReadByte() template <typename T>
inline T Read()
{ {
return m_data[m_offset++]; T value = *reinterpret_cast<const T *const>(&m_data[m_offset]);
m_offset += sizeof(T);
return value;
} }
inline int ReadVarInt() inline int ReadVarInt()
@ -32,7 +35,7 @@ namespace Feather::Network
uint8_t read; uint8_t read;
do do
{ {
read = ReadByte(); read = Read<uint8_t>();
int value = (read & 0b01111111); int value = (read & 0b01111111);
result |= (value << (7 * numRead)); result |= (value << (7 * numRead));
@ -47,33 +50,13 @@ namespace Feather::Network
return result; return result;
} }
inline uint16_t ReadUnsignedShort()
{
return (ReadByte() << 8) | ReadByte();
}
inline int64_t ReadLong()
{
int64_t value = 0;
// FIXME
value |= (ReadByte() << 56);
value |= (ReadByte() << 48);
value |= (ReadByte() << 40);
value |= (ReadByte() << 32);
value |= (ReadByte() << 24);
value |= (ReadByte() << 16);
value |= (ReadByte() << 8);
value |= (ReadByte() << 0);
return value;
}
string ReadString() string ReadString()
{ {
int size = ReadVarInt(); int size = ReadVarInt();
string str; string str;
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
str += ReadByte(); str += Read<uint8_t>();
} }
//printf("Read string of length %d: %s\n", size, str); //printf("Read string of length %d: %s\n", size, str);

View File

@ -25,7 +25,7 @@ namespace Feather::Network
int clientProtocolVersion = packet.ReadVarInt(); int clientProtocolVersion = packet.ReadVarInt();
string serverIp = packet.ReadString(); string serverIp = packet.ReadString();
unsigned short port = packet.ReadUnsignedShort(); uint16_t port = packet.Read<uint16_t>();
// next desired state // next desired state
ProtocolState intention = (ProtocolState)(packet.ReadVarInt()); ProtocolState intention = (ProtocolState)(packet.ReadVarInt());
@ -83,7 +83,7 @@ R"({
break; break;
} }
case ServerboundPacketType::STATUS_PING: case ServerboundPacketType::STATUS_PING:
int64_t timestamp = packet.ReadLong(); int64_t timestamp = packet.Read<int64_t>();
printf("[Protocol] Client sent STATUS_PING: %lld\n", timestamp); printf("[Protocol] Client sent STATUS_PING: %lld\n", timestamp);
/*DynamicNetworkMessage msg(VARINT_MAX_SIZE + sizeof(int64_t)); /*DynamicNetworkMessage msg(VARINT_MAX_SIZE + sizeof(int64_t));