]> git.ipfire.org Git - thirdparty/kmod.git/commitdiff
shared/strbuf: make strbuf_reserve_extra public
authorEmil Velikov <emil.l.velikov@gmail.com>
Sun, 2 Aug 2026 12:26:13 +0000 (13:26 +0100)
committerLucas De Marchi <demarchi@kernel.org>
Mon, 10 Aug 2026 13:49:47 +0000 (08:49 -0500)
We'll need the function shortly, so make it public (within kmod).
In the process, re-introduce the test with some changes:
 - cosmetics - test function signature, new test macros, DECLARE_*
 - do not request an extra byte for \0
 - check both ::size and ::bytes

Signed-off-by: Emil Velikov <emil.l.velikov@gmail.com>
Link: https://github.com/kmod-project/kmod/pull/451
Signed-off-by: Lucas De Marchi <demarchi@kernel.org>
shared/strbuf.c
shared/strbuf.h
testsuite/test-shared.c

index 76aab073f1811a4ca5b13f37baa1aac3f9fafcae..1499b6d503a50d88b859d9d916da5c4f3bd64d8f 100644 (file)
@@ -33,7 +33,7 @@ static bool buf_realloc(struct strbuf *buf, size_t sz)
        return true;
 }
 
-static bool strbuf_reserve_extra(struct strbuf *buf, size_t n)
+bool strbuf_reserve_extra(struct strbuf *buf, size_t n)
 {
        if (n < buf->size - buf->used)
                return true;
index 074699a60a6a0cae43a811ab8e8fd008ac7ed2ee..20ed7a25f93e1452891745a6a3ce6d5380d7e0c1 100644 (file)
@@ -50,6 +50,16 @@ void strbuf_clear(struct strbuf *buf);
  */
 const char *strbuf_str(struct strbuf *buf);
 
+/*
+ * Reserve/allocate extra space to buf.
+ *
+ * Check the current buf size and re-allocate, as needed. Therefore follow-up pushes of the
+ * given size (or less) are guaranteed to a) not require re-allocation and b) succeed.
+ *
+ * The terminating \0 byte will be handled internally.
+ */
+bool strbuf_reserve_extra(struct strbuf *buf, size_t n);
+
 bool strbuf_pushchar(struct strbuf *buf, char ch);
 size_t strbuf_pushmem(struct strbuf *buf, const char *src, size_t sz);
 static inline size_t strbuf_pushchars(struct strbuf *buf, const char *str)
index b12051d36f5e49b5881622f09cfd2dc4b2b1096a..b45162d26f34541799222143c04fe487c9f262dd 100644 (file)
@@ -626,6 +626,30 @@ static int test_strbuf_used(void)
 }
 DEFINE_TEST(test_strbuf_used, .description = "test strbuf_used");
 
+static int test_strbuf_reserve_extra(void)
+{
+       DECLARE_STRBUF(buf);
+       const char *str;
+       size_t size;
+
+       strbuf_reserve_extra(&buf, strlen(TEXT));
+       size = buf.size;
+       str = buf.bytes;
+       TS_ASSERT(size >= strlen(TEXT) + 1);
+
+       strbuf_pushchars(&buf, TEXT);
+       TS_ASSERT(size == buf.size);
+       TS_ASSERT(str == buf.bytes);
+
+       strbuf_clear(&buf);
+       strbuf_pushchars(&buf, TEXT);
+       TS_ASSERT(size == buf.size);
+       TS_ASSERT(str == buf.bytes);
+
+       return 0;
+}
+DEFINE_TEST(test_strbuf_reserve_extra, .description = "test strbuf_reserve_extra");
+
 static int test_strbuf_shrink_to(void)
 {
        _cleanup_strbuf_ struct strbuf buf;