]> git.ipfire.org Git - thirdparty/git.git/blob - strvec.c
Merge branch 'jx/dirstat-parseopt-help'
[thirdparty/git.git] / strvec.c
1 #include "git-compat-util.h"
2 #include "strvec.h"
3 #include "strbuf.h"
4
5 const char *empty_strvec[] = { NULL };
6
7 void strvec_init(struct strvec *array)
8 {
9 struct strvec blank = STRVEC_INIT;
10 memcpy(array, &blank, sizeof(*array));
11 }
12
13 static void strvec_push_nodup(struct strvec *array, const char *value)
14 {
15 if (array->v == empty_strvec)
16 array->v = NULL;
17
18 ALLOC_GROW(array->v, array->nr + 2, array->alloc);
19 array->v[array->nr++] = value;
20 array->v[array->nr] = NULL;
21 }
22
23 const char *strvec_push(struct strvec *array, const char *value)
24 {
25 strvec_push_nodup(array, xstrdup(value));
26 return array->v[array->nr - 1];
27 }
28
29 const char *strvec_pushf(struct strvec *array, const char *fmt, ...)
30 {
31 va_list ap;
32 struct strbuf v = STRBUF_INIT;
33
34 va_start(ap, fmt);
35 strbuf_vaddf(&v, fmt, ap);
36 va_end(ap);
37
38 strvec_push_nodup(array, strbuf_detach(&v, NULL));
39 return array->v[array->nr - 1];
40 }
41
42 void strvec_pushl(struct strvec *array, ...)
43 {
44 va_list ap;
45 const char *arg;
46
47 va_start(ap, array);
48 while ((arg = va_arg(ap, const char *)))
49 strvec_push(array, arg);
50 va_end(ap);
51 }
52
53 void strvec_pushv(struct strvec *array, const char **items)
54 {
55 for (; *items; items++)
56 strvec_push(array, *items);
57 }
58
59 void strvec_pop(struct strvec *array)
60 {
61 if (!array->nr)
62 return;
63 free((char *)array->v[array->nr - 1]);
64 array->v[array->nr - 1] = NULL;
65 array->nr--;
66 }
67
68 void strvec_split(struct strvec *array, const char *to_split)
69 {
70 while (isspace(*to_split))
71 to_split++;
72 for (;;) {
73 const char *p = to_split;
74
75 if (!*p)
76 break;
77
78 while (*p && !isspace(*p))
79 p++;
80 strvec_push_nodup(array, xstrndup(to_split, p - to_split));
81
82 while (isspace(*p))
83 p++;
84 to_split = p;
85 }
86 }
87
88 void strvec_clear(struct strvec *array)
89 {
90 if (array->v != empty_strvec) {
91 int i;
92 for (i = 0; i < array->nr; i++)
93 free((char *)array->v[i]);
94 free(array->v);
95 }
96 strvec_init(array);
97 }
98
99 const char **strvec_detach(struct strvec *array)
100 {
101 if (array->v == empty_strvec)
102 return xcalloc(1, sizeof(const char *));
103 else {
104 const char **ret = array->v;
105 strvec_init(array);
106 return ret;
107 }
108 }