code / bp

Lines4.3K C3.3K Markdown541 YAML273 make110 Shell77 Lua54
(51 lines)
1 //
2 // utils.h - Some utility and printing functions.
3 //
4 #pragma once
6 #include <err.h>
7 #include <stdarg.h>
8 #include <stdbool.h>
9 #include <stdlib.h> // IWYU pragma: export
10 #include <string.h> // IWYU pragma: export
11 #include <unistd.h>
13 #ifndef auto
14 #define auto __auto_type
15 #endif
17 #define S1(x) #x
18 #define S2(x) S1(x)
20 #define require(e, msg) \
21 ({ \
22 __typeof__(e) __expr = e; \
23 if (_Generic(__expr, int: (ssize_t)__expr < 0, ssize_t: (ssize_t)__expr < 0, default: !__expr)) \
24 errx(1, __FILE__ ":" S2(__LINE__) ": " msg); \
25 __expr; \
26 })
28 #define When(x, _tag) \
29 ((x)->type == _tag \
30 ? &(x)->__tagged._tag \
31 : (errx(1, __FILE__ ":%d This was supposed to be a " #_tag "\n", __LINE__), &(x)->__tagged._tag))
33 #ifndef public
34 #define public __attribute__((visibility("default")))
35 #endif
37 #define new(t) require(calloc(1, sizeof(t)), "`new(" #t ")` allocation failure")
38 #define checked_strdup(s) require(strdup(s), "`checked_strdup(" #s ")` allocation failure")
39 #define grow(arr, n) require(realloc(arr, sizeof(arr[0]) * (n)), "`grow(" #arr ", " #n ")` allocation failure")
41 #define streq(a, b) (strcmp(a, b) == 0)
43 __attribute__((nonnull(1))) char unescapechar(const char *escaped, const char **after, const char *end);
44 __attribute__((pure, nonnull)) const char *after_name(const char *str, const char *end);
45 __attribute__((pure, nonnull, returns_nonnull)) const char *after_spaces(const char *str, bool skip_nl,
46 const char *end);
47 __attribute__((nonnull)) bool matchchar(const char **str, char c, bool skip_nl, const char *end);
48 __attribute__((nonnull)) bool matchstr(const char **str, const char *target, bool skip_nl, const char *end);
49 __attribute__((nonnull)) void delete(void *p);
51 // vim: ts=4 sw=0 et cino=L2,l1,(0,W4,m1,\:0