-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresult.h
More file actions
517 lines (438 loc) · 17.3 KB
/
result.h
File metadata and controls
517 lines (438 loc) · 17.3 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
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
517
#ifndef RESULT_H
#define RESULT_H
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdnoreturn.h>
#include <errno.h>
#include <stdatomic.h>
#include <stdarg.h>
#include <string.h>
// ============= Configuration =============
#ifndef RESULT_ERROR_POOL_SIZE
#define RESULT_ERROR_POOL_SIZE 256
#endif
#ifndef RESULT_ERROR_MESSAGE_POOL_SIZE
#define RESULT_ERROR_MESSAGE_POOL_SIZE 8192
#endif
#ifndef RESULT_MAX_ERROR_MESSAGE_LEN
#define RESULT_MAX_ERROR_MESSAGE_LEN 128
#endif
#ifndef TRUNC_INDICATOR
#define TRUNC_INDICATOR "..."
#endif
// Uncomment the following line to globally enable color in `print_error_chain`
// #define RESULT_FEATURE_COLOR
#ifdef RESULT_FEATURE_COLOR
#define _RESULT_COLOR_RED "\x1b[38;2;233;62;67m" // rgb(233, 62, 67)
#define _RESULT_COLOR_ORANGE "\x1b[38;2;255;171;112m" // rgb(255, 171, 112)
#define _RESULT_COLOR_YELLOW "\x1b[38;2;255;210;66m" // rgb(255, 210, 66)
#define _RESULT_COLOR_GREEN "\x1b[38;2;171;225;91m" // rgb(171, 225, 91)
#define _RESULT_COLOR_BLUE "\x1b[38;2;121;184;255m" // rgb(121, 184, 255)
#define _RESULT_COLOR_PURPLE "\x1b[38;2;173;138;162m" // rgb(173, 138, 162)
#define _RESULT_COLOR_GREY "\x1b[38;2;103;112;122m" // rgb(103, 112, 122)
#define _RESULT_COLOR_RESET "\x1b[0m"
#else
#define _RESULT_COLOR_RED ""
#define _RESULT_COLOR_ORANGE ""
#define _RESULT_COLOR_YELLOW ""
#define _RESULT_COLOR_GREEN ""
#define _RESULT_COLOR_BLUE ""
#define _RESULT_COLOR_PURPLE ""
#define _RESULT_COLOR_GREY ""
#define _RESULT_COLOR_RESET ""
#endif
// ============= Panic Handling =============
#ifndef PANIC
_Noreturn static inline void _panic_internal(const char *msg, const char *file, int line) {
fprintf(stderr, "PANIC: %s (%s:%d)\n", msg, file, line);
abort();
}
#define PANIC(msg) _panic_internal(msg, __FILE__, __LINE__)
#endif
// ============= Error Handling =============
typedef struct Error {
int domain_id;
const char *domain_name;
int raw_code;
int type_code;
const char *message;
const struct Error *cause;
const char *file;
int line;
const char *func;
} Error;
typedef struct {
int raw_code;
int type_code;
const char *message;
} ErrorInfo;
typedef struct {
int domain_id;
const char *domain_name;
const ErrorInfo *errors;
size_t error_count;
} ErrorDomain;
static Error result_error_pool[RESULT_ERROR_POOL_SIZE];
static _Atomic size_t result_error_pool_index = 0;
static char result_error_message_pool[RESULT_ERROR_MESSAGE_POOL_SIZE];
static _Atomic size_t result_error_message_pool_index = 0;
static inline const Error *_result_error_new(
const Error *cause, const ErrorDomain *domain, int err_code,
const char *file, int line, const char *func
) {
size_t index = atomic_fetch_add(&result_error_pool_index, 1);
Error *new_err = &result_error_pool[index % RESULT_ERROR_POOL_SIZE];
new_err->domain_id = domain->domain_id;
new_err->domain_name = domain->domain_name;
new_err->raw_code = domain->errors[err_code].raw_code;
new_err->type_code = err_code;
new_err->message = domain->errors[err_code].message;
new_err->cause = cause;
new_err->file = file;
new_err->line = line;
new_err->func = func;
return new_err;
}
static inline const Error *_result_error_new_fmt(
const Error *cause, const ErrorDomain *domain, int err_code,
const char *file, int line, const char *func, const char *format, ...
) {
size_t msg_index = atomic_fetch_add(&result_error_message_pool_index, RESULT_MAX_ERROR_MESSAGE_LEN);
char *msg_buffer = &result_error_message_pool[msg_index % RESULT_ERROR_MESSAGE_POOL_SIZE];
va_list args;
va_start(args, format);
int required_len = vsnprintf(msg_buffer, RESULT_MAX_ERROR_MESSAGE_LEN, format, args);
va_end(args);
if (required_len >= RESULT_MAX_ERROR_MESSAGE_LEN) {
const size_t trunc_indicator_len = sizeof(TRUNC_INDICATOR) - 1;
size_t start_pos = RESULT_MAX_ERROR_MESSAGE_LEN - trunc_indicator_len - 1;
memcpy(msg_buffer + start_pos, TRUNC_INDICATOR, trunc_indicator_len + 1);
}
size_t index = atomic_fetch_add(&result_error_pool_index, 1);
Error *new_err = &result_error_pool[index % RESULT_ERROR_POOL_SIZE];
new_err->domain_id = domain->domain_id;
new_err->domain_name = domain->domain_name;
new_err->raw_code = domain->errors[err_code].raw_code;
new_err->type_code = err_code;
new_err->message = msg_buffer;
new_err->cause = cause;
new_err->file = file;
new_err->line = line;
new_err->func = func;
return new_err;
}
static inline const Error *_result_from_errno(
int errno_val, const ErrorDomain *domain, int fallback_err_code,
const char *file, int line, const char *func
) {
for (size_t i = 0; i < domain->error_count; ++i)
if (domain->errors[i].raw_code == errno_val)
return _result_error_new(NULL, domain, domain->errors[i].type_code, file, line, func);
return _result_error_new(NULL, domain, fallback_err_code, file, line, func);
}
static inline void print_error_chain(FILE *stream, const Error *error)
{
fprintf(stream, "Traceback (root cause first):\n");
const Error *chain[RESULT_ERROR_POOL_SIZE];
int depth = 0;
while (error != NULL && depth < RESULT_ERROR_POOL_SIZE) {
chain[depth++] = error;
error = error->cause;
}
for (int i = depth - 1; i >= 0; --i)
{
const Error *current = chain[i];
fprintf(stream,
" File \""
_RESULT_COLOR_BLUE "%s"
_RESULT_COLOR_RESET "\", line "
_RESULT_COLOR_YELLOW "%d"
_RESULT_COLOR_RESET ", in "
_RESULT_COLOR_GREEN "%s"
_RESULT_COLOR_RESET "()\n",
current->file, current->line, current->func
);
fprintf(stream,
" ["
_RESULT_COLOR_ORANGE "%s"
_RESULT_COLOR_RESET "]: "
_RESULT_COLOR_RED "%s"
_RESULT_COLOR_RESET " ("
_RESULT_COLOR_PURPLE "%d"
_RESULT_COLOR_RESET ")"
_RESULT_COLOR_RESET "\n",
current->domain_name, current->message, current->raw_code
);
}
}
#define ERROR(name, _code, _message) [name] = {.raw_code = _code, .type_code = name, .message = _message}
#define DEFINE_ERROR_DOMAIN(name, id, ...) \
static const ErrorInfo name##_ERRORS[] = { __VA_ARGS__ }; \
static const ErrorDomain name##_DOMAIN = { \
.domain_id = id, \
.domain_name = #name, \
.errors = name##_ERRORS, \
.error_count = sizeof(name##_ERRORS) / sizeof(ErrorInfo) \
}
// ============= Result Handling =============
#define RESULT_TYPE(Typename, Type) \
typedef struct { \
bool _is_ok; \
union { \
Type value; \
const Error *error; \
}; \
} Typename##Result
#define Ok(Typename, Value) ((Typename##Result){ ._is_ok = true, .value = (Value) })
#define Fail(ResultType, DomainObject, ErrCode) \
((ResultType##Result){ \
._is_ok = false, \
.error = _result_error_new(NULL, &(DomainObject), ErrCode, __FILE__, __LINE__, __func__) \
})
#define Fail_from_errno(ResultType, DomainObject, errno_val, FallbackErrCode) \
((ResultType##Result){ \
._is_ok = false, \
.error = _result_from_errno(errno_val, &(DomainObject), FallbackErrCode, __FILE__, __LINE__, __func__) \
})
#define Fail_fmt(ResultType, DomainObject, ErrCode, ...) \
((ResultType##Result){ \
._is_ok = false, \
.error = _result_error_new_fmt(NULL, &(DomainObject), ErrCode, __FILE__, __LINE__, __func__, __VA_ARGS__) \
})
#define Propagate(Typename, ErrStructPtr) \
((Typename##Result){ \
._is_ok = false, \
.error = _result_error_new(ErrStructPtr, &STANDARD_DOMAIN, STD_ERR_PROPAGATED, __FILE__, __LINE__, __func__) \
})
#define Result(Typename) Typename##Result
#define is_ok(result) ((result)._is_ok)
#define is_error(result) (!(result)._is_ok)
#define unwrap_ok(result) \
(is_ok(result) ? (result).value : (PANIC("Called unwrap_ok() on an Error value"), (result).value))
#define expect_ok(result, message) \
(is_ok(result) ? (result).value : (PANIC(message), (result).value))
#define unwrap_error(result) \
(is_error(result) ? (result).error : (PANIC("Called unwrap_error() on an Ok value"), (result).error))
#define error_msg(result) (unwrap_error(result)->message)
#define error_domain(result) (unwrap_error(result)->domain_name)
#define or_ok(result, default_val) \
(is_ok(result) ? unwrap_ok(result) : (default_val))
#define FREE_RESULT(result_var, free_func) \
do { \
if (is_ok(result_var)) \
free_func(unwrap_ok(result_var)); \
} while(0)
#define TRY_CAST(EnclosingTypename, ExprTypename, res_expr) \
({ \
Result(ExprTypename) res = (res_expr); \
if (is_error(res)) \
return Propagate(EnclosingTypename, unwrap_error(res)); \
unwrap_ok(res); \
})
#define TRY(Typename, res_expr) \
TRY_CAST(Typename, Typename, res_expr)
#define TRY_FAIL_CAST(EnclosingTypename, ExprTypename, res_expr, FailDomain, FailCode) \
({ \
Result(ExprTypename) res = (res_expr); \
if (is_error(res)) { \
const Error *cause = unwrap_error(res); \
const Error *new_err = _result_error_new(cause, &(FailDomain), FailCode, __FILE__, __LINE__, __func__); \
return ((EnclosingTypename##Result){ ._is_ok = false, .error = new_err }); \
} \
unwrap_ok(res); \
})
#define TRY_FAIL(Typename, res_expr, FailDomain, FailCode) \
TRY_FAIL_CAST(Typename, Typename, res_expr, FailDomain, FailCode)
#define MAP_RESULT(OutputResultTypename, func_ptr, InputResultTypename, result_expr) \
({\
Result(InputResultTypename) _res_map_input = (result_expr); \
is_ok(_res_map_input) \
? Ok(OutputResultTypename, func_ptr(unwrap_ok(_res_map_input))) \
: ((OutputResultTypename##Result){ ._is_ok = false, .error = unwrap_error(_res_map_input) }); \
})
// ============= Optional Handling =============
#define OPTIONAL_TYPE(Typename, Type) \
typedef struct { \
bool _is_some; \
Type value; \
} Typename##Optional
#define Some(Typename, Value) ((Typename##Optional){ ._is_some = true, .value = (Value) })
#define None(Typename) ((Typename##Optional){ ._is_some = false})
#define Optional(Typename) Typename##Optional
#define is_some(Varname) ((Varname)._is_some)
#define is_none(Varname) (!(Varname)._is_some)
#define unwrap_some(Varname) \
(is_some(Varname) ? (Varname).value : (PANIC("Called unwrap_some() on a None value"), (Varname).value))
#define expect_some(Varname, message) \
(is_some(Varname) ? (Varname).value : (PANIC(message), (Varname).value))
#define or_some(Varname, default_value) \
(is_some(Varname) ? unwrap_some(Varname) : (default_value))
#define FREE_OPTIONAL(optional_var, free_func) \
do { \
if (is_some(optional_var)) \
free_func(unwrap_some(optional_var)); \
} while(0)
#define MAP_OPTIONAL(OutputOptionalTypename, func_ptr, InputOptionalTypename, optional_expr) \
({ \
Optional(InputOptionalTypename) _opt_map_input = (optional_expr); \
is_some(_opt_map_input) \
? Some(OutputOptionalTypename, func_ptr(unwrap_some(_opt_map_input))) \
: None(OutputOptionalTypename); \
})
#define TRY_SOME(Typename, target_var, opt_expr) \
do { \
Optional(Typename) opt = (opt_expr); \
if (is_none(opt)) \
return None(Typename); \
target_var = unwrap_some(opt); \
} while(0)
// ============= Pre-defined Types =============
// Void type for Results that carry no value
typedef struct { bool _unused; } result_void_t;
RESULT_TYPE(Void, result_void_t);
#define Ok_void() Ok(Void, (result_void_t){true})
OPTIONAL_TYPE(Char, char);
OPTIONAL_TYPE(UChar, unsigned char);
OPTIONAL_TYPE(Short, short);
OPTIONAL_TYPE(UShort, unsigned short);
OPTIONAL_TYPE(Int, int);
OPTIONAL_TYPE(UInt, unsigned int);
OPTIONAL_TYPE(Long, long);
OPTIONAL_TYPE(ULong, unsigned long);
OPTIONAL_TYPE(LongLong, long long);
OPTIONAL_TYPE(ULongLong, unsigned long long);
OPTIONAL_TYPE(Float, float);
OPTIONAL_TYPE(Double, double);
OPTIONAL_TYPE(String, const char*);
OPTIONAL_TYPE(VoidPtr, void*);
RESULT_TYPE(Char, char);
RESULT_TYPE(UChar, unsigned char);
RESULT_TYPE(Short, short);
RESULT_TYPE(UShort, unsigned short);
RESULT_TYPE(Int, int);
RESULT_TYPE(UInt, unsigned int);
RESULT_TYPE(Long, long);
RESULT_TYPE(ULong, unsigned long);
RESULT_TYPE(LongLong, long long);
RESULT_TYPE(ULongLong, unsigned long long);
RESULT_TYPE(Float, float);
RESULT_TYPE(Double, double);
RESULT_TYPE(String, const char*);
RESULT_TYPE(VoidPtr, void*);
RESULT_TYPE(CharOptional, CharOptional);
RESULT_TYPE(UCharOptional, UCharOptional);
RESULT_TYPE(ShortOptional, ShortOptional);
RESULT_TYPE(UShortOptional, UShortOptional);
RESULT_TYPE(IntOptional, IntOptional);
RESULT_TYPE(UIntOptional, UIntOptional);
RESULT_TYPE(LongOptional, LongOptional);
RESULT_TYPE(ULongOptional, ULongOptional);
RESULT_TYPE(LongLongOptional, LongLongOptional);
RESULT_TYPE(ULongLongOptional, ULongLongOptional);
RESULT_TYPE(FloatOptional, FloatOptional);
RESULT_TYPE(DoubleOptional, DoubleOptional);
RESULT_TYPE(StringOptional, StringOptional);
RESULT_TYPE(VoidPtrOptional, VoidPtrOptional);
// ============= Predefined Error Domains =============
enum StandardErrorCodes {
STD_ERR_GENERIC = 0,
STD_ERR_OUT_OF_MEMORY,
STD_ERR_INVALID_ARGUMENT,
STD_ERR_NULL_POINTER,
STD_ERR_BUFFER_OVERFLOW,
STD_ERR_NOT_FOUND,
STD_ERR_ACCESS_DENIED,
STD_ERR_TIMEOUT,
STD_ERR_NOT_IMPLEMENTED,
STD_ERR_PROPAGATED
};
DEFINE_ERROR_DOMAIN(STANDARD, 1,
ERROR(STD_ERR_GENERIC, 0, "Generic error"),
ERROR(STD_ERR_OUT_OF_MEMORY, ENOMEM, "Out of memory"),
ERROR(STD_ERR_INVALID_ARGUMENT, EINVAL, "Invalid argument"),
ERROR(STD_ERR_NULL_POINTER, EFAULT, "Null pointer"),
ERROR(STD_ERR_BUFFER_OVERFLOW, EOVERFLOW, "Buffer overflow"),
ERROR(STD_ERR_NOT_FOUND, ENOENT, "Not found"),
ERROR(STD_ERR_ACCESS_DENIED, EACCES, "Access denied"),
ERROR(STD_ERR_TIMEOUT, ETIMEDOUT, "Timeout"),
ERROR(STD_ERR_NOT_IMPLEMENTED, ENOSYS, "Not implemented"),
ERROR(STD_ERR_PROPAGATED, -1, "Error propagated")
);
enum IoErrorCodes {
IO_ERR_FILE_NOT_FOUND = 0,
IO_ERR_PERMISSION_DENIED,
IO_ERR_FILE_EXISTS,
IO_ERR_READ_FAILED,
IO_ERR_WRITE_FAILED,
IO_ERR_SEEK_FAILED,
IO_ERR_DISK_FULL,
IO_ERR_INVALID_PATH,
IO_ERR_DEVICE_NOT_READY
};
DEFINE_ERROR_DOMAIN(IO, 2,
ERROR(IO_ERR_FILE_NOT_FOUND, ENOENT, "File not found"),
ERROR(IO_ERR_PERMISSION_DENIED, EACCES, "Permission denied"),
ERROR(IO_ERR_FILE_EXISTS, EEXIST, "File already exists"),
ERROR(IO_ERR_READ_FAILED, EIO, "Read operation failed"),
ERROR(IO_ERR_WRITE_FAILED, EIO, "Write operation failed"),
ERROR(IO_ERR_SEEK_FAILED, ESPIPE, "Seek operation failed"),
ERROR(IO_ERR_DISK_FULL, ENOSPC, "Disk full"),
ERROR(IO_ERR_INVALID_PATH, ENOTDIR, "Invalid path"),
ERROR(IO_ERR_DEVICE_NOT_READY, ENODEV, "Device not ready")
);
enum NetworkErrorCodes {
NET_ERR_CONNECTION_FAILED = 0,
NET_ERR_CONNECTION_REFUSED,
NET_ERR_CONNECTION_TIMEOUT,
NET_ERR_HOST_NOT_FOUND,
NET_ERR_NETWORK_UNREACHABLE,
NET_ERR_PROTOCOL_ERROR,
NET_ERR_INVALID_URL,
NET_ERR_SSL_ERROR,
NET_ERR_AUTHENTICATION_FAILED
};
DEFINE_ERROR_DOMAIN(NETWORK, 3,
ERROR(NET_ERR_CONNECTION_FAILED, ECONNREFUSED, "Connection failed"),
ERROR(NET_ERR_CONNECTION_REFUSED, ECONNREFUSED, "Connection refused"),
ERROR(NET_ERR_CONNECTION_TIMEOUT, ETIMEDOUT, "Connection timeout"),
ERROR(NET_ERR_HOST_NOT_FOUND, EHOSTUNREACH, "Host not found"),
ERROR(NET_ERR_NETWORK_UNREACHABLE, ENETUNREACH, "Network unreachable"),
ERROR(NET_ERR_PROTOCOL_ERROR, EPROTO, "Protocol error"),
ERROR(NET_ERR_INVALID_URL, EINVAL, "Invalid URL"),
ERROR(NET_ERR_SSL_ERROR, EPROTO, "SSL/TLS error"),
ERROR(NET_ERR_AUTHENTICATION_FAILED, EACCES, "Authentication failed")
);
enum ParseErrorCodes {
PARSE_ERR_INVALID_FORMAT = 0,
PARSE_ERR_UNEXPECTED_CHARACTER,
PARSE_ERR_UNEXPECTED_END,
PARSE_ERR_NUMBER_TOO_LARGE,
PARSE_ERR_NUMBER_TOO_SMALL,
PARSE_ERR_INVALID_ESCAPE,
PARSE_ERR_SYNTAX_ERROR,
PARSE_ERR_ENCODING_ERROR
};
DEFINE_ERROR_DOMAIN(PARSE, 4,
ERROR(PARSE_ERR_INVALID_FORMAT, EINVAL, "Invalid format"),
ERROR(PARSE_ERR_UNEXPECTED_CHARACTER, EILSEQ, "Unexpected character"),
ERROR(PARSE_ERR_UNEXPECTED_END, ENODATA, "Unexpected end of input"),
ERROR(PARSE_ERR_NUMBER_TOO_LARGE, ERANGE, "Number too large"),
ERROR(PARSE_ERR_NUMBER_TOO_SMALL, ERANGE, "Number too small"),
ERROR(PARSE_ERR_INVALID_ESCAPE, EILSEQ, "Invalid escape sequence"),
ERROR(PARSE_ERR_SYNTAX_ERROR, EINVAL, "Syntax error"),
ERROR(PARSE_ERR_ENCODING_ERROR, EILSEQ, "Encoding error")
);
enum MathErrorCodes {
MATH_ERR_DIV_BY_ZERO = 0,
MATH_ERR_OVERFLOW,
MATH_ERR_UNDERFLOW,
MATH_ERR_INVALID_OPERATION
};
DEFINE_ERROR_DOMAIN(MATH, 5,
ERROR(MATH_ERR_DIV_BY_ZERO, EDOM, "Division by zero"),
ERROR(MATH_ERR_OVERFLOW, ERANGE, "Overflow occurred"),
ERROR(MATH_ERR_UNDERFLOW, ERANGE, "Underflow occurred"),
ERROR(MATH_ERR_INVALID_OPERATION, EINVAL, "Invalid operation")
);
#endif // RESULT_H