/* -------------------------------------------------------------- * File : helper.h * Authors : Aoran Zeng * Created on : <2023-08-28> * Last modified : <2023-08-31> * * helper: * * helper functions and macros * -------------------------------------------------------------*/ #ifndef XY_H #define XY_H #include #include #include #include // #define NDEBUG #ifdef _WIN32 static bool xy_on_windows = true; static bool xy_on_linux = false; static bool xy_on_macos = false; static bool xy_on_bsds = false; #include #define xy_useutf8() SetConsoleOutputCP(65001) #else static bool xy_on_windows = false; static bool xy_on_linux = true; static bool xy_on_macos = false; static bool xy_on_bsds = false; #define xy_useutf8() #endif #define xy_arylen(x) (sizeof(x) / sizeof(x[0])) static inline void* xy_malloc0 (size_t size) { void* ptr = malloc(size); memset(ptr, 0, size); return ptr; } #define XY_INFO 00001 #define XY_SUCCESS 00001<<1 #define XY_WARN 00001<<2 #define XY_ERROR 00001<<3 static void xy_log (int level, const char* str) { char* color_fmt_str = NULL; bool to_stderr = false; if (level & XY_INFO) { color_fmt_str = "\033[34m%s\033[0m"; // 蓝色 } else if (level & XY_SUCCESS) { color_fmt_str = "\033[32m%s\033[0m"; // 绿色 } else if (level & XY_WARN) { color_fmt_str = "\033[33m%s\033[0m\n"; // 黄色 to_stderr = true; } else if (level & XY_ERROR) { color_fmt_str = "\033[31m%s\033[0m\n"; // 红色 to_stderr = true; } else { //xy_assert ("CAN'T REACH!"); } // -2 把中间%s减掉 size_t len = strlen(color_fmt_str) -2; char* buf = malloc(strlen(str) + len + 1); sprintf (buf, color_fmt_str, str); if (to_stderr) { fprintf(stderr, buf); } else { puts(buf); } free(buf); } #define xy_info(str) xy_log (XY_INFO, str) #define xy_error(str) xy_log (XY_ERROR, str) /** * 将str中所有的src字符替换成dest,并返回一个全新的字符串 * 现在已经废弃不用 */ static char* xy_strch (const char* str, char src,const char* dest) { size_t str_len = strlen(str); size_t dest_len = strlen(dest); size_t size = str_len*dest_len; char* ret = (char*)malloc(size); int i=0; int j=0; while(i al_cur) { al_times += 1; al_cur = al_times * al_fixed; ret = realloc(ret, al_cur); if (NULL==ret) { xy_error ("xy: No availble memory!"); return NULL; } } strcpy(cur, str); cur += strlen(str); } va_end(args); *cur = '\0'; return ret; } bool xy_streql(const char* str1, const char* str2) { return strcmp(str1, str2) == 0 ? true : false; } #endif