#include #include #include #include #ifdef NAUNET_ON_WINDOWS #include "winwrap.h" #else #include #endif #include "util/timer/timer.h" #include "util/thread/thread.h" #include "common.h" #ifndef NAUNET_ON_WINDOWS #define RESET "\033[0m" static inline const char *get_color_for_level(u8 level) { #define NORMAL "\x1B[0m" #define RED "\x1B[31m" #define GREEN "\x1B[32m" #define YELLOW "\x1B[33m" #define BLUE "\x1B[34m" #define MAGENTA "\x1B[35m" #define CYAN "\x1B[36m" #define WHITE "\x1B[37m" switch (level) { case AL_LOG_ERROR: return RED; case AL_LOG_WARN: return YELLOW; default: return ""; } } #endif s32 al_print_default(void *userdata, u8 level, char *message) { (void)userdata; s32 ret = 0; #ifdef NAUNET_ON_WINDOWS (void)level; ret = al_printf("%*.*s\n", 0, AL_LOG_MESSAGE_SIZE, message); #else ret = al_printf("%s%*.*s%s\n", get_color_for_level(level), 0, AL_LOG_MESSAGE_SIZE, message, RESET); #endif return ret; } #ifdef AL_MEMORY_TRACKING #include "util/thread/thread.h" static struct nn_mutex malloc_mutex; static void malloc_lock(void) { nn_mutex_lock(&malloc_mutex); } static void malloc_unlock(void) { nn_mutex_unlock(&malloc_mutex); } #endif bool nn_common_init(const char *thread_name) { if (thread_name) nn_thread_set_name(thread_name); if (!setlocale(LC_ALL, "")) return false; al_set_print(al_print_default, NULL); #ifdef NAUNET_ON_WINDOWS SYSTEM_INFO info; GetSystemInfo(&info); al_set_page_size(info.dwPageSize); #else al_set_page_size(sysconf(_SC_PAGESIZE)); #endif #ifdef AL_MEMORY_TRACKING al_malloc_init(); nn_mutex_init(&malloc_mutex); al_set_alloc(malloc, calloc, realloc, #ifdef AL_HAVE_POSIX_MEMALIGN posix_memalign, #endif free, malloc_lock, malloc_unlock); #endif al_random_init((u32)(nn_get_timestamp() / 1000000)); #ifdef NAUNET_ON_WINDOWS if (!nn_windows_init()) return false; #endif return true; } void nn_common_close(void) { #ifdef NAUNET_ON_WINDOWS nn_windows_close(); #endif #ifdef AL_MEMORY_TRACKING al_malloc_close(); size_t current; size_t peak; size_t total; size_t ops; al_malloc_stats(¤t, &peak, &total, &ops); al_printf("malloc stats, current: %.2fKB, peak: %.2fKB, total: %.2fKB, ops: %zu.\n", current / 1024.f, peak / 1024.f, total / 1024.f, ops); nn_mutex_destroy(&malloc_mutex); #endif }