From: Emil Velikov Date: Sun, 2 Aug 2026 12:26:13 +0000 (+0100) Subject: shared/strbuf: make strbuf_reserve_extra public X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=44cdb6fa55f5790b9d1615eb709a1329649f5686;p=thirdparty%2Fkmod.git shared/strbuf: make strbuf_reserve_extra public 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 Link: https://github.com/kmod-project/kmod/pull/451 Signed-off-by: Lucas De Marchi --- diff --git a/shared/strbuf.c b/shared/strbuf.c index 76aab07..1499b6d 100644 --- a/shared/strbuf.c +++ b/shared/strbuf.c @@ -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; diff --git a/shared/strbuf.h b/shared/strbuf.h index 074699a..20ed7a2 100644 --- a/shared/strbuf.h +++ b/shared/strbuf.h @@ -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) diff --git a/testsuite/test-shared.c b/testsuite/test-shared.c index b12051d..b45162d 100644 --- a/testsuite/test-shared.c +++ b/testsuite/test-shared.c @@ -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;