Add basic Buffer class

This commit is contained in:
DankParrot 2020-07-24 22:51:59 -07:00
parent f298df5aef
commit 4946a5fa56
4 changed files with 82 additions and 10 deletions

View File

@ -4,6 +4,7 @@ feather_src = [
'network/NetworkManager.cpp',
'network/TCPListener.cpp',
'network/Buffer.cpp',
'util/StringUtil.cpp',

38
src/network/Buffer.cpp Normal file
View File

@ -0,0 +1,38 @@
#include "Buffer.h"
#include <cstring>
using byte = uint8_t;
namespace Feather::Network
{
int Buffer::WriteVarInt(int value)
{
int size = 0;
do {
byte temp = (byte)(value & 0b01111111);
// Note: >>> means that the sign bit is shifted with the rest of the number rather than being left alone
value >>= 7;
if (value != 0) {
temp |= 0b10000000;
}
WriteByte(temp);
size++;
} while (value != 0);
return size;
}
void Buffer::WriteString(const char* str)
{
WriteString(str, strlen(str));
}
void Buffer::WriteString(const char *str, size_t length)
{
WriteVarInt(length);
for (int i = 0; i < length; i++)
WriteByte(str[i]);
}
}

30
src/network/Buffer.h Normal file
View File

@ -0,0 +1,30 @@
#pragma once
#include <vector>
#include <cstdint>
using std::vector;
namespace Feather::Network
{
class Buffer
{
public:
inline void WriteByte(uint8_t byte) { m_data.push_back(byte); }
// Returns the number of bytes written.
int WriteVarInt(int i);
// Write a null terminated string to the buffer.
void WriteString(const char *str);
// Write a string with known size to the buffer
void WriteString(const char *str, size_t length);
inline vector<uint8_t> GetData() { return m_data; }
inline size_t Size() { return m_data.size(); }
private:
vector<uint8_t> m_data;
};
}

View File

@ -8,6 +8,8 @@
#include <mutex>
#include "Buffer.h"
namespace Feather::Network
{
class TCPSocket
@ -162,17 +164,18 @@ namespace Feather::Network
std::vector<unsigned char> EncodeMessageTest(int packetid, const unsigned char* data, size_t size)
{
std::vector<unsigned char> message;
int msg_size = fuckvarintsize(packetid) + fuckvarintsize(int(size)) + int(size);
// fuck fuck fuck this is terrible
// TODO proper clas for this varint bullshit
writeVarInt(msg_size, message);
writeVarInt(packetid, message);
writeVarInt(size, message);
for (size_t i = 0; i < size; i++)
message.push_back(data[i]);
Buffer msg;
return message;
// TODO: message size prepender. could potentially be done without copying
int msg_size = fuckvarintsize(packetid) + fuckvarintsize(int(size)) + int(size);
msg.WriteVarInt(msg_size);
msg.WriteVarInt(packetid);
msg.WriteVarInt(size);
for (size_t i = 0; i < size; i++)
msg.WriteByte(data[i]);
return msg.GetData();
}
bool SendShitTest()