Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion kvec.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ int main() {
#define AC_KVEC_H

#include <stdlib.h>
#include <string.h>

#define kv_roundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x))

Expand All @@ -60,7 +61,7 @@ int main() {
#define kv_size(v) ((v).n)
#define kv_max(v) ((v).m)

#define kv_resize(type, v, s) ((v).m = (s), (v).a = (type*)realloc((v).a, sizeof(type) * (v).m))
#define kv_resize(type, v, s) ((v).m = (s), (v).n = (v).n > (s)? s : (v).n, (v).a = (type*)realloc((v).a, sizeof(type) * (v).m))

#define kv_copy(type, v1, v0) do { \
if ((v1).m < (v0).n) kv_resize(type, v1, (v0).n); \
Expand All @@ -87,4 +88,36 @@ int main() {
: (v).n <= (size_t)(i)? (v).n = (i) + 1 \
: 0), (v).a[(i)])

#define kv_p(type, v) ((((v).n < ((v).m >> 2))?\
((v).m >>= 1,\
(v).a = (type*)realloc((v).a, sizeof(type) * (v).m), 0)\
: 0),\
(v).a[--(v).n])

#define kv_insert(type, v, i, x) do {\
if ((v).m == (v).n) {\
(v).m = (v).m? (v).m<<1 : 2;\
(v).a = (type*)realloc((v).a, sizeof(type) * (v).m);\
}\
if ((v).m <= (size_t)(i)) {\
(v).m = (v).n = (i) + 1;\
kv_roundup32((v).m);\
(v).a = (type*)realloc((v).a, sizeof(type) * (v).m);\
} else if ((v).n <= (size_t)(i)) {\
(v).n = (i) + 1;\
} else {++(v).n;}\
memmove((v).a + i + 1, (v).a + i, sizeof(type) * ((v).n - i - 1));\
(v).a[(i)] = x;\
} while(0)

#define kv_remove(type, v, i) do {\
if (i < (v).n) {\
if (--(v).n < ((v).m >> 2)) {\
(v).m >>= 1;\
(v).a = (type*)realloc((v).a, sizeof(type) * (v).m);\
}\
memmove((v).a + i, (v).a + i + 1, sizeof(type) * ((v).n - i));\
}\
} while(0)

#endif