summaryrefslogtreecommitdiff
path: root/src/common.c
blob: d0bd863fc07b09764471f419280a873866aaab8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <al/lib.h>
#include <al/log.h>
#include <al/random.h>
#include <locale.h>
#ifdef NAUNET_ON_WINDOWS
#include "winwrap.h"
#else
#include <unistd.h>
#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(&current, &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
}