-
Notifications
You must be signed in to change notification settings - Fork 26
/
str_arena.h
82 lines (66 loc) · 2 KB
/
str_arena.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
#pragma once
#include "dbcore/sm-common.h"
#include "varstr.h"
#include <atomic>
#include <memory>
namespace ermia {
class str_arena {
public:
static const uint64_t ReserveBytes = 128 * 1024 * 1024;
static const size_t MinStrReserveLength = 2 * CACHELINE_SIZE;
str_arena() : n(0) {
// adler32 (log checksum) needs it aligned
ALWAYS_ASSERT(
not posix_memalign((void **)&str, DEFAULT_ALIGNMENT, ReserveBytes));
memset(str, '\0', ReserveBytes);
reset();
}
// non-copyable/non-movable for the time being
str_arena(str_arena &&) = delete;
str_arena(const str_arena &) = delete;
str_arena &operator=(const str_arena &) = delete;
inline void reset() {
ASSERT(n < ReserveBytes);
n = 0;
}
varstr *next(uint64_t size) {
uint64_t off = n;
n += align_up(size + sizeof(varstr));
ASSERT(n < ReserveBytes);
varstr *ret = new (str + off) varstr(str + off + sizeof(varstr), size);
return ret;
}
varstr *atomic_next(uint64_t size) {
uint64_t off = n.fetch_add(
align_up(size + sizeof(varstr)),
std::memory_order_acq_rel); // for adler32's 16-byte alignment
ASSERT(n < ReserveBytes);
varstr *ret = new (str + off) varstr(str + off + sizeof(varstr), size);
return ret;
}
inline varstr *operator()(uint64_t size) { return next(size); }
bool manages(const varstr *px) const {
return (char *)px >= str and
(uint64_t) px->data() + px->size() <= (uint64_t)str + n;
}
private:
char *str;
std::atomic<size_t> n;
};
class scoped_str_arena {
public:
scoped_str_arena(str_arena *arena) : arena(arena) {}
scoped_str_arena(str_arena &arena) : arena(&arena) {}
scoped_str_arena(scoped_str_arena &&) = default;
// non-copyable
scoped_str_arena(const scoped_str_arena &) = delete;
scoped_str_arena &operator=(const scoped_str_arena &) = delete;
~scoped_str_arena() {
if (arena)
arena->reset();
}
ALWAYS_INLINE str_arena *get() { return arena; }
private:
str_arena *arena;
};
} // namespace ermia