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