Joedb 9.1.4
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 <stddef.h>
7#include <stdint.h>
8#include <algorithm>
9
10namespace joedb
11{
12 /// @ingroup journal
13 template<int log_size> class Buffer
14 {
15 public:
16 static constexpr size_t size = (1 << log_size);
17 static constexpr int64_t ssize = (1 << log_size);
18 static constexpr size_t extra_size = 8;
19
21 size_t index;
22
23 //////////////////////////////////////////////////////////////////////////
24 template<typename T> void write(T x)
25 //////////////////////////////////////////////////////////////////////////
26 {
27 JOEDB_ASSERT(index + sizeof(T) < size + extra_size);
28 std::copy_n((const char *)&x, sizeof(T), data + index);
29 index += sizeof(T);
30 }
31
32 //////////////////////////////////////////////////////////////////////////
33 template<typename T> T read()
34 //////////////////////////////////////////////////////////////////////////
35 {
36 JOEDB_ASSERT(index + sizeof(T) < size + extra_size);
37 T result;
38 std::copy_n(data + index, sizeof(T), (char *)&result);
39 index += sizeof(T);
40 return result;
41 }
42
43 //////////////////////////////////////////////////////////////////////////
44 template<typename T> void compact_write(T x)
45 //////////////////////////////////////////////////////////////////////////
46 {
47 if (x < 0x20)
49 else if (x < 0x20 * 0x100)
50 {
51 write<uint8_t>(uint8_t(0x20 | (x >> 8)));
53 }
54 else
55 {
57
58 while ((x >> (8 * extra_bytes)) >= 0x20 && extra_bytes < sizeof(T) - 1)
60
61 write<uint8_t>(uint8_t((extra_bytes << 5) | (x >> (8 * extra_bytes))));
64 while (extra_bytes)
66 }
67 }
68
69 //////////////////////////////////////////////////////////////////////////
70 template<typename T> T compact_read()
71 //////////////////////////////////////////////////////////////////////////
72 {
74 int extra_bytes = first_byte >> 5;
75 T result = first_byte & 0x1f;
76 while (--extra_bytes >= 0)
77 result = T((result << 8) | read<uint8_t>());
78 return result;
79 }
80 };
81}
82
83#endif
T compact_read()
Definition Buffer.h:70
static constexpr int64_t ssize
Definition Buffer.h:17
size_t index
Definition Buffer.h:21
void write(T x)
Definition Buffer.h:24
static constexpr size_t extra_size
Definition Buffer.h:18
char data[size+extra_size]
Definition Buffer.h:20
static constexpr size_t size
Definition Buffer.h:16
void compact_write(T x)
Definition Buffer.h:44
#define JOEDB_ASSERT(x)
Definition assert.h:18
Definition Blob.h:7