Joedb 9.5.0
The Journal-Only Embedded Database
Loading...
Searching...
No Matches
Buffer.h
Go to the documentation of this file.
1#ifndef joedb_Buffer_declared
2#define joedb_Buffer_declared
3
5
6#include <stdint.h>
7#include <cstring>
8
9namespace joedb
10{
11 /// @ingroup journal
12 template<int log_size> class Buffer
13 {
14 public:
15 static constexpr size_t size = (1 << log_size);
16 static constexpr int64_t ssize = (1 << log_size);
17 static constexpr size_t extra_size = 8;
18
20 size_t index;
21
22 //////////////////////////////////////////////////////////////////////////
23 template<typename T> void write(T x)
24 //////////////////////////////////////////////////////////////////////////
25 {
26 JOEDB_DEBUG_ASSERT(index + sizeof(T) < size + extra_size);
27 std::memcpy(data + index, (const char *)&x, sizeof(T));
28 index += sizeof(T);
29 }
30
31 //////////////////////////////////////////////////////////////////////////
32 template<typename T> T read()
33 //////////////////////////////////////////////////////////////////////////
34 {
35 JOEDB_DEBUG_ASSERT(index + sizeof(T) < size + extra_size);
36 T result;
37 std::memcpy((char *)&result, data + index, sizeof(T));
38 index += sizeof(T);
39 return result;
40 }
41
42 //////////////////////////////////////////////////////////////////////////
43 template<typename T> void compact_write(T x)
44 //////////////////////////////////////////////////////////////////////////
45 {
46 if (x < 0x20)
47 write<uint8_t>(uint8_t(x));
48 else if (x < 0x20 * 0x100)
49 {
50 write<uint8_t>(uint8_t(0x20 | (x >> 8)));
51 write<uint8_t>(uint8_t(x));
52 }
53 else
54 {
55 uint32_t extra_bytes = 2;
56
57 while ((x >> (8 * extra_bytes)) >= 0x20 && extra_bytes < sizeof(T) - 1)
58 extra_bytes++;
59
60 write<uint8_t>(uint8_t((extra_bytes << 5) | (x >> (8 * extra_bytes))));
61 write<uint8_t>(uint8_t(x >> (8 * --extra_bytes)));
62 write<uint8_t>(uint8_t(x >> (8 * --extra_bytes)));
63 while (extra_bytes)
64 write<uint8_t>(uint8_t(x >> (8 * --extra_bytes)));
65 }
66 }
67
68 //////////////////////////////////////////////////////////////////////////
69 template<typename T> T compact_read()
70 //////////////////////////////////////////////////////////////////////////
71 {
72 const uint8_t first_byte = read<uint8_t>();
73 int extra_bytes = first_byte >> 5;
74 T result = first_byte & 0x1f;
75 while (--extra_bytes >= 0)
76 result = T((result << 8) | read<uint8_t>());
77 return result;
78 }
79 };
80}
81
82#endif
T compact_read()
Definition Buffer.h:69
static constexpr int64_t ssize
Definition Buffer.h:16
size_t index
Definition Buffer.h:20
void write(T x)
Definition Buffer.h:23
static constexpr size_t extra_size
Definition Buffer.h:17
char data[size+extra_size]
Definition Buffer.h:19
static constexpr size_t size
Definition Buffer.h:15
void compact_write(T x)
Definition Buffer.h:43
#define JOEDB_DEBUG_ASSERT(x)
Definition assert.h:20
Definition Blob.h:7