aboutsummaryrefslogtreecommitdiff
path: root/util/util.h
diff options
context:
space:
mode:
authorflu0r1ne <flu0r1ne@flu0r1ne.net>2022-10-30 19:30:29 -0500
committerflu0r1ne <flu0r1ne@flu0r1ne.net>2022-10-30 19:30:29 -0500
commit20e52f326cdf1b6c2ca9b2c0b5be07637d9196d2 (patch)
tree1d957cfd5ca8b9ccd0a91fa5d5415599edd241d1 /util/util.h
downloadqidx-20e52f326cdf1b6c2ca9b2c0b5be07637d9196d2.tar.xz
qidx-20e52f326cdf1b6c2ca9b2c0b5be07637d9196d2.zip
Initial commit
Diffstat (limited to 'util/util.h')
-rw-r--r--util/util.h78
1 files changed, 78 insertions, 0 deletions
diff --git a/util/util.h b/util/util.h
new file mode 100644
index 0000000..ef378ca
--- /dev/null
+++ b/util/util.h
@@ -0,0 +1,78 @@
+#ifndef UTIL_H
+#define UTIL_H
+
+#include <stdarg.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <stdbool.h>
+
+#if defined(__GNUC__) || defined(__clang__)
+# define NORETURN __attribute__((__noreturn__))
+#else
+# define NORETURN
+#endif
+
+#if defined(__GNUC__)
+# define UNUSED __attribute__((__unused__))
+#else
+# define UNUSED
+#endif
+
+#define N_ENTRIES(x) (sizeof(x) / sizeof(*x))
+#define member_size(type, member) sizeof(((type *)(0))->member)
+#define TYPEOF(x) __typeof__(x)
+
+#define PACKED __attribute__((__packed__))
+
+#if defined(__GNUC__)
+# define FALLTHROUGH __attribute__ ((fallthrough))
+#else
+# define FALLTHROUGH
+#endif
+
+NORETURN void die(const char *format, ...) __attribute__((format (printf, 1, 2)));
+NORETURN void die_errno(const char *format, ...) __attribute__((format (printf, 1, 2)));
+
+void err(const char * format, ...) __attribute__((format (printf, 1, 2)));
+void err_errno(const char * format, ...) __attribute__((format (printf, 1, 2)));
+
+#define XREALLOC_ARRAY(x, alloc) ((x) = xrealloc((x), (alloc) * sizeof(*(x))))
+#define ALLOC_ARRAY(x, n) (malloc((n) * sizeof(*x)))
+
+#define ALIGN_ADDR_MASK(addr, mask) \
+ ((addr + ((mask) - 1)) & ~((mask) - 1))
+
+#define ALIGN_ADDR_16(addr) ALIGN_ADDR_MASK(addr, 0x10)
+#define ALIGN_ADDR_32(addr) ALIGN_ADDR_MASK(addr, 0x20)
+#define ALIGN_ADDR_64(addr) ALIGN_ADDR_MASK(addr, 0x40)
+#define ALIGN_ADDR(addr, bytes) ALIGN_ADDR_MASK(addr, (8ULL*(bytes)))
+
+// Scaling: 0, 24, 66, 140, 269, 495, 890
+#define ALLOC_NC(x) (((x)+14)*7/4)
+
+#define AM_RESIZE_ALLOC(buf, sz, cap, item_sz, alloc_nc) \
+ do { \
+ TYPEOF(sz) _sz = (sz); \
+ if((cap) < _sz) { \
+ void * nb; \
+ TYPEOF(cap) nc; \
+ if(_sz < alloc_nc((cap))) { \
+ nc = alloc_nc((cap)); \
+ } else { \
+ nc = _sz; \
+ } \
+ nb = realloc((buf), (item_sz) * nc); \
+ if(nb) { \
+ (cap) = nc; \
+ (buf) = nb; \
+ } else { \
+ free((buf)); \
+ (buf) = NULL; \
+ } \
+ } \
+ } while(0)
+
+#define AM_RESIZE(buf, sz, cap) \
+ AM_RESIZE_ALLOC(buf, sz, cap, sizeof(*buf), ALLOC_NC)
+
+#endif