Git development
 help / color / mirror / Atom feed
* [PATCH] trailer: change strbuf in-place in unfold_value()
@ 2026-05-14 18:40 René Scharfe
  2026-05-14 21:30 ` Ramsay Jones
                   ` (2 more replies)
  0 siblings, 3 replies; 6+ messages in thread
From: René Scharfe @ 2026-05-14 18:40 UTC (permalink / raw)
  To: Git List; +Cc: Jeff King

Avoid an allocation by doing s/\n\s*/ /g (replacing NL and any following
whitespace with a SP) right in the strbuf instead of copying the result
to a temporary one and swapping them in the end.  We can safely do that
because the replacement is never longer than the original string.

Signed-off-by: René Scharfe <l.s.r@web.de>
---
Formatted with --function-context for easier review.
Inspired by https://lore.kernel.org/git/20260513185408.GA147423@coredump.intra.peff.net/

 trailer.c | 16 ++++++----------
 1 file changed, 6 insertions(+), 10 deletions(-)

diff --git a/trailer.c b/trailer.c
index 470f86a4a2..b89fa12fe7 100644
--- a/trailer.c
+++ b/trailer.c
@@ -988,29 +988,25 @@ static int ends_with_blank_line(const char *buf, size_t len)
 
 static void unfold_value(struct strbuf *val)
 {
-	struct strbuf out = STRBUF_INIT;
 	size_t i;
+	size_t pos = 0;
 
-	strbuf_grow(&out, val->len);
 	i = 0;
 	while (i < val->len) {
 		char c = val->buf[i++];
 		if (c == '\n') {
 			/* Collapse continuation down to a single space. */
 			while (i < val->len && isspace(val->buf[i]))
 				i++;
-			strbuf_addch(&out, ' ');
-		} else {
-			strbuf_addch(&out, c);
+			val->buf[pos++] = ' ';
+		} else if (pos != i) {
+			val->buf[pos++] = c;
 		}
 	}
+	strbuf_setlen(val, pos);
 
 	/* Empty lines may have left us with whitespace cruft at the edges */
-	strbuf_trim(&out);
-
-	/* output goes back to val as if we modified it in-place */
-	strbuf_swap(&out, val);
-	strbuf_release(&out);
+	strbuf_trim(val);
 }
 
 static struct trailer_block *trailer_block_new(void)
-- 
2.54.0


^ permalink raw reply related	[flat|nested] 6+ messages in thread

end of thread, other threads:[~2026-05-15  7:33 UTC | newest]

Thread overview: 6+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-05-14 18:40 [PATCH] trailer: change strbuf in-place in unfold_value() René Scharfe
2026-05-14 21:30 ` Ramsay Jones
2026-05-15  4:44   ` Jeff King
2026-05-15  6:47   ` René Scharfe
2026-05-15  4:47 ` Jeff King
2026-05-15  7:33 ` [PATCH v2] " René Scharfe

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox