-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexed_types.hpp
411 lines (374 loc) · 10.2 KB
/
indexed_types.hpp
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/**
* @file indexed_types.h
* @author Jens Munk Hansen <[email protected]>
* @date Thu June 02 18:14:44 2009
*
* @brief Generic indexed types. It is not thread safe, so in a
* threaded environment it is adviced to extend this class
* with a custom deleter, which is thread safe
*
*
*/
/*
* This file is part of SOFUS.
*
* SOFUS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SOFUS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SOFUS. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
// C headers
#include <sps/cstdio>
#include <sps/cstdlib>
#include <cstdint>
#include <cstring>
// C++ headers
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <sps/typeinfo>
namespace sps {
/**
* Indexed types by means of custom auto-pointer and garbage
* collector. The allocation takes place outside this manager to
* allow the possibility for using a shared memory segment.
*
* Usage example:
*
* class A {
* public:
* A() {
* data = shared_ptr<int>(new int(2));
* } }
* #ifdef _INDEXED_TYPES_CLONEABLE
* A* clone() const {
* A* out = new A(*this);
* out->data = shared_ptr<int>(new int(*this->data.get()));
* return out;
* }
* #endif
* private:
* shared_ptr<int> data;
* };
*
* A* pA = new A();
*
* // Remove ownership
* indexed_type_index i = create_handle<A>(pA); // pA is now NULL
*
* // Get object
* pA = &(get_object<A>(i));
*
* // Use object through pointer
* *pA->data = 5;
*
* // Clone object - note A may contain shared_ptr's
* indexed_type_index j = clone_object<A>(i);
*
* // Destroy objects
* destroy_object<A>(i);
* destroy_object<A>(j);
*/
/// Cross-platform index
typedef uint64_t indexed_type_index;
/// Forward declaration of indexed_auto_ptr_collector
template<typename T> class indexed_auto_ptr_collector;
/**
* Indexed auto pointer, which take ownership and delete the object
* when it is destroyed. Be sure not to delete any aliases to the
* object argument used in the ctor.
*
*/
template <typename T>
class indexed_auto_ptr {
public:
/**
* Ctor, note the ownership cannot be taken instantly
*
* @param ptr
*/
#ifdef SPS_TYPE_ID_NAME
explicit indexed_auto_ptr(T*& ptr) : type(typeid(T).name()), t(ptr) {
#else
explicit indexed_auto_ptr(T*& ptr) : type(&typeid(T)), t(ptr) {
#endif
signature = this;
indexed_auto_ptr_collector<T>::register_handle(this);
ptr = 0;
}
/**
* Dtor
*
*/
~indexed_auto_ptr() {
delete t; // destroy object
signature = NULL; // destroy signature
}
/**
* Convert index to an indexed_auto_ptr<T>.
*
* @param index
*
* @return
*
* @throw std::runtime_error
*/
static indexed_auto_ptr* from_index(const indexed_type_index index );
/**
* Convert indexed_auto_ptr<T> to an index.
*
*
* @return
*/
indexed_type_index to_index();
/**
* Get the actual object contained by handle
*
*
* @return
*/
T& get_object() const {
return *t;
}
private:
/// used as a unique object signature
indexed_auto_ptr* signature;
/// type checkig information
base_id_t type;
/// object pointer
T *t;
/// Collector
friend class indexed_auto_ptr_collector<T>;
};
namespace types {
/**
\defgroup IndexedAutoPtr helper functions
@{
*/
/**
* Create integer handle for object
*
* @param t The object
*
* @return
*/
template <typename T> indexed_type_index create_handle(T* t) {
indexed_auto_ptr<T>* handle = new indexed_auto_ptr<T>(t);
return handle->to_index();
}
/**
* Obtain object represented by handle.
*
* @param index
*
* @throw std::runtime_error
*
* @return
*/
template <typename T> T& get_object(const indexed_type_index index) {
indexed_auto_ptr<T>* handle = indexed_auto_ptr<T>::from_index(index);
return handle->get_object();
}
/**
* Destroy object. If deleting object, rather than leaving it to
* garbage collection, you must delete it via the handle; do not
* delete T* directly.
*
* @param index
*
* @throw std::runtime_error
*/
template <typename T> void destroy_object(const indexed_type_index index) {
indexed_auto_ptr<T>* handle = indexed_auto_ptr<T>::from_index(index);
// If no exception is thrown using from_index at index, it is okay to
// reset the pointer
indexed_auto_ptr_collector<T>::objvector[index] = nullptr;
delete handle;
}
#ifdef _INDEXED_TYPES_CLONEABLE
/**
* Clone object using index - not possible since T may contain
* shared_ptr and C++ does not support reflection (without using
* macros and templates). The solution is to require T to implement:
*
* T* T::clone() const;
*
* @param index
*
* @return
*
* @throw std::runtime_error
*/
template <typename T>
indexed_type_index clone_object(const indexed_type_index index) {
indexed_auto_ptr<T>* curHandle = indexed_auto_ptr<T>::from_index(index);
T* clone = curHandle->get_object().clone();
indexed_auto_ptr<T>* newHandle = new indexed_auto_ptr<T>(clone);
return newHandle->to_index();
}
#endif
//@}
} // namespace types
/**
* Name:
* indexed_auto_ptr_collector
*
* Description:
* - Indexed collector singleton (one collector object for each type
T). Ensures that registered handles are deleted when the library
is released (they may also be deleted before that without
problems).
*
*/
template <typename T>
class indexed_auto_ptr_collector {
public:
static std::vector<indexed_auto_ptr<T>*> objvector;
/**
* Destructor
*
*/
~indexed_auto_ptr_collector() {
size_t nObjectsCleared = 0;
typename std::vector<indexed_auto_ptr<T>*>::iterator i;
typename std::vector<indexed_auto_ptr<T>*>::iterator end = objvector.end();
for (i = objvector.begin(); i != end ; ++i) {
if (*i) {
// check for valid signature
if ((*i)->signature == *i) {
delete *i;
nObjectsCleared++;
}
}
}
#ifdef DEBUG
if (nObjectsCleared) {
fprintf(stdout, "Garbage collector: ");
fprintf(stdout, "Cleared %zu %s item(s)\n",
nObjectsCleared, this->objname);
}
#endif
}
/**
* Register handle
*
* @param obj
*/
static void register_handle(indexed_auto_ptr<T>* obj) {
// Singleton - one for each type
static indexed_auto_ptr_collector singleton(obj);
typename std::vector<indexed_auto_ptr<T>*>::iterator i;
typename std::vector<indexed_auto_ptr<T>*>::iterator end = objvector.end();
i = std::find(objvector.begin(), objvector.end(), nullptr);
if (i != end) {
(*i) = obj;
} else {
singleton.objvector.push_back(obj);
}
}
private:
/// Name
char objname[256];
/**
* Private ctor (prevent construction)
*
* @param obj
*/
explicit indexed_auto_ptr_collector(indexed_auto_ptr<T>* obj) {
char buffer[128];
// buffer is always terminated
#ifdef SPS_TYPE_ID_NAME
snprintf(buffer, sizeof(buffer), "%zu", strlen(obj->type));
#else
snprintf(buffer, sizeof(buffer), "%zu", strlen(obj->type.name()));
#endif
#if defined(__GNUC__)
// GNU use the length followed by the name
strncpy(objname, obj->type + strlen(buffer), sizeof(objname));
#elif defined(_MSC_VER)
// Microsoft have 6 extra characters in names
strncpy(objname, obj->type + 6, sizeof(objname));
#endif
// strncpy does not terminate if source is larger than destination
objname[sizeof(objname)-1] = '\0';
}
/**
* Private copy-ctor (prevent construction)
*
*/
indexed_auto_ptr_collector(const indexed_auto_ptr_collector&);
};
/// Explicit instantiation
template <typename T>
std::vector<indexed_auto_ptr<T>*> indexed_auto_ptr_collector<T>::objvector;
template <typename T>
indexed_auto_ptr<T>*
indexed_auto_ptr<T>::from_index(const indexed_type_index index) {
// Find object in static vector
indexed_auto_ptr* obj = NULL;
if (index < indexed_auto_ptr_collector<T>::objvector.size()) {
if (indexed_auto_ptr_collector<T>::objvector[index] != nullptr) {
obj = indexed_auto_ptr_collector<T>::objvector[index];
}
}
if (!obj) {
// Check to see we don"t have an invalid pointer
fprintf(stderr,
"Parameter is NULL. It does not represent an " \
"indexed_auto_ptr object.\n");
throw std::runtime_error("indexed_auto_ptr<T>::from_index");
}
if ( !( ((uintptr_t) obj) < UINTPTR_MAX) ) {
fprintf(stderr, "Pointer value of of range");
throw std::runtime_error("indexed_auto_ptr<T>::from_index");
}
// Check memory has correct signature
if (obj->signature != obj) {
fprintf(stderr,
"Parameter does not represent an indexed_auto_ptr object.\n");
throw std::runtime_error("indexed_auto_ptr<T>::from_index");
}
#ifdef SPS_TYPE_ID_NAME
if (strcmp(obj->type, typeid(T).name()) != 0) {
fprintf(stderr, "Given: <%s>, Required: <%s>.\n", obj->type,
typeid(T).name());
#else
if (*(obj->type) != typeid(T)) {
fprintf(stderr, "Given: <%s>, Required: <%s>.\n", obj->type->name(),
typeid(T).name());
#endif
fprintf(stderr,
"Given indexed_auto_ptr does not represent the correct type.\n");
throw std::runtime_error("indexed_auto_ptr<T>::from_index");
#ifdef SPS_TYPE_ID_NAME
}
#else
}
#endif
return obj;
}
template <typename T>
indexed_type_index indexed_auto_ptr<T>::to_index() {
// Find pointer in vector
auto it = find(indexed_auto_ptr_collector<T>::objvector.begin(),
indexed_auto_ptr_collector<T>::objvector.end(), this);
if (it != indexed_auto_ptr_collector<T>::objvector.end()) {
return indexed_type_index(
std::distance(
indexed_auto_ptr_collector<T>::objvector.begin(),
it));
} else {
fprintf(stderr, "Invalid index.\n");
throw std::runtime_error("indexed_auto_ptr<T>::to_index");
}
}
} // namespace sps