#ifndef INCLUDED_UTILS_H #define INCLUDED_UTILS_H #include #include #include #include #include #include #include #define ASSERT assert #define REALLOC realloc #define FREE free #define ERROR(FMT, ...) fprintf (stderr, "ERROR: "FMT"\n", ##__VA_ARGS__) #define INFO(FMT, ...) fprintf (stdout, "INFO: "FMT"\n", ##__VA_ARGS__) #ifdef VERBOSE #define LOG(FMT, ...) fprintf (stderr, "INFO: "FMT"\n", ##__VA_ARGS__) #else #define LOG(...) #endif #define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP) #define MIN(A,B) \ ({ \ typeof (A) _a = (A); \ typeof (B) _b = (B); \ _a < _b ? _a : _b; \ }) #define ARRAY_LEN(array) (sizeof (array)/sizeof (*array)) #define ARRAY_GET(array, index) \ (ASSERT(index >= 0), ASSERT(index < ARRAY_LEN(array)), array[index]) #ifndef TEMP_CAPACITY #define TEMP_CAPACITY (16*1024*1024) #endif static size_t temp_size = 0; static char temp[TEMP_CAPACITY] = { 0 }; static inline void * talloc (size_t size) { ASSERT(temp_size + size <= TEMP_CAPACITY); void *result = &temp[temp_size]; temp_size += size; return result; } static inline char * tstrdup (const char *cstr) { size_t n = strlen (cstr); char *result = talloc (n + 1); memcpy (result, cstr, n); result[n] = '\0'; return result; } static inline char * tprintf(const char *format, ...) { va_list args; va_start (args, format); int n = vsnprintf (NULL, 0, format, args); va_end (args); ASSERT(n >= 0); char *result = talloc (n + 1); va_start (args, format); vsnprintf (result, n + 1, format, args); va_end (args); return result; } static inline void temp_reset(void) { temp_size = 0; } static inline size_t temp_save(void) { return temp_size; } static inline void temp_rewind(size_t checkpoint) { temp_size = checkpoint; } static inline int rand_from_to (int min, int max) { return min + rand () % (max + 1 - min); } static inline size_t display_width (const char *mbs) { size_t width = 0; while (*mbs) { width += 1; mbs += 1 + ((*mbs & 1 << 7) >> 7); } return width; } static inline size_t count_mb (const char *mbs) { size_t count = 0; while (*mbs) { char mb = (*mbs & 1 << 7) >> 7; count += mb; mbs += 1 + mb; } return count; } static inline void pause (void) { printf ("Нажмите чтобы продолжить..."); while (getchar () != '\n'); } // NOTE(cmmm): not portable, size_t is expected to be 8 bytes long static inline int log10sz (size_t sz) { return ((sz >= 10000000000000000000lu) ? 19 : (sz >= 1000000000000000000lu) ? 18 : (sz >= 100000000000000000lu) ? 17 : (sz >= 10000000000000000lu) ? 16 : (sz >= 1000000000000000lu) ? 15 : (sz >= 100000000000000lu) ? 14 : (sz >= 10000000000000lu) ? 13 : (sz >= 1000000000000lu) ? 12 : (sz >= 100000000000lu) ? 11 : (sz >= 1000000000lu) ? 9 : (sz >= 100000000lu) ? 8 : (sz >= 10000000lu) ? 7 : (sz >= 1000000lu) ? 6 : (sz >= 100000lu) ? 5 : (sz >= 10000lu) ? 4 : (sz >= 1000lu) ? 3 : (sz >= 100lu) ? 2 : (sz >= 10lu) ? 1 : 0u); } extern int levenshtein_distance (const char *a, const char *b); #endif