Bug fix
[satune.git] / src / common.h
1 /*      Copyright (c) 2015 Regents of the University of California
2  *
3  *      Author: Brian Demsky <bdemsky@uci.edu>
4  *
5  *      This program is free software; you can redistribute it and/or
6  *      modify it under the terms of the GNU General Public License
7  *      version 2 as published by the Free Software Foundation.
8  */
9
10 /** @file common.h
11  *  @brief General purpose macros.
12  */
13
14 #ifndef __COMMON_H__
15 #define __COMMON_H__
16
17 #include <stdio.h>
18 #include "config.h"
19 #include "time.h"
20
21
22 #if 1
23 extern int model_out;
24 extern int model_err;
25 extern int switch_alloc;
26
27 #define model_dprintf(fd, fmt, ...) do { switch_alloc = 1; dprintf(fd, fmt, ## __VA_ARGS__); switch_alloc = 0; } while (0)
28 #define model_print(fmt, ...) do { model_dprintf(model_out, fmt, ## __VA_ARGS__); } while (0)
29 #define model_print_err(fmt, ...) do { model_dprintf(model_err, fmt, ## __VA_ARGS__); } while (0)
30 #else
31 #define model_print printf
32 #endif
33
34 #define NEXTPOW2(x) ((x == 1) ? 1 : (1 << (sizeof(uint) * 8 - __builtin_clz(x - 1))))
35 #define NUMBITS(x) ((x == 0) ? 0 : 8 * sizeof(x) - __builtin_clz(x))
36
37 #ifdef CONFIG_DEBUG
38 #define DEBUG(fmt, ...) do { model_print("*** %15s:%-4d %25s() *** " fmt, __FILE__, __LINE__, __func__, ## __VA_ARGS__); } while (0)
39 #define DBG() DEBUG("\n")
40 #define DBG_ENABLED() (1)
41 #else
42 #define DEBUG(fmt, ...)
43 #define DBG()
44 #define DBG_ENABLED() (0)
45 #endif
46
47 void assert_hook(void);
48
49 #ifdef CONFIG_ASSERT
50 #define ASSERT(expr) \
51         do { \
52                 if (!(expr)) { \
53                         fprintf(stderr, "Error: assertion failed in %s at line %d\n", __FILE__, __LINE__); \
54                         /* print_trace(); // Trace printing may cause dynamic memory allocation */ \
55                         assert_hook();                           \
56                         exit(EXIT_FAILURE); \
57                 } \
58         } while (0)
59 #else
60 #define ASSERT(expr) \
61         do { } while (0)
62 #endif/* CONFIG_ASSERT */
63
64 #define error_msg(...) fprintf(stderr, "Error: " __VA_ARGS__)
65
66 void print_trace(void);
67
68 static inline long long getTimeNano() {
69         struct timespec time;
70         clock_gettime(CLOCK_REALTIME, &time);
71         return time.tv_sec * 1000000000 + time.tv_nsec;
72 }
73 #endif/* __COMMON_H__ */