-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy patharray.h
60 lines (46 loc) · 1.31 KB
/
array.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
#ifndef ARRAY_H
#define ARRAY_H
#include <limits>
#include "alloc.h"
#include "common.h"
#define MAX(a, b) ((a > b) ? a : b)
// A constant capacity buffer without C++ magic.
template<typename T, MEM mem>
struct Array {
// Members
size_t cap, len;
T *data;
Array() {
cap = len = 0;
data = nullptr;
}
Array(size_t n) : Array() {
reserve(n);
}
// No destructor, no copy and rvalue constructors.
// It works like a C struct.
public:
void push(T v) {
constexpr size_t size_t_max = std::numeric_limits<size_t>::max();
assert(len < size_t_max);
assert(len < cap);
size_t new_len = len + 1;
data[len] = v;
len = new_len;
}
void reserve(size_t n) {
assert(len == 0 && cap == 0);
if (!n) return;
data = (T *) allocate(n * sizeof(T), mem);
assert(data);
len = 0;
cap = n;
}
T& operator[](size_t i) { assert(i < len); return data[i]; }
const T& operator[](size_t i) const { assert(i < len); return data[i]; }
inline T* begin() { return this->data; }
inline const T* begin() const { return this->data; }
inline T* end() { return &this->data[len]; }
inline const T* end() const { return &this->data[len]; }
};
#endif