forked from RisingTyde/integrity-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintegrity.h
517 lines (467 loc) · 21.4 KB
/
integrity.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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
#pragma once
#include <functional>
#include <string>
#include <stdexcept>
#include <vector>
#include <sstream>
#include <iomanip> // for the string formating functions like setfill
#include <cstring>
#include <cmath>
/*
* Notes
* Compiler does not allow default arguments on function templates
* Has to be in a namespace not in a class otherwise g++ does not compile it
*/
namespace Integrity {
static const char* VERSION = "1.0.0";
static constexpr const char* defaultExceptionMessage = "Integrity check failed";
static constexpr const char* defaultNullPointerMessage = "Null pointer";
static constexpr const char* defaultEmptyStringMessage = "Empty string";
enum class DispType;
struct TypeValue;
static std::string makeString(const char* defaultMessage, const std::vector<TypeValue>& items);
static std::string makeString(const std::function<void(std::stringstream&)>& messageFunc);
static void throwWithMessage(const char* defaultMessage, const std::vector<Integrity::TypeValue>& items);
template<typename T> static const char* getFloatAppropriateMessage(T value);
template<typename T> TypeValue toTypeValue(T primitive);
using out = std::stringstream &;
class NonType {
private:
NonType() {};
public:
static NonType& Singleton()
{
static NonType Singleton;
return Singleton;
}
};
// ******************************************************************************************************************
// * -------------------------------------------------- check------------------------------------------------------ *
// ******************************************************************************************************************
/// <summary>
/// Checks whether a condition is true, if not raises a logic_error with default message
/// </summary>
/// <param name="condition">The condition to check is true.</param>
/// <exception cref="logic_error">Raised if condition is false</exception>
inline void check(bool condition) {
if (!condition) {
throw std::logic_error(defaultExceptionMessage);
}
}
/// <summary>
/// Checks whether a condition is true, if not raises a logic_error with given message
/// </summary>
/// <param name="condition">The condition to check is true.</param>
/// <exception cref="logic_error">Raised if condition is false</exception>
inline void check(bool condition, const char* message) {
if (!condition) {
throw std::logic_error(message);
}
}
/// <summary>
/// Placeholder to prevent non-bool being passed in as first parameter.
/// </summary>
/// <param name="youNeedABool">Did you accidentally do = instead of ==?</param>
/// <remarks>If this is not here then common errors like check(a = b) instead of check(a == b) do not get caught by compiler</remarks>
template<typename NONBOOL, typename M1 = NonType, typename M2 = NonType, typename M3 = NonType, typename M4 = NonType>
inline void check(NONBOOL youNeedABoolHere, M1 m1 = NonType::Singleton(), M2 m2 = NonType::Singleton(), M3 m3 = NonType::Singleton(), M4 m4 = NonType::Singleton()) = delete;
/// <summary>
/// Checks whether a condition is true, if not raises a logic_error
/// </summary>
/// <param name="condition">The condition to check is true.</param>
/// <param name="M1">Optional string or primitive</param>
/// <param name="M2">Optional string or primitive</param>
/// <param name="M3">Optional string or primitive</param>
/// <param name="M4">Optional string or primitive</param>
/// <exception cref="logic_error">Raised if condition is false</exception>
template<typename M1 = NonType, typename M2 = NonType, typename M3 = NonType, typename M4 = NonType>
inline void check(bool condition, M1 m1 = NonType::Singleton(), M2 m2 = NonType::Singleton(), M3 m3 = NonType::Singleton(), M4 m4 = NonType::Singleton()) {
if (!condition) {
throwWithMessage(defaultExceptionMessage, { toTypeValue(m1), toTypeValue(m2), toTypeValue(m3), toTypeValue(m4) });
}
}
template<typename B> inline void checkM(B condition, const std::function<void(std::stringstream&)>& messageFunc)=delete;
/// <summary>
/// Checks whether a condition is true, if not raises a logic_error where you can pass a lambda function to build the message
/// </summary>
/// <param name="condition">The condition to check is true.</param>
/// <param name="messageFunc">Example: [=](Integrity::out out) { out << whateverYouWant; }</param>
/// <exception cref="logic_error">Raised if condition is false</exception>
/// <remarks>
/// This function exists so that you can control the deferred message building by passing in a lambda function which is called if the condition fails.
/// </remarks>
template<> inline void checkM<bool>(bool condition, const std::function<void(std::stringstream&)>& messageFunc) {
if (!condition) {
throw std::logic_error(makeString(messageFunc));
}
}
// ******************************************************************************************************************
// * -------------------------------------------------- fail ------------------------------------------------------ *
// ******************************************************************************************************************
/// <summary>
/// Raises a logic_error with a default message
/// </summary>
/// <exception cref="logic_error"></exception>
inline void fail() {
throw std::logic_error(defaultExceptionMessage);
}
inline void fail(const char* message) {
throw std::logic_error(message);
}
/// <summary>
/// Raises a logic_error where you can pass a lambda function to build the message
/// </summary>
/// <param name="messageFunc">Example: [=](Integrity::out out) { out << whateverYouWant; }</param>
/// <exception cref="logic_error">Raised if condition is false</exception>
/// <remarks>
/// This function exists so that you can control the deferred message building by passing in a lambda function which is called if the condition fails.
/// </remarks>
inline void failM(const std::function<void(std::stringstream&)>& messageFunc) {
throw std::logic_error(makeString(messageFunc));
}
/// <summary>
/// Raises a logic_error
/// </summary>
/// <param name="M1">Optional string or primitive</param>
/// <param name="M2">Optional string or primitive</param>
/// <param name="M3">Optional string or primitive</param>
/// <param name="M4">Optional string or primitive</param>
/// <exception cref="logic_error"></exception>
template<typename M1 = NonType, typename M2 = NonType, typename M3 = NonType, typename M4 = NonType>
inline void fail(const M1& m1 = NonType::Singleton(), const M2& m2 = NonType::Singleton(), const M3& m3 = NonType::Singleton(), const M4& m4 = NonType::Singleton()) {
throwWithMessage(defaultExceptionMessage, { toTypeValue(m1), toTypeValue(m2), toTypeValue(m3), toTypeValue(m4) });
}
// ******************************************************************************************************************
// * -------------------------------------- checkIsValidNumber ---------------------------------------------------- *
// ******************************************************************************************************************
template<typename N>
inline void checkIsValidNumber(const N value, const char* message) {
if (std::isnan(value) || std::isinf(value)) {
throw std::logic_error(message);
}
}
/// <summary>
/// Raises a logic_error if the number is NaN or +-Infinity
/// </summary>
/// <param name="value">float, double or long double</param>
/// <param name="M1">Optional string or primitive</param>
/// <param name="M2">Optional string or primitive</param>
/// <param name="M3">Optional string or primitive</param>
/// <param name="M4">Optional string or primitive</param>
/// <exception cref="logic_error"></exception>
template<typename N, typename M1 = NonType, typename M2 = NonType, typename M3 = NonType, typename M4 = NonType>
inline void checkIsValidNumber(const N value, const M1& m1 = NonType::Singleton(), const M2& m2 = NonType::Singleton(), const M3& m3 = NonType::Singleton(), const M4& m4 = NonType::Singleton()) {
if (std::isnan(value) || std::isinf(value)) {
const char* defaultMessage = getFloatAppropriateMessage(value);
throwWithMessage(defaultMessage, { toTypeValue(m1), toTypeValue(m2), toTypeValue(m3), toTypeValue(m4) });
}
}
/// <summary>
/// Raises a logic_error if the number is NaN or +-Infinity
/// </summary>
/// <param name="value">float, double or long double</param>
/// <param name="messageFunc">Example: [=](Integrity::out out) { out << whateverYouWant; }</param>
/// <exception cref="logic_error"></exception>
/// <remarks>
/// This function exists so that you can control the deferred message building by passing in a lambda function which is called if the condition fails.
/// </remarks>
template<typename N>
inline void checkIsValidNumberM(const N value, const std::function<void(std::stringstream&)>& messageFunc) {
if (std::isnan(value) || std::isinf(value)) {
throw std::logic_error(makeString(messageFunc));
}
}
// ******************************************************************************************************************
// * ---------------------------------------------- checkNotNull -------------------------------------------------- *
// ******************************************************************************************************************
/// <summary>
/// Raises a logic_error if the pointer is null (i.e. 0)
/// </summary>
/// <param name="pointer">a pointer to check for nullness</param>
/// <exception cref="logic_error">message will be 'Null pointer'</exception>
inline void checkNotNull(const void* pointer) {
if (pointer == nullptr) {
throw std::logic_error("Null pointer");
}
}
/// <summary>
/// Raises a logic_error if the pointer is null (i.e. 0)
/// </summary>
/// <param name="pointer">a pointer to check for nullness</param>
/// <param name="message">message to use in the exception</param>
/// <exception cref="logic_error"></exception>
inline void checkNotNull(const void* pointer, const char* message) {
if (pointer == nullptr) {
throw std::logic_error(message);
}
}
/// <summary>
/// Raises a logic_error if the pointer is null (i.e. 0)
/// </summary>
/// <param name="pointer">a pointer to check for nullness</param>
/// <param name="M1">Optional string or primitive</param>
/// <param name="M2">Optional string or primitive</param>
/// <param name="M3">Optional string or primitive</param>
/// <param name="M4">Optional string or primitive</param>
/// <exception cref="logic_error"></exception>
template<typename M1 = NonType, typename M2 = NonType, typename M3 = NonType, typename M4 = NonType>
inline void checkNotNull(const void* pointer, const M1 & m1 = NonType::Singleton(), const M2 & m2 = NonType::Singleton(), const M3 & m3 = NonType::Singleton(), const M4 & m4 = NonType::Singleton()) {
if (pointer == nullptr) {
throwWithMessage(defaultNullPointerMessage, { toTypeValue(m1), toTypeValue(m2), toTypeValue(m3), toTypeValue(m4) });
}
}
/// <summary>
/// Raises a logic_error if the pointer is null (i.e. 0)
/// </summary>
/// <param name="pointer">a pointer to check for nullness</param>
/// <param name="messageFunc">Example: [=](Integrity::out out) { out << whateverYouWant; }</param>
/// <exception cref="logic_error"></exception>
/// <remarks>
/// This function exists so that you can control the deferred message building by passing in a lambda function which is called if the condition fails.
/// </remarks>
inline void checkNotNullM(const void* pointer, std::function<void(std::stringstream&)> messageFunc) {
if (pointer == nullptr) {
throw std::logic_error(makeString(messageFunc));
}
}
// ******************************************************************************************************************
// * ---------------------------------------- checkStringNotNullOrEmpty ------------------------------------------- *
// ******************************************************************************************************************
/// <summary>
/// Checks whether a string is null or zero length.
/// </summary>
/// <param name="s">The (wstring, std::string, u16string, u32string) to check for zero length.</param>
/// <exception cref="logic_error">Raised if s is empty</exception>
/// <remarks>
/// Note that an exception is only raised if the string has exactly zero length; a string with a single space (for example) would be fine
/// </remarks>
template<typename M1 = NonType, typename M2 = NonType, typename M3 = NonType, typename M4 = NonType>
inline void checkStringNotNullOrEmpty(const char* s, const M1& m1 = NonType::Singleton(), const M2& m2 = NonType::Singleton(), const M3& m3 = NonType::Singleton(), const M4& m4 = NonType::Singleton()) {
if (s == nullptr) {
throwWithMessage(defaultNullPointerMessage, { toTypeValue(m1), toTypeValue(m2), toTypeValue(m3), toTypeValue(m4) });
} else if(std::strlen(s) == 0) {
throwWithMessage(defaultEmptyStringMessage, { toTypeValue(m1), toTypeValue(m2), toTypeValue(m3), toTypeValue(m4) });
}
}
template<typename M1 = NonType, typename M2 = NonType, typename M3 = NonType, typename M4 = NonType>
inline void checkStringNotNullOrEmpty(char* s, const M1& m1 = NonType::Singleton(), const M2& m2 = NonType::Singleton(), const M3& m3 = NonType::Singleton(), const M4& m4 = NonType::Singleton()) {
if (s == nullptr) {
throwWithMessage(defaultNullPointerMessage, { toTypeValue(m1), toTypeValue(m2), toTypeValue(m3), toTypeValue(m4) });
}
else if (std::strlen(s) == 0) {
throwWithMessage(defaultEmptyStringMessage, { toTypeValue(m1), toTypeValue(m2), toTypeValue(m3), toTypeValue(m4) });
}
}
template<typename S, typename M1 = NonType, typename M2 = NonType, typename M3 = NonType, typename M4 = NonType>
inline void checkStringNotNullOrEmpty(const S& s, const M1& m1 = NonType::Singleton(), const M2& m2 = NonType::Singleton(), const M3& m3 = NonType::Singleton(), const M4& m4 = NonType::Singleton()) {
// If you get a compiler error like: left of .empty must have class/struct/union
// in the line below, then you have not passed a string as firt param to checkStringNotNullOrEmpty
if (s.empty()) {
throwWithMessage(defaultEmptyStringMessage, { toTypeValue(m1), toTypeValue(m2), toTypeValue(m3), toTypeValue(m4) });
}
}
template<typename S, typename M1 = NonType, typename M2 = NonType, typename M3 = NonType, typename M4 = NonType>
inline void checkStringNotNullOrEmpty(S* s, const M1& m1 = NonType::Singleton(), const M2& m2 = NonType::Singleton(), const M3& m3 = NonType::Singleton(), const M4& m4 = NonType::Singleton()) {
if (s == 0) {
throwWithMessage(defaultNullPointerMessage, { toTypeValue(m1), toTypeValue(m2), toTypeValue(m3), toTypeValue(m4) });
} else if (s->empty()) {
throwWithMessage(defaultEmptyStringMessage, { toTypeValue(m1), toTypeValue(m2), toTypeValue(m3), toTypeValue(m4) });
}
}
inline void checkStringNotNullOrEmptyM(const char* s, const std::function<void(std::stringstream&)>& messageFunc) {
if (s == 0 || std::strlen(s) == 0) {
throw std::logic_error(makeString(messageFunc));
}
}
template <typename S>
inline void checkStringNotNullOrEmptyM(const S& s, const std::function<void(std::stringstream&)>& messageFunc) {
if (s.empty()) {
throw std::logic_error(makeString(messageFunc));
}
}
template <typename S>
inline void checkStringNotNullOrEmptyM(const S* s, const std::function<void(std::stringstream&)>& messageFunc) {
if (s == 0 || s->empty()) {
throw std::logic_error(makeString(messageFunc));
}
}
// "private" functions... -----------------------------------------------------------------------------------------------
enum class DispType {
isBool,
isString, // std::string, std::wstring, std::u16string, std::u32string
isCharStar,
isNumber, // short, int, long, long long & unsigned variants, and float, double and long double
isChar,
nonType, // placeholder for when no message argument was passed in
};
struct TypeValue {
DispType type;
std::string value;
TypeValue(DispType theType, const std::string& theValue) {
type = theType;
value = theValue;
}
std::string representationImplyingType() {
switch (this->type) {
case DispType::isBool:
return this->value; // will be True or False
case DispType::isChar:
return "'" + this->value + "'"; // use ' to imply char
case DispType::isString:
return "\"" + this->value + "\""; // use ' to imply string
case DispType::isCharStar:
return "`" + this->value + "`"; // use ` (backtick) to imply char*
case DispType::isNumber:
return this->value; // ints, longs, floats etc. are all just represented as their value
default:
return "Invalid DispType";
}
}
};
static std::string makeString(const char* defaultMessage, const std::vector<TypeValue>& items) {
std::string retString = "";
bool atLeastOne = false;
for (TypeValue item : items) {
if (item.type == DispType::nonType) {
continue;
}
atLeastOne = true;
std::size_t braces = retString.find("{}");
if (braces != std::string::npos) {
retString = retString.replace(braces, 2, item.value);
}
else {
std::string asString;
// if the first message argument was a char* then don't stick any quotes around it...
if (retString.length() == 0 && item.type == Integrity::DispType::isCharStar) {
asString = item.value;
}
else {
asString = item.representationImplyingType();
}
if (retString.length() == 0) {
retString = asString;
}
else {
retString = retString + ", " + asString;
}
}
}
if (!atLeastOne) {
return defaultMessage;
}
return retString;
}
static std::string makeString(const std::function<void(std::stringstream&)>& messageFunc) {
if (messageFunc == nullptr) {
return defaultExceptionMessage;
}
try {
std::stringstream ss;
messageFunc(ss);
return ss.str();
}
catch (...) {
return std::string(defaultExceptionMessage) + ": [error]";
}
}
template<typename T> inline TypeValue toTypeValue(T primitive) {
return TypeValue(DispType::isNumber, std::to_string(primitive));
}
template<> inline TypeValue toTypeValue<NonType>(NonType value) {
return TypeValue(DispType::nonType, "");
}
template<> inline TypeValue toTypeValue<bool>(const bool value) {
return TypeValue(DispType::isBool, value ? "True" : "False");
}
template<> inline TypeValue toTypeValue<char>(const char value) {
return TypeValue(DispType::isChar, std::string(1, value));
}
template<> inline TypeValue toTypeValue<unsigned char>(const unsigned char value) {
return TypeValue(DispType::isChar, std::string(1, value));
}
template<> inline TypeValue toTypeValue<char16_t>(const char16_t value) {
std::stringstream ss;
if (value > 0xff) {
ss << "0x" << std::hex << std::setfill('0') << std::setw(2 * sizeof(char16_t)) << std::uppercase << (long) value;
}
else {
ss << (char) value;
}
return TypeValue(DispType::isChar, ss.str());
}
template<> inline TypeValue toTypeValue<char32_t>(const char32_t value) {
std::stringstream ss;
if (value > 0xff) {
ss << "0x" << std::hex << std::setfill('0') << std::setw(2 * sizeof(char32_t)) << std::uppercase << (long) value;
}
else {
ss << (char) value;
}
return TypeValue(DispType::isChar, ss.str());
}
template<> inline TypeValue toTypeValue<wchar_t>(const wchar_t value) {
std::stringstream ss;
if (value > 0xff) {
ss << "0x" << std::hex << std::setfill('0') << std::setw(2 * sizeof(wchar_t)) << std::uppercase << (long) value;
}
else {
ss << (char) value;
}
return TypeValue(DispType::isChar, ss.str());
}
inline TypeValue toTypeValue(const std::string& value) {
return TypeValue(DispType::isString, value);
}
// string conversions...
/*
* see https://dbj.org/c17-codecvt-deprecated-panic/
*/
template<typename F> inline std::string toStdString(F str) {
if (str.empty())
return {};
return { std::begin(str), std::end(str) };
};
template<> inline TypeValue toTypeValue<std::wstring>(std::wstring value) {
return TypeValue(DispType::isString, toStdString(value));
}
template<> inline TypeValue toTypeValue<std::u16string>(std::u16string value) {
return TypeValue(DispType::isString, toStdString(value));
}
template<> inline TypeValue toTypeValue<std::u32string>(std::u32string value) {
return TypeValue(DispType::isString, toStdString(value));
}
template<> inline TypeValue toTypeValue<const char*>(const char* str) {
return TypeValue(DispType::isCharStar, std::string(str));
}
/*
* It is tempting to have a specialisation for T* (i.e. any pointer) which prints out the
* address of the pointer, but actually having the memory address of a pointer is not very
* helpful, and it is more likely that the developer intended to print the value of the
* item being pointed to. (So for example if the have an int* they probably want to print the
* value of the int rather than the memory address). By not having a T* specialisation then the
* developer will get a compile error if they don't dereference the pointer (which is probably
* better)
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function"
static void throwWithMessage(const char* defaultMessage, const std::vector<Integrity::TypeValue>& items) {
std::string exceptionMessage = makeString(defaultMessage, items);
throw std::logic_error(exceptionMessage);
}
#pragma GCC diagnostic pop
template<typename T> static const char* getFloatAppropriateMessage(T value) {
if (std::isnan(value)) {
return "NaN";
}
if (std::isinf(value)) {
if (value > 0) {
return "+Infinity";
}
else {
return "-Infinity";
}
}
return "Error: expected invalid float";
}
}