-
Notifications
You must be signed in to change notification settings - Fork 36
/
CompactStrings.h
84 lines (62 loc) · 1.99 KB
/
CompactStrings.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#pragma once
#include <Common/PODArray.h>
#include <Service/memcopy.h>
#include <common/StringRef.h>
namespace RK
{
/**
* Compact string list which store all data into single memory block to avoid the overhead of multiple allocations and de-allocations.
*/
class CompactStrings
{
public:
using Offsets = PODArray<int64_t, 128, Allocator<false>, 15, 8>;
using Data = PODArray<char, 256, Allocator<false>, 15, 8>;
static constexpr size_t AVG_ELEMENT_SIZE_HINT = 64;
struct Iterator
{
Offsets::const_iterator itr;
const Data & data;
Iterator(Offsets::const_iterator itr_, const Data & data_) : itr(itr_), data(data_) {}
void operator++()
{
itr++;
}
bool operator!=(const Iterator & other) const
{
return itr != other.itr;
}
StringRef operator*() const
{
return StringRef(data.data() + *(itr - 1), *itr - *(itr - 1));
}
};
CompactStrings() = default;
CompactStrings(CompactStrings && other);
CompactStrings(const CompactStrings & other);
void reserve(size_t n, size_t total_size = 0);
inline void push_back(const String & s)
{
const size_t old_size = data.size();
const size_t size_to_append = s.size();
const size_t new_size = old_size + size_to_append;
data.resize(new_size);
memcopy(data.data() + old_size, s.c_str(), size_to_append);
offsets.push_back(new_size);
}
template <class Ttr> void push_back(Ttr begin, Ttr end)
{
for (Ttr it = begin; it != end; ++it)
push_back(*it);
}
StringRef operator[](int64_t i) const;
String getString(int64_t i) const;
Strings toStrings() const;
inline Iterator begin() const { return Iterator(offsets.begin(), data); }
inline Iterator end() const { return Iterator(offsets.end(), data); }
size_t size() const { return offsets.size(); }
private:
Data data;
Offsets offsets;
};
}