]> git.ipfire.org Git - thirdparty/kmod.git/commitdiff
strbuf: Do not append '\0' if not needed
authorLucas De Marchi <lucas.de.marchi@gmail.com>
Tue, 12 Nov 2024 19:43:20 +0000 (13:43 -0600)
committerLucas De Marchi <lucas.de.marchi@gmail.com>
Sun, 17 Nov 2024 21:35:13 +0000 (15:35 -0600)
Unconditionally appending '\0' is not a big problem, but that does
trigger the buffer to potentially be re-allocated. Avoid that by
checking the last char is not already NUL.

Signed-off-by: Lucas De Marchi <lucas.de.marchi@gmail.com>
Reviewed-by: Emil Velikov <emil.l.velikov@gmail.com>
Link: https://github.com/kmod-project/kmod/pull/239
shared/strbuf.c

index 5a25976c3b1408c71ec43230f5496b806f496312..69d20db6ec925d3432da2ba806e3426257f77d58 100644 (file)
@@ -78,9 +78,11 @@ char *strbuf_steal(struct strbuf *buf)
 
 const char *strbuf_str(struct strbuf *buf)
 {
-       if (!strbuf_reserve_extra(buf, 1))
-               return NULL;
-       buf->bytes[buf->used] = '\0';
+       if (!buf->used || buf->bytes[buf->used - 1]) {
+               if (!strbuf_reserve_extra(buf, 1))
+                       return NULL;
+               buf->bytes[buf->used] = '\0';
+       }
        return buf->bytes;
 }