Merge branch 'js/complete-checkout-t' into maint-2.42
[alt-git.git] / strvec.c
blob89dc9e7e753313acbb0a5dc83b7705f3538a4c45
1 #include "git-compat-util.h"
2 #include "strvec.h"
3 #include "hex.h"
4 #include "strbuf.h"
6 const char *empty_strvec[] = { NULL };
8 void strvec_init(struct strvec *array)
10 struct strvec blank = STRVEC_INIT;
11 memcpy(array, &blank, sizeof(*array));
14 static void strvec_push_nodup(struct strvec *array, const char *value)
16 if (array->v == empty_strvec)
17 array->v = NULL;
19 ALLOC_GROW(array->v, array->nr + 2, array->alloc);
20 array->v[array->nr++] = value;
21 array->v[array->nr] = NULL;
24 const char *strvec_push(struct strvec *array, const char *value)
26 strvec_push_nodup(array, xstrdup(value));
27 return array->v[array->nr - 1];
30 const char *strvec_pushf(struct strvec *array, const char *fmt, ...)
32 va_list ap;
33 struct strbuf v = STRBUF_INIT;
35 va_start(ap, fmt);
36 strbuf_vaddf(&v, fmt, ap);
37 va_end(ap);
39 strvec_push_nodup(array, strbuf_detach(&v, NULL));
40 return array->v[array->nr - 1];
43 void strvec_pushl(struct strvec *array, ...)
45 va_list ap;
46 const char *arg;
48 va_start(ap, array);
49 while ((arg = va_arg(ap, const char *)))
50 strvec_push(array, arg);
51 va_end(ap);
54 void strvec_pushv(struct strvec *array, const char **items)
56 for (; *items; items++)
57 strvec_push(array, *items);
60 void strvec_pop(struct strvec *array)
62 if (!array->nr)
63 return;
64 free((char *)array->v[array->nr - 1]);
65 array->v[array->nr - 1] = NULL;
66 array->nr--;
69 void strvec_split(struct strvec *array, const char *to_split)
71 while (isspace(*to_split))
72 to_split++;
73 for (;;) {
74 const char *p = to_split;
76 if (!*p)
77 break;
79 while (*p && !isspace(*p))
80 p++;
81 strvec_push_nodup(array, xstrndup(to_split, p - to_split));
83 while (isspace(*p))
84 p++;
85 to_split = p;
89 void strvec_clear(struct strvec *array)
91 if (array->v != empty_strvec) {
92 int i;
93 for (i = 0; i < array->nr; i++)
94 free((char *)array->v[i]);
95 free(array->v);
97 strvec_init(array);
100 const char **strvec_detach(struct strvec *array)
102 if (array->v == empty_strvec)
103 return xcalloc(1, sizeof(const char *));
104 else {
105 const char **ret = array->v;
106 strvec_init(array);
107 return ret;