-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathallocator.cpp
More file actions
53 lines (43 loc) · 1.47 KB
/
allocator.cpp
File metadata and controls
53 lines (43 loc) · 1.47 KB
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
struct Allocator {
Array_dyn<Array<u8>> full;
Array_dyn<u8> current;
s64 level = 0;
};
template <typename T=u8>
Array<T> allocator_alloc(Allocator* a, s64 count) {
s64 size = count * sizeof(T);
if (a->current.size + size > a->current.capacity) {
array_push(&a->full, a->current);
a->current.size = a->current.capacity;
a->current = {};
s64 n = 128 << a->level;
if (n < size) n = size;
a->current = Array_dyn<u8> {array_create<u8>(n)};
a->current.do_not_reallocate = true;
a->current.size = 0;
++a->level;
}
a->current.size += size;
assert(a->current.size <= a->current.capacity);
Array<u8> result = array_subarray(a->current, a->current.size-size);
array_memset(result);
return {(T*)result.data, (s64)(result.size/sizeof(T))};
}
s64 allocator_index(Allocator* a) {
s64 index = 0;
for (auto arr: a->full) index += arr.size;
index += a->current.size;
return index;
}
void allocator_free(Allocator* a, s64 index=0) {
s64 index_full = 0;
for (auto arr: a->full) index_full += arr.size;
while (a->full.size and index < index_full - a->full.back().size) {
Array_dyn<u8> temp {a->full.back()};
index_full -= temp.size;
--a->full.size;
if (temp.capacity > a->current.capacity) simple_swap(&temp, &a->current);
array_free(&temp);
}
a->current.size = max(index - index_full, 0ll);
}