strbuf_split_buf(): simplify iteration

While iterating, update str and slen to keep track of the part of the string that hasn't been processed yet rather than computing things relative to the start of the original string. This eliminates one local variable, reduces the scope of another, and reduces the amount of arithmetic needed within the loop. 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 1173bb331103b7e6d9e95549c7b7be12546d0697
1 file changed +10 -13
strbuf.c
+10 -13
@@ -110,25 +110,22 @@ struct strbuf **strbuf_split_buf(const char *str, size_t slen, int delim, int ma
110 {
111 struct strbuf **ret = NULL;
112 size_t nr = 0, alloc = 0;
113 - const char *n, *p;
113 struct strbuf *t;
114
116 - p = n = str;
117 - while (n < str + slen) {
118 - int len;
119 - if (max <= 0 || nr + 1 < max)
120 - n = memchr(n, delim, slen - (n - str));
121 - else
122 - n = NULL;
123 - if (!n)
124 - n = str + slen - 1;
125 - len = n - p + 1;
115 + while (slen) {
116 + int len = slen;
117 + if (max <= 0 || nr + 1 < max) {
118 + const char *end = memchr(str, delim, slen);
119 + if (end)
120 + len = end - str + 1;
121 + }
122 t = xmalloc(sizeof(struct strbuf));
123 strbuf_init(t, len);
128 - strbuf_add(t, p, len);
124 + strbuf_add(t, str, len);
125 ALLOC_GROW(ret, nr + 2, alloc);
126 ret[nr++] = t;
131 - p = ++n;
127 + str += len;
128 + slen -= len;
129 }
130 ALLOC_GROW(ret, nr + 1, alloc); /* In case string was empty */
131 ret[nr] = NULL;