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