Rename, move some json stuff to header

This commit is contained in:
Chris Marsh
2017-07-24 10:54:47 -07:00
parent 449584b9c9
commit 88ab85c81e
5 changed files with 87 additions and 84 deletions

View File

@ -1,85 +1,7 @@
#include "serialization.h"
#include "connection.h"
#include "discord-rpc.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/internal/itoa.h"
// I want to use as few allocations as I can get away with, and to do that with RapidJson, you need to supply some of
// your own allocators for stuff rather than use the defaults
class LinearAllocator {
public:
char* buffer_;
char* end_;
LinearAllocator() {
assert(0); // needed for some default case in rapidjson, should not use
}
LinearAllocator(char* buffer, size_t size) : buffer_(buffer), end_(buffer + size) {}
static const bool kNeedFree = false;
void* Malloc(size_t size)
{
char* res = buffer_;
buffer_ += size;
if (buffer_ > end_) {
buffer_ = res;
return nullptr;
}
return res;
}
void* Realloc(void* originalPtr, size_t originalSize, size_t newSize)
{
if (newSize == 0) {
return nullptr;
}
// allocate how much you need in the first place
assert(!originalPtr && !originalSize);
return Malloc(newSize);
}
static void Free(void* ptr) { /* shrug */ }
};
template<int Size>
class FixedLinearAllocator : public LinearAllocator {
public:
char fixedBuffer_[Size];
FixedLinearAllocator() : LinearAllocator(fixedBuffer_, Size) {}
static const bool kNeedFree = false;
};
// wonder why this isn't a thing already, maybe I missed it
class DirectStringBuffer {
public:
typedef typename char Ch;
char* buffer_;
char* end_;
char* current_;
DirectStringBuffer(char* buffer, size_t maxLen)
: buffer_(buffer)
, end_(buffer + maxLen)
, current_(buffer)
{}
void Put(char c)
{
if (current_ < end_) {
*current_++ = c;
}
}
void Flush() {}
size_t GetSize() const
{
return current_ - buffer_;
}
};
using Encoding = rapidjson::UTF8<char>;
// Writer appears to need about 16 bytes per nested object level (with 64bit size_t)
using WriterAllocator = FixedLinearAllocator<2048>;
constexpr size_t WriterNestingLevels = 2048 / 16;
using JsonWriter = rapidjson::Writer<DirectStringBuffer, Encoding, Encoding, WriterAllocator, rapidjson::kWriteNoFlags>;
// it's ever so slightly faster to not have to strlen the key
template<typename T>
void WriteKey(JsonWriter& w, T& k) {