strbuf_split_buf(): use ALLOC_GROW()
Use ALLOC_GROW() rather than inline code to manage memory in strbuf_split_buf(). Rename "pos" to "nr" because it better describes the use of the variable and it better conforms to the "ALLOC_GROW" idiom. Also, instead of adding a sentinal NULL value after each entry is added to the list, only add it once after all of the entries have been added. Signed-off-by: Michael Haggerty <mhagger@alum.mit.edu> Signed-off-by: Jeff King <peff@peff.net>
Michael Haggerty committed
Nov 4, 2012 at 07:46 UTC
b8c2c1fa35f240ea8eee719c0f5a657285864573
1 file changed
+7
-10
strbuf.c
+7
-10
@@ -108,33 +108,30 @@ void strbuf_ltrim(struct strbuf *sb)
108
109
struct strbuf **strbuf_split_buf(const char *str, size_t slen, int delim, int max)
110
{
111
- int alloc = 2, pos = 0;
111
+ struct strbuf **ret = NULL;
112
+ size_t nr = 0, alloc = 0;
113
const char *n, *p;
113
- struct strbuf **ret;
114
struct strbuf *t;
115
116
- ret = xcalloc(alloc, sizeof(struct strbuf *));
116
p = n = str;
117
while (n < str + slen) {
118
int len;
120
- if (max <= 0 || pos + 1 < max)
119
+ if (max <= 0 || nr + 1 < max)
120
n = memchr(n, delim, slen - (n - str));
121
else
122
n = NULL;
124
- if (pos + 1 >= alloc) {
125
- alloc = alloc * 2;
126
- ret = xrealloc(ret, sizeof(struct strbuf *) * alloc);
127
- }
123
if (!n)
124
n = str + slen - 1;
125
len = n - p + 1;
126
t = xmalloc(sizeof(struct strbuf));
127
strbuf_init(t, len);
128
strbuf_add(t, p, len);
134
- ret[pos] = t;
135
- ret[++pos] = NULL;
129
+ ALLOC_GROW(ret, nr + 2, alloc);
130
+ ret[nr++] = t;
131
p = ++n;
132
}
133
+ ALLOC_GROW(ret, nr + 1, alloc); /* In case string was empty */
134
+ ret[nr] = NULL;
135
return ret;
136
}
137