mkp224o/vec.h

75 lines
1.7 KiB
C
Raw Normal View History

#define VEC_STRUCT(typename,inttype) \
2017-09-24 21:13:16 +02:00
struct typename { \
inttype *buf; \
size_t len, alen; \
}
#define VEC_INIT(ctl) memset(&ctl,0,sizeof(ctl))
2017-09-24 21:13:16 +02:00
#define VEC_ADD1(ctl) { \
2017-09-24 21:13:16 +02:00
if (!(ctl).alen) { \
(ctl).alen = 8; \
(ctl).buf = malloc(8 * sizeof(*(ctl).buf)); \
2017-09-24 21:13:16 +02:00
} else if ((ctl).len >= (ctl).alen) { \
(ctl).alen *= 2; \
(ctl).buf = realloc((ctl).buf,(ctl).alen * sizeof(*(ctl).buf)); \
2017-09-24 21:13:16 +02:00
} \
++(ctl).len; \
2017-09-24 21:13:16 +02:00
}
#define VEC_ADD(ctl,val) { \
2017-09-24 21:13:16 +02:00
if (!(ctl).alen) { \
(ctl).alen = 8; \
(ctl).buf = malloc(8 * sizeof(*(ctl).buf)); \
} else if ((ctl).len >= (ctl).alen) { \
(ctl).alen *= 2; \
(ctl).buf = realloc((ctl).buf,(ctl).alen * sizeof(*(ctl).buf)); \
} \
(ctl).buf[(ctl).len++] = (val); \
}
#define VEC_ADDN(ctl,n) { \
if (!(ctl).alen) { \
(ctl).alen = 8; \
(ctl).buf = malloc(8 * sizeof(*(ctl).buf)); \
2017-09-24 21:13:16 +02:00
} \
size_t nlen = (ctl).alen; \
while ((ctl).len + n > nlen) \
nlen *= 2; \
if (nlen > (ctl).alen) { \
(ctl).alen = nlen; \
(ctl).buf = realloc((ctl).buf,nlen * sizeof(*(ctl).buf)); \
2017-09-24 21:13:16 +02:00
} \
(ctl).len += n; \
}
#define VEC_REMOVE(ctl,n) { \
--(ctl).len; \
memmove( \
&(ctl).buf[(n) * sizeof(*(ctl).buf)], \
&(ctl).buf[(n + 1) * sizeof(*(ctl).buf)], \
((ctl).len - (n)) * sizeof(*(ctl).buf)); \
}
#define VEC_INSERT(ctl,n,val) { \
VEC_ADD1(ctl); \
memmove( \
&(ctl).buf[(n + 1) * sizeof(*(ctl).buf)], \
&(ctl).buf[(n) * sizeof(*(ctl).buf)], \
((ctl).len - (n) - 1) * sizeof(*(ctl).buf)); \
(ctl).buf[n] = (val); \
}
#define VEC_ZERO(ctl) \
memset((ctl).buf,0,(ctl).len * sizeof(*(ctl).buf))
#define VEC_FREE(ctl) { \
free((ctl).buf); \
memset(&(ctl), 0, sizeof((ctl))); \
}
2017-09-24 21:13:16 +02:00
#define VEC_LENGTH(ctl) ((ctl).len)
#define VEC_BUF(ctl,num) ((ctl).buf[num])
#define VEC_FOR(ctl,it) for (size_t it = 0;it < VEC_LENGTH((ctl));++it)