From 6bef4cb4dcb17dd59be44ab15caf812ed1a25660 Mon Sep 17 00:00:00 2001 From: Joshua Ashton Date: Tue, 28 Jul 2020 05:51:42 +0100 Subject: [PATCH] Use a generic template read for PacketReader --- src/network/PacketReader.h | 31 +++++++------------------------ src/network/Protocol.cpp | 4 ++-- 2 files changed, 9 insertions(+), 26 deletions(-) diff --git a/src/network/PacketReader.h b/src/network/PacketReader.h index 339c527..bee1093 100644 --- a/src/network/PacketReader.h +++ b/src/network/PacketReader.h @@ -20,9 +20,12 @@ namespace Feather::Network { } - inline uint8_t ReadByte() + template + inline T Read() { - return m_data[m_offset++]; + T value = *reinterpret_cast(&m_data[m_offset]); + m_offset += sizeof(T); + return value; } inline int ReadVarInt() @@ -32,7 +35,7 @@ namespace Feather::Network uint8_t read; do { - read = ReadByte(); + read = Read(); int value = (read & 0b01111111); result |= (value << (7 * numRead)); @@ -47,33 +50,13 @@ namespace Feather::Network 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() { int size = ReadVarInt(); string str; for (int i = 0; i < size; i++) { - str += ReadByte(); + str += Read(); } //printf("Read string of length %d: %s\n", size, str); diff --git a/src/network/Protocol.cpp b/src/network/Protocol.cpp index 4b9ef6b..b787916 100644 --- a/src/network/Protocol.cpp +++ b/src/network/Protocol.cpp @@ -25,7 +25,7 @@ namespace Feather::Network int clientProtocolVersion = packet.ReadVarInt(); string serverIp = packet.ReadString(); - unsigned short port = packet.ReadUnsignedShort(); + uint16_t port = packet.Read(); // next desired state ProtocolState intention = (ProtocolState)(packet.ReadVarInt()); @@ -83,7 +83,7 @@ R"({ break; } case ServerboundPacketType::STATUS_PING: - int64_t timestamp = packet.ReadLong(); + int64_t timestamp = packet.Read(); printf("[Protocol] Client sent STATUS_PING: %lld\n", timestamp); /*DynamicNetworkMessage msg(VARINT_MAX_SIZE + sizeof(int64_t));