81 lines
1.8 KiB
C++
81 lines
1.8 KiB
C++
#pragma once
|
|
|
|
#include "Common.h"
|
|
|
|
#include <cstdio>
|
|
#include <cstdint>
|
|
#include <string>
|
|
|
|
using std::string;
|
|
|
|
namespace Feather
|
|
{
|
|
// Class to read packet data, such as is produced by NetworkMessage
|
|
class PacketReader
|
|
{
|
|
public:
|
|
PacketReader(const uint8_t *const dataPtr)
|
|
: m_data(dataPtr), m_offset(0), m_length(ReadVarInt())
|
|
{
|
|
}
|
|
|
|
template <typename T>
|
|
inline T Peek()
|
|
{
|
|
return *reinterpret_cast<const T* const>(&m_data[m_offset]);
|
|
}
|
|
|
|
template <typename T>
|
|
inline T Read()
|
|
{
|
|
T value = Peek<T>();
|
|
m_offset += sizeof(T);
|
|
return value;
|
|
}
|
|
|
|
template <typename T = int32_t>
|
|
inline T ReadVarInt()
|
|
{
|
|
int32_t numRead = 0;
|
|
int32_t result = 0;
|
|
uint8_t read;
|
|
do
|
|
{
|
|
read = Read<uint8_t>();
|
|
int value = (read & 0b01111111);
|
|
result |= (value << (7 * numRead));
|
|
|
|
numRead++;
|
|
if (numRead > 5)
|
|
{
|
|
// complain
|
|
//throw new RuntimeException("VarInt is too big");
|
|
}
|
|
} while ((read & 0b10000000) != 0);
|
|
|
|
return static_cast<T>(result);
|
|
}
|
|
|
|
string ReadString()
|
|
{
|
|
int size = ReadVarInt();
|
|
string str;
|
|
|
|
for (int i = 0; i < size; i++) {
|
|
str += Read<uint8_t>();
|
|
}
|
|
|
|
//printf("Read string of length %d: %s\n", size, str);
|
|
|
|
return str;
|
|
}
|
|
|
|
uint32_t Length() const { return m_length; }
|
|
private:
|
|
const uint8_t *const m_data;
|
|
uint32_t m_offset;
|
|
const uint32_t m_length;
|
|
};
|
|
|
|
}
|