git/list[1] front-page[2] threads[3] people[4] search[5] about
 

[PATCH 2/4] strbuf_split_buf(): simplify iteration

From
Michael Haggerty <mhagger@alum.mit.edu>
Date
Nov 4, 2012, 06:46 UTC
Message-ID
<1352011614-29334-3-git-send-email-mhagger@alum.mit.edu>
In-Reply-To
<1352011614-29334-1-git-send-email-mhagger@alum.mit.edu>

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>
---
 strbuf.c | 23 ++++++++++-------------
 1 file changed, 10 insertions(+), 13 deletions(-)
diff --git a/strbuf.c b/strbuf.c
index 5256c2a..c7cd529 100644
--- a/strbuf.c
+++ b/strbuf.c
@@ -110,25 +110,22 @@ struct strbuf **strbuf_split_buf(const char *str, size_t slen, int delim, int ma
 {
 	struct strbuf **ret = NULL;
 	size_t nr = 0, alloc = 0;
-	const char *n, *p;
 	struct strbuf *t;
 
-	p = n = str;
-	while (n < str + slen) {
-		int len;
-		if (max <= 0 || nr + 1 < max)
-			n = memchr(n, delim, slen - (n - str));
-		else
-			n = NULL;
-		if (!n)
-			n = str + slen - 1;
-		len = n - p + 1;
+	while (slen) {
+		int len = slen;
+		if (max <= 0 || nr + 1 < max) {
+			const char *end = memchr(str, delim, slen);
+			if (end)
+				len = end - str + 1;
+		}
 		t = xmalloc(sizeof(struct strbuf));
 		strbuf_init(t, len);
-		strbuf_add(t, p, len);
+		strbuf_add(t, str, len);
 		ALLOC_GROW(ret, nr + 2, alloc);
 		ret[nr++] = t;
-		p = ++n;
+		str += len;
+		slen -= len;
 	}
 	ALLOC_GROW(ret, nr + 1, alloc); /* In case string was empty */
 	ret[nr] = NULL;
-- 
1.8.0
Previous: Jeff KingNext: Michael Haggerty
Message 6 of 9 in “Simplify and document strbuf_split() functions”
  1. 0/4 Simplify and document strbuf_split() functionsMichael Haggerty, Nov 4, 2012
  2. 1/4 strbuf_split_buf(): use ALLOC_GROW()Michael Haggerty, Nov 4, 2012
  3. Jeff KingNov 4, 2012
  4. Michael HaggertyNov 6, 2012
  5. Jeff KingNov 8, 2012
  6. 2/4 strbuf_split_buf(): simplify iterationMichael Haggerty, Nov 4, 2012
  7. 3/4 strbuf_split*(): rename "delim" parameter to "terminator"Michael Haggerty, Nov 4, 2012
  8. 4/4 strbuf_split*(): document functionsMichael Haggerty, Nov 4, 2012
  9. Jeff KingNov 4, 2012

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.