subcmd-util.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #ifndef __SUBCMD_UTIL_H
  2. #define __SUBCMD_UTIL_H
  3. #include <stdarg.h>
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #define NORETURN __attribute__((__noreturn__))
  7. static inline void report(const char *prefix, const char *err, va_list params)
  8. {
  9. char msg[1024];
  10. vsnprintf(msg, sizeof(msg), err, params);
  11. fprintf(stderr, " %s%s\n", prefix, msg);
  12. }
  13. static NORETURN inline void die(const char *err, ...)
  14. {
  15. va_list params;
  16. va_start(params, err);
  17. report(" Fatal: ", err, params);
  18. exit(128);
  19. va_end(params);
  20. }
  21. #define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
  22. #define alloc_nr(x) (((x)+16)*3/2)
  23. /*
  24. * Realloc the buffer pointed at by variable 'x' so that it can hold
  25. * at least 'nr' entries; the number of entries currently allocated
  26. * is 'alloc', using the standard growing factor alloc_nr() macro.
  27. *
  28. * DO NOT USE any expression with side-effect for 'x' or 'alloc'.
  29. */
  30. #define ALLOC_GROW(x, nr, alloc) \
  31. do { \
  32. if ((nr) > alloc) { \
  33. if (alloc_nr(alloc) < (nr)) \
  34. alloc = (nr); \
  35. else \
  36. alloc = alloc_nr(alloc); \
  37. x = xrealloc((x), alloc * sizeof(*(x))); \
  38. } \
  39. } while(0)
  40. static inline void *xrealloc(void *ptr, size_t size)
  41. {
  42. void *ret = realloc(ptr, size);
  43. if (!ret && !size)
  44. ret = realloc(ptr, 1);
  45. if (!ret) {
  46. ret = realloc(ptr, size);
  47. if (!ret && !size)
  48. ret = realloc(ptr, 1);
  49. if (!ret)
  50. die("Out of memory, realloc failed");
  51. }
  52. return ret;
  53. }
  54. #define astrcatf(out, fmt, ...) \
  55. ({ \
  56. char *tmp = *(out); \
  57. if (asprintf((out), "%s" fmt, tmp ?: "", ## __VA_ARGS__) == -1) \
  58. die("asprintf failed"); \
  59. free(tmp); \
  60. })
  61. static inline void astrcat(char **out, const char *add)
  62. {
  63. char *tmp = *out;
  64. if (asprintf(out, "%s%s", tmp ?: "", add) == -1)
  65. die("asprintf failed");
  66. free(tmp);
  67. }
  68. static inline int prefixcmp(const char *str, const char *prefix)
  69. {
  70. for (; ; str++, prefix++)
  71. if (!*prefix)
  72. return 0;
  73. else if (*str != *prefix)
  74. return (unsigned char)*prefix - (unsigned char)*str;
  75. }
  76. #endif /* __SUBCMD_UTIL_H */