Initial skeleton.
[ashd.git] / lib / utils.h
1 #ifndef _UTILS_H
2 #define _UTILS_H
3
4 #define smalloc(size) ({void *__result__; ((__result__ = malloc(size)) == NULL)?({exit(-1); (void *)0;}):__result__;})
5 #define srealloc(ptr, size) ({void *__result__; ((__result__ = realloc((ptr), (size))) == NULL)?({exit(-1); (void *)0;}):__result__;})
6 #define szmalloc(size) memset(smalloc(size), 0, size)
7 #define sstrdup(str) ({char *__strbuf__ = (str); strcpy(smalloc(strlen(__strbuf__) + 1), __strbuf__);})
8 #define omalloc(o) ((o) = szmalloc(sizeof(*(o))))
9
10 #define bufinit(buf) memset(&(buf), 0, sizeof(buf))
11 #define buffree(buf) do { if((buf).b != NULL) {free((buf).b);} } while(0)
12 #define sizebuf(buf, wanted) (_sizebuf((struct buffer *)&(buf), (wanted), sizeof(*((buf).b))))
13 #define bufadd(buf, new) \
14 do { \
15     _sizebuf((struct buffer *)&(buf), (buf).d + 1, sizeof(*((buf).b))); \
16     (buf).b[(buf).d++] = (new); \
17 } while(0)
18 #define bufcat(buf, new, size) \
19 do { \
20     size_t __bufcat_size__; \
21     __bufcat_size__ = (size); \
22     _sizebuf((struct buffer *)&(buf), (buf).d + __bufcat_size__, sizeof((buf).b)); \
23     memcpy((buf).b + (buf).d, (new), (__bufcat_size__) * sizeof(*((buf).b))); \
24     (buf).d += __bufcat_size__; \
25 } while(0)
26 #define bufcatstr2(buf, str) \
27 do { \
28     char *__buf__; \
29     __buf__ = (str); \
30     bufcat((buf), __buf__, strlen(__buf__)); \
31 } while(0)
32
33 struct buffer {
34     void *b;
35     size_t s, d;
36 };
37
38 #define typedbuf(type) struct {type *b; size_t s, d;}
39
40 struct charbuf {
41     char *b;
42     size_t s, d;
43 };
44
45 struct charvbuf {
46     char **b;
47     size_t s, d;
48 };
49
50 void _sizebuf(struct buffer *buf, size_t wanted, size_t el);
51
52 #endif