-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathextensions.hpp
509 lines (423 loc) · 16.4 KB
/
extensions.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/*
* Created by Dmitry Lyssenko
*
* Macro definitions for declaring enums and auto-stringification:
*
* ENUM - will declare enum type w/o any possibility for stringification (mimics enum declaration)
* ENUMSTR - will declare enum type and provide an array of c-strings representing enums
* ENUMSTC - will declare enum type and static declaration (only) of array of c-strings
* STRINGIFY - initialization (stringification) of previously declared enum type with ENUMSTC macro
* STRENM - resolve enum c-string by enum value
*
* trivial macro definitions making enum stringification easy:
* declare enums now in a few simple steps:
* 1. define a macro enlisting all enum items:
*
* #define MY_COLORS \
* Red, \
* Amber, \
* Green
*
* 2. declare enums with ENUM, or ENUMSTR, or ENUMSTC marcos:
*
* ENUMSTR(trafficLightColors, MY_COLORS)
*
* - ENUM macro only declares trafficLightColors of enums (no stringification, mimic enum)
* - ENUMSTR in addition stringifies enums into: const char* trafficLightColors_str[] array
* - ENUMSTC only declares static const char* trafficLightColors_str[] array, so that later
* it could be initialized via STRINGIFY macro.
* ENUMSTC and STRINGIFY must be used in pair, when there's a need to define the array
* with stringified enums as **static**
*
*
* 3. initialize an array of c-strings to generated by ENUMSTC macro (this step is redundant
* if ENUMSTR was used - there stringification occurs within the same macro):
*
* STRINGIFY(SomeClass::trafficLightColors, MY_COLORS)
*
* // or drop the class qualifier if declared not in class:
* STRINGIFY(trafficLightColors, MY_COLORS)
*
* Now, enum trafficLightColors is defined, as well as its c-string representation:
*
* std::cout << "All traffic-light colors:";
* for(int i = 0; i < COUNT_ARGS(MY_COLORS); ++i)
* cout << " "" << SomeClass::trafficLightColors_str[i];
* // or equally: cout << ' ' << STRENM(trafficLightColors, i);
* cout << endl;
*
* Obvious caveat: enums declared that way do not allow value re-definition
* However, consider enum value redefinition a bad programming practice.
* If so required, provide enum-remapping facility instead
*/
#pragma once
#include <string>
#include <vector>
#include <type_traits>
#include <mutex>
#include <tuple>
#include "macrolib.hpp"
#define __COMMA_SEPARATED__(X) X,
#define __STR_COMMA_SEPARATED__(X) #X,
// declare enum from definition
#define ENUM(ENUM_CLASS, ENDEF...) \
enum ENUM_CLASS { MACRO_TO_ARGS(__COMMA_SEPARATED__, ENDEF) };
// declare enum from definition & stringify
#define ENUMSTR(ENUM_CLASS, ENDEF...) \
enum ENUM_CLASS { MACRO_TO_ARGS(__COMMA_SEPARATED__, ENDEF) }; \
const char * ENUM_CLASS ## _str[COUNT_ARGS(ENDEF)] \
{ MACRO_TO_ARGS(__STR_COMMA_SEPARATED__, ENDEF) };
// declare enum from definition & declare static for STRINGIFY
#define ENUMSTC(ENUM_CLASS, ENDEF...) \
enum ENUM_CLASS { MACRO_TO_ARGS(__COMMA_SEPARATED__, ENDEF) }; \
static const char * ENUM_CLASS ## _str[];
// stringification for ENUMSTC
#define STRINGIFY(ENUM_CLASS, ENDEF...) \
const char * ENUM_CLASS ## _str[] { MACRO_TO_ARGS(__STR_COMMA_SEPARATED__, ENDEF) };
// resolve c-string from enum index
#define STRENM(ENUM_CLASS, ENUM_IDX) ENUM_CLASS ## _str[ENUM_IDX]
/*
* A trivial wrapper around std::exception
* - to be used with enum stringification in classes (ENUMSTR, STRINGIFY)
*
* Synopsis:
* // 1. define ENUMSTR within the class, enumerating exception reasons
*
* class myClass {
* public:
* ...
* define THROWREASON
* InvalidInput, \
* IncorrectUsage, \
* WrongType
* ENUMSTR(ThrowReason, THROWREASON)
*
* ...
* EXCEPTION(ThrowReason)
* };
* STRINGIFY(myClass::ThrowReason, THROWREASON)
* #undef THROWREASON
*
*
* // 2. use in throwing defined exception reasons, e.g.:
* throw EXP(InvalidInput);
*
*
* // 3. Possible output upon non-handled exception:
* libc++abi.dylib: terminating with uncaught exception of type myClass::stdException: InvalidInput
*
*
* // 4. define catching exception:
* try { ... } // something producing ThrowReason exception
* catch(myClass::stdException & e) { // or std::exception & e, but then to access code()
* // and where() down-casting is required
* std::cout << "exception string: " << e.what() << std::endl;
* std::cout << "exception code: " << e.code() << std::endl;
* std::cout << "exception in: " << e.where() << std::endl;
* }
*
*/
// return std::exception from classes;
// upon throwing a copy of the object is made (throwing is by value). In our case
// a shallow copy will suffice despite the pointer: the class is meant to be used
// with ENUMSTR / STRINGIFY, which are static data.
// for in-class declaration:
#define EXCEPTIONS(THROW_ENUM) \
class stdException: public std::exception { \
public: \
stdException(void) = delete; \
stdException(int reason, const char *what, \
const char *func, const char *file, int line): \
ec_{reason}, msg_{what}, func_{func}, file_{file}, line_{line} {} \
const char * what(void) const noexcept { return msg_; } \
std::string where(void) const noexcept { \
return std::string{"file: '"} + file_ + \
"', func: '" + func_ + \
"()', line: " + std::to_string(line_); \
} \
const char * func(void) const noexcept { return func_; } \
const char * file(void) const noexcept { return file_; } \
int line(void) const noexcept { return line_; } \
int code(void) const noexcept { return ec_; } \
private: \
int ec_; \
const char * msg_; \
const char * func_; \
const char * file_; \
int line_; \
}; \
stdException __exp__(THROW_ENUM __reason__, const char *__funcname__, \
const char *__filename__, int __line__) const \
{ return stdException{__reason__, STRENM(THROW_ENUM, __reason__), \
__funcname__, __filename__, __line__}; }
// for in-place throw parameter
#define EXP(TROW_REASON) __exp__(TROW_REASON, __func__, __FILE__, __LINE__)
/*
* Following trivial extension facilitates ability to check if a value is in
* enumeration (similar to python's "x in [...]" construct)
*
* Synopsis:
*
* x = 5;
* if(x AMONG(1,2,3,5,6))
* std::cout << "x is in!" << std::endl;
* else
* std::cout << "x is not in!" << std::endl;
*
*
* CAVEAT on usage with c-strings:
* - first parameter in AMONG macros to be type-casted as <const char*>:
*
* const char *x = "abc";
* if(x AMONG(static_cast<const char*>("abc"), "def", "xyz")) ...
*
*
* Preferably use AMONG construct, when number of enlisted arguments > 2, otherwise
* go with conditional 'or'
*/
template<class T>
bool operator==(const T &__a__, std::vector<T> __v__) {
for(auto &x: __v__)
if(x == __a__) return true;
return false;
}
bool operator==(const std::string &__a__, std::vector<const char *> __b__) {
for(auto x: __b__)
if(__a__ == x) return true;
return false;
}
#define AMONG(FIRST, REST...) \
== std::vector<decltype(FIRST)>{FIRST, MACRO_TO_ARGS(__COMMA_SEPARATED__, REST)}
/*
* GUARD is a polymorphic macro allowing preserving and automatically reinstating the
* value of the preserved object accessed either by a reference, or via getters/setters
*
* 1. following GUARD interface provides a guard functionality for an arbitrary objects
* accessible by reference: it will preserve the object value upon interface declaration
* and will restore the object value upon exiting the scope (GUARD's destruction);
*
* Synopsis:
*
* double x = 3.14;
* cout << "x: " << x << endl;
* {
* GUARD(x)
* x = 2.71;
* cout << "x: " << x << endl;
* }
* cout << "x: " << x << endl;
*
* Output:
* x: 3.14
* x: 2.71
* x: 3.14
*
*
* 2. Sometimes classes cater only getter and setter methods to access
* their objects. For such case, this GUARD interface provides a solution:
*
* class MyX {
* public:
* int get(void) const { return x_; }
* void set(int x) { x_ = x; }
* private:
* int x_;
* };
*
* MyX x;
* x.set(123);
* cout << "x: " << x.get() << endl;
* {
* GUARD(x.get, x.set) // spell here object's getter and setter, alternatively
* x.set(-1); // it could be collapsed: into GUARD(x.get, x.set, -1)
* cout << "x: " << x.get() << endl;
* }
* cout << "x: " << x.get() << endl;
*
* Output:
* x: 123
* x: -1
* x: 123
*
*
* in case where's multiple objects to guard, list them one by one each on the
* new line:
* // ...
* GUARD(x)
* GUARD(y)
* // ...
*/
// There are 3 forms of GUARD: for a {single object}, form {getter, setter}
// and form {getter, setter, value}
// Forms demultiplexing occurs in __GUARD_CHOOSER__ macro, which results into
// expanding __GUARD_1_ARG__ for the former case and into __GUARD_2_ARG__ for
// the latter
//
// __GUARD_1_ARG__: declares a trivial class __Guard_X__, which stores object's
// value and its pointer. Restoration of the object's value occurs upon __GUARD_X__'s
// destruction
//
// __GUARD_2_ARG__: declares a child class of __Guard_X__, where it only captures
// the value of the object through its getter (in the constructor of the child class
// xptr_ is getting nullified so that when destroyed the restoration at parent is skipped)
// Restoration of the object is designed through capturing object's setter via lambda
// and calling the lambda (i.e. object's setter effectively) with preserved value
// in the destructor of the child class
//
// __GUARD_3_ARG__: just same as __GUARD_2_ARG__, just sets 3rd parameter (value)
// immediately via setter
//
// Each form of GUARD is appended __LINE__ macro to ensure uniqueness of declarations
// allowing multiple invocations of the macro dodging name clashing
#define __STITCH_2TKNS__(X,Y) X ## Y
#define STITCH_2TKNS(X,Y) __STITCH_2TKNS__(X, Y)
#define __GUARD_1_ARG__(X) \
__Guard_X__<decltype(X)> STITCH_2TKNS(__my_Guard_X__, __LINE__)(X);
#define __GUARD_2_ARG__(X, Y) \
struct STITCH_2TKNS(__Guard_GS__, __LINE__): public __Guard_X__<decltype(X())> { \
/* __Guard_X__ constructor capturing by value from getter(), and setter via lambda */\
STITCH_2TKNS(__Guard_GS__, __LINE__)(decltype(X()) __Guard_X_arg__, \
std::function<void(decltype(X()))> __Guard_X_l__): \
__Guard_X__<decltype(X())>(__Guard_X_arg__), /* capture getter's value in base class */\
lambda{__Guard_X_l__} /* capture lambda, passed in the initializer list */\
{ __Guard_X__<decltype(X())>::xptr_ = nullptr; } /* ensure destructor disengaged */\
~STITCH_2TKNS(__Guard_GS__, __LINE__)(void) \
{ lambda(__Guard_X__<decltype(X())>::x_); }; /* reinstate via setter captured in lambda*/\
std::function<void (decltype(X()))> lambda; \
} STITCH_2TKNS(__my_Guard_GS__, __LINE__) \
{ X(), [&](decltype(X()) __Guard_X_arg__) { Y(__Guard_X_arg__); } };
#define __GUARD_3_ARG__(X, Y, V) \
__GUARD_2_ARG__(X, Y) \
Y(V);
#define __GUARD_4TH_ARG__(ARG1, ARG2, ARG3, ARG4,...) ARG4
#define __GUARD_CHOOSER__(ARGS...) \
__GUARD_4TH_ARG__(ARGS, __GUARD_3_ARG__, __GUARD_2_ARG__, __GUARD_1_ARG__)
#define GUARD(ARGS...) \
__GUARD_CHOOSER__(ARGS)(ARGS)
template <typename T>
class __Guard_X__ {
// Guard class itself
public:
__Guard_X__(void) = delete;
__Guard_X__(typename std::remove_reference<T>::type & __Guard_X_arg__):
x_{__Guard_X_arg__}, xptr_{&__Guard_X_arg__} {}
__Guard_X__(typename std::remove_reference<T>::type && __Guard_X_arg__):
x_{std::move(__Guard_X_arg__)}, xptr_{&__Guard_X_arg__} {}
~__Guard_X__(void) { if(xptr_) *xptr_ = std::move(x_); }
protected:
typename std::remove_reference<T>::type x_;
typename std::remove_reference<T>::type * xptr_;
};
/*
* A trivial SWAP macro facilitating plain `void swap(left, right)` operation:
*
* Synopsis:
* class my_class {
* friend SWAP(my_class, a_, b_, c_)
* ...
* }
*
* The above translates into:
* class my_class {
* friend void swap(my_class &left, my_class &right) {
* using std::swap;
* swap(left.a_, right.a_);
* swap(left.b_, right.b_);
* swap(left.c_, right.c_);
* }
* ...
* }
*
*
* Another COPY macro defying a copy for all enumerated elements: void copy(to, const from)
* - similar to SWAP, but copies by value - to facilitate copying in non-default CC:
*
* Synopsis:
* class my_class {
* COPY(my_class, a_, b_, c_)
* my_class(const my_class &rhs) { // CC
* copy(*this, rhs);
* ...
* }
* ...
* private:
* some_type a_, b_, c_;
* }
*
*/
#define __SWAP_PAIR__(X) swap(__left__.X, __right__.X);
#define SWAP(TYPE, ARGS...) \
void swap(TYPE &__left__, TYPE &__right__) \
{ using std::swap; MACRO_TO_ARGS(__SWAP_PAIR__, ARGS) }
#define __COPY_VAR__(X) __left__.X = __right__.X;
#define COPY(TYPE, ARGS...) \
void copy(TYPE &__left__, const TYPE &__right__) \
{ MACRO_TO_ARGS(__COPY_VAR__, ARGS) }
/*
* A couple of definitions for mutexes:
* ULOCK - declare a unique_lock (mutex sguard)
* TLOCK - declare an operator-like lock
*
* Synopsis:
* {
* ULOCK(mtx)
* ...
* } // mtx will be automatically released
*
* TLOCK(mtx) { // block is executed under mtx
* ...
* }
*
*/
#define ULOCK(MTX) \
std::unique_lock<std::mutex> STITCH_2TKNS(__ulck__, __LINE__){MTX};
#define TLOCK(MTX) \
for(std::unique_lock<std::mutex> __tlck__(MTX); __tlck__.owns_lock(); __tlck__.unlock())
/*
* Sometimes, the code refactoring is required from within the loop, then it's required to
* return flow control code like continue / break / return and none
* - that simple enum defines those in Fc__:
* Fc__::Continue / Fc__::Continue / Fc__::Return / Fc__::None
*
* CBR polymorphic macro handles the return Fc__ codes and the return values as this:
*
* Synopsis:
* CBR(user_func(..)) // user_func() returns only Fc__, thus
* // Fc__::Return returns void
* or,
* CBR(user_func(..)) // user_func() returns tuple<Fc__, ret_val_type>
* // Fc__::Return returns second value of tuple
* or,
* CBR(user_func(..), ret_val) // user_func() returns only Fc__, and
* // Fc__::Return returns rv
*
*/
#define __FC__ \
None, \
Continue, \
Break, \
Return
ENUM(Fc__, __FC__)
#undef __FC__
Fc__ __Fctl_first__(Fc__ fc) { return fc; }
template<typename T>
T __Fctl_first__(const std::tuple<Fc__, T> & tpl) { return std::get<0>(tpl); }
template<typename T>
T __Fctl_second__(const std::tuple<Fc__, T> & tpl) { return std::get<1>(tpl); }
#define __CBR_1_ARG__(RC) \
auto const & __OPSRC__ = (RC); \
if(__Fctl_first__(__OPSRC__) == Fc__::Continue) continue; \
if(__Fctl_first__(__OPSRC__) == Fc__::Break) break; \
if(__Fctl_first__(__OPSRC__) == Fc__::Return) return __Fctl_second__(__OPSRC__);
#define __CBR_2_ARG__(RC, RV) \
auto const & __OPSRC__ = (RC); \
if(__OPSRC__ == Fc__::Continue) continue; \
if(__OPSRC__ == Fc__::Break) break; \
if(__OPSRC__ == Fc__::Return) return RV;
#define __CBR_3RD_ARG__(ARG1, ARG2, ARG3, ...) ARG3
#define __CBR_CHOOSER__(ARGS...) \
__CBR_3RD_ARG__(ARGS, __CBR_2_ARG__, __CBR_1_ARG__)
#define CBR(ARGS...) \
__CBR_CHOOSER__(ARGS)(ARGS)
#define CNT_BRK_RTN(ARGS...) /* longer form of CBR macro */\
__CBR_CHOOSER__(ARGS)(ARGS)