]> mj.ucw.cz Git - netgrind.git/blob - lib/lib.h
TODO: A note on IPv6
[netgrind.git] / lib / lib.h
1 /*
2  *      Sherlock Library -- Miscellaneous Functions
3  *
4  *      (c) 1997--2003 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 /*
11  *  This file should be included as the very first include in all
12  *  source files, especially before all OS includes since it sets
13  *  up libc feature macros.
14  */
15
16 #ifndef _SHERLOCK_LIB_H
17 #define _SHERLOCK_LIB_H
18
19 #include "lib/config.h"
20
21 /* Tell libc we're going to use all extensions available */
22
23 #define _GNU_SOURCE
24
25 /* Ugly structure handling macros */
26
27 #define OFFSETOF(s, i) ((unsigned int)&((s *)0)->i)
28 #define SKIP_BACK(s, i, p) ((s *)((char *)p - OFFSETOF(s, i)))
29 #define ALIGN(s, a) (((s)+a-1)&~(a-1))
30 #define UNALIGNED_PART(ptr, type) (((long) (ptr)) % sizeof(type))
31
32 /* Some other macros */
33
34 #define MIN(a,b) (((a)<(b))?(a):(b))
35 #define MAX(a,b) (((a)>(b))?(a):(b))
36 #define CLAMP(x,min,max) ({ int _t=x; (_t < min) ? min : (_t > max) ? max : _t; })
37 #define ABS(x) ((x) < 0 ? -(x) : (x))
38 #define ARRAY_SIZE(a) (sizeof(a)/sizeof(*(a)))
39
40 /* Logging */
41
42 void die(byte *, ...) NONRET;
43
44 #ifdef DEBUG
45 void assert_failed(char *assertion, char *file, int line) NONRET;
46 #define ASSERT(x) do { if (!(x)) assert_failed(#x, __FILE__, __LINE__); } while(0)
47 #else
48 void assert_failed(void) NONRET;
49 #define ASSERT(x) do { if (__builtin_constant_p(x) && !(x)) assert_failed(); } while(0)
50 #endif
51
52 #ifdef LOCAL_DEBUG
53 #define DBG(x,y...) printf(x,##y)
54 #else
55 #define DBG(x,y...) do { } while(0)
56 #endif
57
58 /* Memory allocation */
59
60 #ifdef DMALLOC
61 /*
62  * The standard dmalloc macros tend to produce lots of namespace
63  * conflicts and we use only xmalloc and xfree, so we can define
64  * the stubs ourselves.
65  */
66 #define DMALLOC_DISABLE
67 #include <dmalloc.h>
68 #define xmalloc(size) _xmalloc_leap(__FILE__, __LINE__, size)
69 #define xrealloc(ptr,size) _xrealloc_leap(__FILE__, __LINE__, ptr, size)
70 #define xfree(ptr) _xfree_leap(__FILE__, __LINE__, ptr)
71 #else
72 /*
73  * Unfortunately, several libraries we might want to link to define
74  * their own xmalloc and we don't want to interfere with them, hence
75  * the renaming.
76  */
77 #define xmalloc sh_xmalloc
78 void *xmalloc(unsigned);
79 void *xrealloc(void *, unsigned);
80 #define xfree(x) free(x)
81 #endif
82
83 void *xmalloc_zero(unsigned);
84 byte *stralloc(byte *);
85
86 /* prime.c */
87
88 int isprime(uns);
89 uns nextprime(uns);
90
91 #endif