[PATCH 1/3] strbuf.[ch]: add STRBUF_HINT_SIZE macro = 8192

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



In b449f4cfc97 (Rework strbuf API and semantics., 2007-09-06) the
first hardcoding of 8192 appeared in strbuf.[ch], then in
f1696ee398e (Strbuf API extensions and fixes., 2007-09-10) another one
was added, and in b4e04fb66e8 (strbuf: add strbuf_read_once to read
without blocking, 2015-12-15) a third.

Let's factor that out into a STRBUF_HINT_SIZE macro, and add a
strbuf_hint() helper macro for "hint ? hint : STRBUF_HINT_SIZE".

Signed-off-by: Ævar Arnfjörð Bjarmason <avarab@xxxxxxxxx>
---
 strbuf.c |  6 +++---
 strbuf.h | 11 +++++++++++
 2 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/strbuf.c b/strbuf.c
index 4df30b45494..7e9f5fdc4de 100644
--- a/strbuf.c
+++ b/strbuf.c
@@ -517,7 +517,7 @@ ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
 	size_t oldlen = sb->len;
 	size_t oldalloc = sb->alloc;
 
-	strbuf_grow(sb, hint ? hint : 8192);
+	strbuf_grow(sb, strbuf_hint(hint));
 	for (;;) {
 		ssize_t want = sb->alloc - sb->len - 1;
 		ssize_t got = read_in_full(fd, sb->buf + sb->len, want);
@@ -532,7 +532,7 @@ ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
 		sb->len += got;
 		if (got < want)
 			break;
-		strbuf_grow(sb, 8192);
+		strbuf_grow(sb, STRBUF_HINT_SIZE);
 	}
 
 	sb->buf[sb->len] = '\0';
@@ -544,7 +544,7 @@ ssize_t strbuf_read_once(struct strbuf *sb, int fd, size_t hint)
 	size_t oldalloc = sb->alloc;
 	ssize_t cnt;
 
-	strbuf_grow(sb, hint ? hint : 8192);
+	strbuf_grow(sb, strbuf_hint(hint));
 	cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
 	if (cnt > 0)
 		strbuf_setlen(sb, sb->len + cnt);
diff --git a/strbuf.h b/strbuf.h
index 223ee2094af..ca3c47966a0 100644
--- a/strbuf.h
+++ b/strbuf.h
@@ -72,6 +72,17 @@ struct strbuf {
 extern char strbuf_slopbuf[];
 #define STRBUF_INIT  { .alloc = 0, .len = 0, .buf = strbuf_slopbuf }
 
+/**
+ * Various functions take a `size_t hint` to give a hint about the
+ * file size, to avoid reallocs. This is the default hint size when
+ * `0` is given. 
+ *
+ * The strbuf_hint() convenience macro is used internally in the
+ * API. DO NOT USE any expression with side-effect for 'size'.
+ */
+#define STRBUF_HINT_SIZE 8192
+#define strbuf_hint(size) ((size) ? (size) : STRBUF_HINT_SIZE)
+
 /*
  * Predeclare this here, since cache.h includes this file before it defines the
  * struct.
-- 
2.32.0.636.g43e71d69cff




[Index of Archives]     [Linux Kernel Development]     [Gcc Help]     [IETF Annouce]     [DCCP]     [Netdev]     [Networking]     [Security]     [V4L]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux Security]     [Linux RAID]     [Linux SCSI]     [Fedora Users]

  Powered by Linux