btrfs: add helper for device path or missing
[linux/fpc-iii.git] / tools / lib / subcmd / subcmd-util.h
blob794a375dad3601e26f870edfa75b3458f1341aa8
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef __SUBCMD_UTIL_H
3 #define __SUBCMD_UTIL_H
5 #include <stdarg.h>
6 #include <stdlib.h>
7 #include <stdio.h>
9 #define NORETURN __attribute__((__noreturn__))
11 static inline void report(const char *prefix, const char *err, va_list params)
13 char msg[1024];
14 vsnprintf(msg, sizeof(msg), err, params);
15 fprintf(stderr, " %s%s\n", prefix, msg);
18 static NORETURN inline void die(const char *err, ...)
20 va_list params;
22 va_start(params, err);
23 report(" Fatal: ", err, params);
24 exit(128);
25 va_end(params);
28 #define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
30 #define alloc_nr(x) (((x)+16)*3/2)
33 * Realloc the buffer pointed at by variable 'x' so that it can hold
34 * at least 'nr' entries; the number of entries currently allocated
35 * is 'alloc', using the standard growing factor alloc_nr() macro.
37 * DO NOT USE any expression with side-effect for 'x' or 'alloc'.
39 #define ALLOC_GROW(x, nr, alloc) \
40 do { \
41 if ((nr) > alloc) { \
42 if (alloc_nr(alloc) < (nr)) \
43 alloc = (nr); \
44 else \
45 alloc = alloc_nr(alloc); \
46 x = xrealloc((x), alloc * sizeof(*(x))); \
47 } \
48 } while(0)
50 static inline void *xrealloc(void *ptr, size_t size)
52 void *ret = realloc(ptr, size);
53 if (!ret && !size)
54 ret = realloc(ptr, 1);
55 if (!ret) {
56 ret = realloc(ptr, size);
57 if (!ret && !size)
58 ret = realloc(ptr, 1);
59 if (!ret)
60 die("Out of memory, realloc failed");
62 return ret;
65 #define astrcatf(out, fmt, ...) \
66 ({ \
67 char *tmp = *(out); \
68 if (asprintf((out), "%s" fmt, tmp ?: "", ## __VA_ARGS__) == -1) \
69 die("asprintf failed"); \
70 free(tmp); \
73 static inline void astrcat(char **out, const char *add)
75 char *tmp = *out;
77 if (asprintf(out, "%s%s", tmp ?: "", add) == -1)
78 die("asprintf failed");
80 free(tmp);
83 #endif /* __SUBCMD_UTIL_H */