| 1 | #ifndef _UTILS_H |
| 2 | #define _UTILS_H |
| 3 | |
| 4 | #include <stdarg.h> |
| 5 | #include <sys/types.h> |
| 6 | |
| 7 | #define max(a, b) (((b) > (a))?(b):(a)) |
| 8 | #define min(a, b) (((b) < (a))?(b):(a)) |
| 9 | |
| 10 | #define smalloc(size) ({void *__result__; ((__result__ = malloc(size)) == NULL)?({exit(-1); (void *)0;}):__result__;}) |
| 11 | #define srealloc(ptr, size) ({void *__result__; ((__result__ = realloc((ptr), (size))) == NULL)?({exit(-1); (void *)0;}):__result__;}) |
| 12 | #define szmalloc(size) memset(smalloc(size), 0, size) |
| 13 | #define sstrdup(str) ({const char *__strbuf__ = (str); strcpy(smalloc(strlen(__strbuf__) + 1), __strbuf__);}) |
| 14 | #define omalloc(o) ((o) = szmalloc(sizeof(*(o)))) |
| 15 | |
| 16 | #define bufinit(buf) memset(&(buf), 0, sizeof(buf)) |
| 17 | #define buffree(buf) do { if((buf).b != NULL) {free((buf).b);} bufinit(buf); } while(0) |
| 18 | #define sizebuf(buf, wanted) (_sizebuf((struct buffer *)&(buf), (wanted), sizeof(*((buf).b)))) |
| 19 | #define bufadd(buf, new) \ |
| 20 | do { \ |
| 21 | _sizebuf((struct buffer *)&(buf), (buf).d + 1, sizeof(*((buf).b))); \ |
| 22 | (buf).b[(buf).d++] = (new); \ |
| 23 | } while(0) |
| 24 | #define bufcat(buf, new, size) \ |
| 25 | do { \ |
| 26 | size_t __bufcat_size__; \ |
| 27 | __bufcat_size__ = (size); \ |
| 28 | _sizebuf((struct buffer *)&(buf), (buf).d + __bufcat_size__, sizeof((buf).b)); \ |
| 29 | memcpy((buf).b + (buf).d, (new), (__bufcat_size__) * sizeof(*((buf).b))); \ |
| 30 | (buf).d += __bufcat_size__; \ |
| 31 | } while(0) |
| 32 | #define bufcatstr(buf, str) \ |
| 33 | do { \ |
| 34 | char *__buf__; \ |
| 35 | __buf__ = (str); \ |
| 36 | bufcat((buf), __buf__, strlen(__buf__)); \ |
| 37 | } while(0) |
| 38 | #define bufcatstr2(buf, str) \ |
| 39 | do { \ |
| 40 | char *__buf__; \ |
| 41 | __buf__ = (str); \ |
| 42 | bufcat((buf), __buf__, strlen(__buf__) + 1); \ |
| 43 | } while(0) |
| 44 | #define bufeat(buf, len) memmove((buf).b, (buf).b + (len), (buf).d -= (len)) |
| 45 | |
| 46 | struct buffer { |
| 47 | void *b; |
| 48 | size_t s, d; |
| 49 | }; |
| 50 | |
| 51 | #define typedbuf(type) struct {type *b; size_t s, d;} |
| 52 | |
| 53 | struct charbuf { |
| 54 | char *b; |
| 55 | size_t s, d; |
| 56 | }; |
| 57 | |
| 58 | struct charvbuf { |
| 59 | char **b; |
| 60 | size_t s, d; |
| 61 | }; |
| 62 | |
| 63 | void _sizebuf(struct buffer *buf, size_t wanted, size_t el); |
| 64 | char *decstr(char **p, size_t *len); |
| 65 | char *vsprintf2(char *format, va_list al); |
| 66 | char *sprintf2(char *format, ...); |
| 67 | char *sprintf3(char *format, ...); |
| 68 | off_t atoo(char *n); |
| 69 | char **tokenize(char *src); |
| 70 | void freeca(char **ca); |
| 71 | int calen(char **a); |
| 72 | void bvprintf(struct charbuf *buf, char *format, va_list al); |
| 73 | void bprintf(struct charbuf *buf, char *format, ...); |
| 74 | void replstr(char **p, char *n); |
| 75 | |
| 76 | #endif |