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