1 #ifndef SERIALIZEBUFFER_HH
2 #define SERIALIZEBUFFER_HH
37 void insert(
const void* __restrict data,
size_t len)
40 if (__builtin_constant_p(len)) {
42 insertN<1>(data);
return;
43 }
else if (len == 2) {
44 insertN<2>(data);
return;
45 }
else if (len == 4) {
46 insertN<4>(data);
return;
47 }
else if (len == 8) {
48 insertN<8>(data);
return;
55 template<
size_t N>
void insertN(
const void* __restrict data);
57 void insertN(
const void* __restrict data,
size_t len);
67 auto accum = [&](
auto* p) { len +=
sizeof(*p); };
68 std::apply([&](
auto&&... args) { (accum(args), ...); }, tuple);
70 uint8_t* newEnd = end + len;
71 if (newEnd > finish) [[unlikely]] {
76 auto write = [&](
auto* src) {
77 memcpy(dst, src,
sizeof(*src));
80 std::apply([&](
auto&&... args) { (write(args), ...); }, tuple);
81 assert(dst == (end + len));
89 insert(std::get<0>(tuple),
sizeof(T));
96 void insertAt(
size_t pos,
const void* __restrict data,
size_t len)
98 assert(buf.
data() + pos + len <= finish);
99 memcpy(buf.
data() + pos, data, len);
112 auto* newEnd = end + len;
115 size_t newSize = newEnd - buf.
data();
116 lastSize =
std::max(lastSize, newSize + 1000);
117 if (newEnd <= finish) {
118 uint8_t* result = end;
122 return allocateGrow(len);
139 assert(buf.
data() <= pos);
148 return end - buf.
data();
157 void insertGrow(
const void* __restrict data,
size_t len);
158 [[nodiscard]] uint8_t* allocateGrow(
size_t len);
159 void grow(
size_t len);
167 static inline size_t lastSize = 50000;
187 void read(
void* __restrict result,
size_t len) __restrict
189 memcpy(result, buf, len);
191 assert(buf <= finish);
201 assert(buf <= finish);
214 const uint8_t* finish;
const T * data() const
Returns pointer to the start of the memory buffer.
void insertAt(size_t pos, const void *data, size_t len)
Insert data at a given position.
ALWAYS_INLINE void insert_tuple_ptr(const std::tuple< T * > &tuple)
void insertN(const void *data, size_t len)
OutputBuffer()
Create an empty output buffer.
uint8_t * allocate(size_t len)
Reserve space to insert the given number of bytes.
MemBuffer< uint8_t > release(size_t &size)
Release ownership of the buffer.
ALWAYS_INLINE void insert_tuple_ptr(const TUPLE &tuple)
Insert all the elements of the given tuple.
size_t getPosition() const
Get the current size of the buffer.
void deallocate(uint8_t *pos)
Free part of a previously allocated buffer.
void insert(const void *data, size_t len)
Insert data at the end of this buffer.
constexpr vecN< N, T > max(const vecN< N, T > &x, const vecN< N, T > &y)
This file implemented 3 utility functions:
size_t size(std::string_view utf8)