1#ifndef SERIALIZEBUFFER_HH
2#define SERIALIZEBUFFER_HH
39 void insert(
const void* __restrict data,
size_t len)
42 if (__builtin_constant_p(len)) {
44 insertN<1>(data);
return;
45 }
else if (len == 2) {
46 insertN<2>(data);
return;
47 }
else if (len == 4) {
48 insertN<4>(data);
return;
49 }
else if (len == 8) {
50 insertN<8>(data);
return;
57 template<
size_t N>
void insertN(
const void* __restrict data);
59 void insertN(
const void* __restrict data,
size_t len);
69 auto accum = [&](
auto* p) { len +=
sizeof(*p); };
70 std::apply([&](
auto&&... args) { (accum(args), ...); }, tuple);
72 if (
const uint8_t* newEnd = end + len; newEnd > buf.
end()) [[unlikely]] {
77 auto write = [&](
auto* src) {
78 memcpy(dst, src,
sizeof(*src));
81 std::apply([&](
auto&&... args) { (write(args), ...); }, tuple);
82 assert(dst == (end + len));
90 insert(std::get<0>(tuple),
sizeof(T));
97 void insertAt(
size_t pos,
const void* __restrict data,
size_t len)
99 assert(buf.
data() + pos + len <= buf.
end());
100 memcpy(buf.
data() + pos, data, len);
111 [[nodiscard]] std::span<uint8_t>
allocate(
size_t len)
113 auto* newEnd = end + len;
116 size_t newSize = newEnd - buf.
data();
117 lastSize = std::max(lastSize, newSize + 1000);
118 if (newEnd <= buf.
end()) {
119 uint8_t* result = end;
121 return {result, len};
123 return {allocateGrow(len), len};
149 return end - buf.
data();
158 void insertGrow(
const void* __restrict data,
size_t len);
159 [[nodiscard]] uint8_t* allocateGrow(
size_t len);
160 void grow(
size_t len);
166 static inline size_t lastSize = 50000;
187 void read(
void* __restrict result,
size_t len)
189 assert(buf.size() >= len);
190 memcpy(result, buf.data(), len);
191 buf = buf.subspan(len);
200 assert(buf.size() >= len);
201 buf = buf.subspan(len);
212 std::span<const uint8_t> buf;
This class manages the lifetime of a block of memory.
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.
std::span< uint8_t > allocate(size_t len)
Reserve space to insert the given number of bytes.
ALWAYS_INLINE void insert_tuple_ptr(const TUPLE &tuple)
Insert all the elements of the given tuple.
MemBuffer< uint8_t > release() &&
Release ownership of the buffer.
size_t getPosition() const
Free part of a previously allocated buffer.
void insert(const void *data, size_t len)
Insert data at the end of this buffer.
This file implemented 3 utility functions: