/
eml_common.h
121 lines (97 loc) · 2.42 KB
/
eml_common.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
#ifndef EML_COMMON_H
#define EML_COMMON_H
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
// EmlError
typedef enum _EmlError {
EmlOk = 0,
EmlSizeMismatch,
EmlUnsupported,
EmlUninitialized,
EmlPostconditionFailed,
EmlUnknownError,
EmlErrors,
} EmlError;
static const char *
eml_error_strs[EmlErrors] = {
"OK",
"SizeMismatch",
"Uninitialized",
"Unsupported",
"Postcondition failed",
"Unknown error",
};
bool
eml_error_valid(EmlError e) {
return (e >= EmlOk && e < EmlErrors);
}
const char *
eml_error_str(EmlError e) {
if (eml_error_valid(e)) {
return eml_error_strs[e];
} else {
return "Invalid error code";
}
}
typedef void (*EmlDebugFunction)(EmlError code, const char *file, int line);
#ifdef EML_DEBUG
void eml_debug_stderr(EmlError code, const char *file, int line)
{
const bool log_error = getenv("EML_DEBUG_LOG") != NULL;
const bool fatal_errors = getenv("EML_DEBUG_FATAL_ERRORS") != NULL;
if (log_error) {
const char *err_str = eml_error_str(code);
fprintf(stderr, "EmlError %s at %s:%d \n",
err_str, file, line);
}
if (fatal_errors) {
exit(11);
}
}
static EmlDebugFunction eml_debug = eml_debug_stderr;
#endif
#ifdef EML_DEBUG
#define EML_PRECONDITION(expr, errorcode) \
do { \
if (!(expr)) { \
if (eml_debug) { eml_debug(errorcode, __FILE__, __LINE__); } \
return errorcode; \
} \
} while (0);
// Return errorcode if expr not satisfied
#define EML_POSTCONDITION(expr, errorcode) \
do { \
if (!(expr)) { \
if (eml_debug) { eml_debug(errorcode, __FILE__, __LINE__); } \
return errorcode; \
} \
} while (0);
#else // EML_DEBUG
// Return errorcode if expr not satisfied
#define EML_PRECONDITION(expr, errorcode) \
do { \
if (!(expr)) { \
return errorcode; \
} \
} while (0);
// Return errorcode if expr not satisfied
#define EML_POSTCONDITION(expr, errorcode) \
do { \
if (!(expr)) { \
return errorcode; \
} \
} while (0);
#endif // EML_DEBUG
// Return if expr gives error
#define EML_CHECK_ERROR(expr) \
do { \
const EmlError _e = (expr); \
if (_e != EmlOk) { \
return _e; \
} \
} while (0);
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#endif // EML_COMMON_H