-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestvector.h
More file actions
142 lines (118 loc) · 2.41 KB
/
testvector.h
File metadata and controls
142 lines (118 loc) · 2.41 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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
namespace teststl
{
template<typename T>
class tvector
{
private:
// container to hold actual contents
// we need to keep this separate to get COW semantics working
struct storage {
int ref;
T* arr;
};
storage* stor;
// to speedup access
T* direct_access;
// length of the array
int length;
// max size of allocated elements as of now (not used as of now)
int size;
// last index - for push_back
int last;
public:
/*
* Constructors
*/
// allocate memory
void allocvec(int length) {
// length is already done
stor = new storage;
stor->ref = 1;
if (length) {
stor->arr = new T[length];
}
direct_access = stor->arr;
last = 0;
}
// default constructor
tvector() : length(0) {
allocvec(0);
}
// explicit int constructor
tvector(int length) : length(length) {
allocvec(length);
}
// length, value constructor
tvector(int length, int val) : length(length) {
allocvec(length);
for (int i = 0; i < length; i++) {
direct_access[i] = val;
}
}
// generic COW function
void copy(const tvector<T>& other) {
size = other.size;
length = other.length;
stor = other.stor;
stor->ref++;
last = other.last;
}
void grow() {
}
// copy constructor: this has to be smart to do COW
// for CoW all we need to do is increment the ref
tvector(const tvector<T>& other) {
std::cout << "Copy" << std::endl;
copy(other);
}
// iterator based constructor
/*
* Others
*/
const T& val(int i) {
if (i < 0 || i >= length) {
return NULL;
}
return direct_access[i];
}
// deref operator
const T& operator[](int i) {
return val(i);
}
// deref operator
T& operator[](int i) {
// make copy
return val(i);
}
// value at
T& at(int i) {
return val(i);
}
// capacity
int capacity() {
return length;
}
// pop back - this will modify array
T& pop_back() {
// Now we need to make a copy for ourselves first
if (last == 0) {
return NULL;
}
return direct_access[--last];
}
// push back - this will modify array
void push_back(const T& val) {
if (length == last) {
// allocate more (double of last size)
grow();
}
// length should now be more than last
direct_access[last++] = val;
}
// assignment operator
const T& operator=(const tvector<T>& other) {
std::cout << "Assignment" << std::endl;
copy(other);
}
};
}