-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockwriter.h
67 lines (58 loc) · 1.35 KB
/
blockwriter.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#pragma once
class BlockWriter
{
struct Block
{
size_t pos;
char buffer[512];
Block() : pos(0), buffer{ 0 } {}
template<typename T>
void write(const T& data, size_t size = sizeof(T))
{
memcpy(&buffer[pos], &data, size);
pos += size;
}
inline size_t space()
{
return 512 - pos;
}
};
public:
size_t blocks = 0;
std::unordered_map<size_t, Block*> block;
template<typename T>
void write(const T& data, size_t size = sizeof(T))
{
if (!block[blocks])
block[blocks] = new Block();
auto space = block[blocks]->space();
if (space == 0)
{
writeNextBlock(data, size);
}
else if (size > space)
{
block[blocks]->write(data, space);
write(((char*)&data)[space], size - space);
}
else
{
block[blocks]->write(data, size);
}
}
template<typename T>
void writeNextBlock(const T& data, size_t size = sizeof(T))
{
blocks++;
write(data, size);
}
template<typename T>
T get(int blockIdx = 0, int pos = 0)
{
return *(T*)&block[blockIdx]->buffer[pos];
}
size_t size()
{
return (blocks * 512) + block[blocks - 1]->pos;
}
};