summaryrefslogtreecommitdiff
path: root/src/dynamic-array.hpp
blob: 29fb765dc16c3abd45c687dd7428d03e9fa0d482 (plain)
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
#ifndef FOUR_ZED_ZED_DYNAMIC_ARRAY_HPP
#define FOUR_ZED_ZED_DYNAMIC_ARRAY_HPP

#include "memory.hpp"

#include <cstdint>
#include <cstring>
#include <cassert>

#define BAKE_DYN_ARRAY(T) template struct DynArray<T>;

struct DynArrayBase {
	char *ptr = nullptr;
	int64_t elementSize = 0;
	int64_t reservedSize = 0;
};

template <typename T>
struct DynArray: DynArrayBase {
	DynArray();
	~DynArray();
	T operator[](std::size_t index);
	T *GetPtr();
	void Reserve(int64_t count);
	private:
		using DynArrayBase::ptr;
		using DynArrayBase::elementSize;
		using DynArrayBase::reservedSize;
};

void inline DynArrayReserve(DynArrayBase *arr, int64_t count);
void inline DynArrayDestroy(DynArrayBase *arr);

template <typename T> inline DynArray<T>::DynArray() {
	this->elementSize = sizeof(T);
}

template <typename T> inline DynArray<T>::~DynArray() {
	DynArrayDestroy(this);
}

template <typename T> inline T DynArray<T>::operator[](std::size_t index) {
	assert(index < this->reservedSize && "Invalid DynArray<T> index");
	return *reinterpret_cast<T *>((this->ptr + (sizeof(T) * index)));
}

template <typename T> inline T *DynArray<T>::GetPtr() {
	return reinterpret_cast<T *>(reinterpret_cast<void *>(this->ptr));
}

template <typename T> inline void DynArray<T>::Reserve(int64_t count) {
	return DynArrayReserve(this, count);
}

#endif /* FOUR_ZED_ZED_DYNAMIC_ARRAY_HPP */