1 /*
2 * Copyright © 2010-2011 Marcin Kościelnicki <[email protected]>
3 * Copyright © 2010 Francisco Jerez <[email protected]>
4 * All Rights Reserved.
5 * SPDX-License-Identifier: MIT
6 */
7
8 #ifndef UTIL_H
9 #define UTIL_H
10
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <inttypes.h>
14
15 #define ADDARRAY(a, e) \
16 do { \
17 if ((a ## num) >= (a ## max)) { \
18 if (!(a ## max)) \
19 (a ## max) = 16; \
20 else \
21 (a ## max) *= 2; \
22 (a) = realloc((a), (a ## max)*sizeof(*(a))); \
23 } \
24 (a)[(a ## num)++] = (e); \
25 } while(0)
26
27 #define FINDARRAY(a, tmp, pred) \
28 ({ \
29 int __i; \
30 \
31 for (__i = 0; __i < (a ## num); __i++) { \
32 tmp = (a)[__i]; \
33 if (pred) \
34 break; \
35 } \
36 \
37 tmp = ((pred) ? tmp : NULL); \
38 })
39
40 /* ceil(log2(x)) */
clog2(uint64_t x)41 static inline int clog2(uint64_t x) {
42 if (!x)
43 return x;
44 int r = 0;
45 while (x - 1 > (1ull << r) - 1)
46 r++;
47 return r;
48 }
49
50 #define ARRAY_SIZE(a) (sizeof (a) / sizeof *(a))
51
52 #define min(a,b) \
53 ({ \
54 typeof (a) _a = (a); \
55 typeof (b) _b = (b); \
56 _a < _b ? _a : _b; \
57 })
58
59 #define max(a,b) \
60 ({ \
61 typeof (a) _a = (a); \
62 typeof (b) _b = (b); \
63 _a > _b ? _a : _b; \
64 })
65
66 #define CEILDIV(a, b) (((a) + (b) - 1)/(b))
67
68 #define extr(a, b, c) ((uint64_t)(a) << (64 - (b) - (c)) >> (64 - (c)))
69 #define extrs(a, b, c) ((int64_t)(a) << (64 - (b) - (c)) >> (64 - (c)))
70 #define sext(a, b) extrs(a, 0, b+1)
71 #define bflmask(a) ((2ull << ((a)-1)) - 1)
72 #define insrt(a, b, c, d) ((a) = ((a) & ~(bflmask(c) << (b))) | ((d) & bflmask(c)) << (b))
73
74 struct envy_loc {
75 int lstart;
76 int cstart;
77 int lend;
78 int cend;
79 const char *file;
80 };
81
82 #define LOC_FORMAT(loc, str) "%s:%d.%d-%d.%d: " str, (loc).file, (loc).lstart, (loc).cstart, (loc).lend, (loc).cend
83
84 uint32_t elf_hash(const char *str);
85
86 FILE *find_in_path(const char *name, const char *path, char **pfullname);
87
88 struct astr {
89 char *str;
90 size_t len;
91 };
92
93 void print_escaped_astr(FILE *out, struct astr *astr);
94
95 #endif
96