aboutsummaryrefslogtreecommitdiff
path: root/src/common.h
diff options
context:
space:
mode:
authorkartofen <mladenovnasko0@gmail.com>2024-08-23 19:55:13 +0300
committerkartofen <mladenovnasko0@gmail.com>2024-08-23 19:55:13 +0300
commit68a62ad356603d64d537e231f06b5d9445e79abe (patch)
tree3682d6b607fed96eafaf7e218d85a03fbc71d914 /src/common.h
usefull commit message
Diffstat (limited to 'src/common.h')
-rw-r--r--src/common.h98
1 files changed, 98 insertions, 0 deletions
diff --git a/src/common.h b/src/common.h
new file mode 100644
index 0000000..b91459a
--- /dev/null
+++ b/src/common.h
@@ -0,0 +1,98 @@
+#ifndef COMMON_H
+#define COMMON_H
+
+// LOGGING
+
+#include <stdio.h>
+#include <time.h>
+
+#define _RED "\033[0;31m"
+#define _GREEN "\033[0;32m"
+#define _YELLOW "\033[0;33m"
+#define _RST "\033[0m"
+
+#define _log_print(...) fprintf(stdout, __VA_ARGS__)
+#define _log(color, message) _log_print("[%s] %s%-7s"_RST" ", timenow(), color, message)
+
+#define info(...) do { \
+ _log(_GREEN, "[INFO]"); \
+ _log_print(__VA_ARGS__); _log_print("\n"); \
+ } while(0)
+#define err(...) do { \
+ _log(_RED, "[ERROR]"); \
+ _log_print(__FILE__":%d: ", __LINE__); \
+ _log_print(__VA_ARGS__); _log_print("\n"); \
+ } while(0)
+#define die(...) do { \
+ err(__VA_ARGS__); \
+ abort(); \
+ } while(0)
+
+static inline char *timenow(void)
+{
+ static char buffer[64];
+ time_t timer = time(NULL);
+ strftime(buffer, 64, "%H:%M:%S", localtime(&timer));
+ return buffer;
+}
+
+// ERROR MANAGEMENT
+
+#include <errno.h>
+
+#define ERR_NZ(e, r, on_fail) do { \
+ int r; \
+ if((r = e)) { on_fail; } \
+ } while(0)
+
+#define ERR_NZ_RET(e) \
+ ERR_NZ(e, r, return r) \
+
+#define ERR_ERRNO_SET(e, on_fail) \
+ ERR_NZ(e, _r, errno = -_r; on_fail)
+
+#define ERR_Z(e, on_fail) do { \
+ if(!(e)) { on_fail; } \
+ } while(0)
+
+#endif
+
+// MEMORY MANAGEMENT
+
+#ifdef ENABLE_MEMDEBUG
+#include "memdebug.h"
+#define DISABLE_DIE_ALLOC
+#endif
+
+#ifndef DISABLE_DIE_ALLOC
+
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+// #ifdef __GNUC__
+// #define __die_alloc(e) ({void *ptr = e; if(!v) die("%s", strerror(errno)); ptr;})
+// #define malloc(...) __die_alloc(malloc(__VA_ARGS__))
+// #define calloc(...) __die_alloc(calloc(__VA_ARGS__))
+// #define realloc(...) __die_alloc(realloc(__VA_ARGS__))
+// #else
+
+#define DIE_ALLOC_BUILDER(name, typed_args, args) \
+ static inline void *__die_##name typed_args \
+ { \
+ void *r = name args; \
+ if(!r) die("%s", strerror(errno)); \
+ return r; \
+ }
+
+DIE_ALLOC_BUILDER(malloc, (size_t size), (size))
+DIE_ALLOC_BUILDER(calloc, (size_t nmemb, size_t size), (nmemb, size))
+DIE_ALLOC_BUILDER(realloc, (void *ptr, size_t size), (ptr, size))
+
+#define malloc(size) __die_malloc ( size)
+#define calloc(nmemb, size) __die_calloc (nmemb, size)
+#define realloc(ptr, size) __die_realloc(ptr, size)
+
+// #endif
+#endif
+