#ifndef COMMON_H #define COMMON_H // LOGGING #include #include #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 #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 #include #include // #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