Merge pull request #48 from lemonsqueeze/tactics_undo
[pachi.git] / util.h
blob0c3955996ce55060d54fde998a8446b753bbe28b
1 #ifndef PACHI_UTIL_H
2 #define PACHI_UTIL_H
4 #include <stdlib.h>
5 #include <stdio.h>
7 /* Portability definitions. */
9 #ifdef _WIN32
12 * sometimes we use winsock and like to avoid a warning to include
13 * windows.h only after winsock2.h
15 #include <winsock2.h>
17 #include <windows.h>
19 #define sleep(seconds) Sleep((seconds) * 1000)
20 #define __sync_fetch_and_add(ap, b) InterlockedExchangeAdd((LONG volatile *) (ap), (b));
21 #define __sync_fetch_and_sub(ap, b) InterlockedExchangeAdd((LONG volatile *) (ap), -((LONG)b));
23 /* MinGW gcc, no function prototype for built-in function stpcpy() */
24 char *stpcpy (char *dest, const char *src);
26 #include <ctype.h>
27 static inline const char *
28 strcasestr(const char *haystack, const char *needle)
30 for (const char *p = haystack; *p; p++) {
31 for (int ni = 0; needle[ni]; ni++) {
32 if (!p[ni])
33 return NULL;
34 if (toupper(p[ni]) != toupper(needle[ni]))
35 goto more_hay;
37 return p;
38 more_hay:;
40 return NULL;
42 #endif
44 /* Misc. definitions. */
46 /* Use make DOUBLE_FLOATING=1 in large configurations with counts > 1M
47 * where 24 bits of floating_t mantissa become insufficient. */
48 #ifdef DOUBLE_FLOATING
49 # define floating_t double
50 # define PRIfloating "%lf"
51 #else
52 # define floating_t float
53 # define PRIfloating "%f"
54 #endif
56 #define likely(x) __builtin_expect(!!(x), 1)
57 #define unlikely(x) __builtin_expect((x), 0)
59 static inline void *
60 checked_malloc(size_t size, char *filename, unsigned int line, const char *func)
62 void *p = malloc(size);
63 if (!p) {
64 fprintf(stderr, "%s:%u: %s: OUT OF MEMORY malloc(%u)\n",
65 filename, line, func, (unsigned) size);
66 exit(1);
68 return p;
71 static inline void *
72 checked_calloc(size_t nmemb, size_t size, const char *filename, unsigned int line, const char *func)
74 void *p = calloc(nmemb, size);
75 if (!p) {
76 fprintf(stderr, "%s:%u: %s: OUT OF MEMORY calloc(%u, %u)\n",
77 filename, line, func, (unsigned) nmemb, (unsigned) size);
78 exit(1);
80 return p;
83 #define malloc2(size) checked_malloc((size), __FILE__, __LINE__, __func__)
84 #define calloc2(nmemb, size) checked_calloc((nmemb), (size), __FILE__, __LINE__, __func__)
86 #endif