]> git.ipfire.org Git - thirdparty/kmod.git/commitdiff
strbuf: Add strbuf_shrink_to()
authorLucas De Marchi <lucas.de.marchi@gmail.com>
Thu, 14 Nov 2024 05:02:07 +0000 (23:02 -0600)
committerLucas De Marchi <lucas.de.marchi@gmail.com>
Sun, 17 Nov 2024 21:35:13 +0000 (15:35 -0600)
Useful when working with paths on a loop and resetting to a base path
component on every loop iteration.

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
shared/strbuf.h
testsuite/test-strbuf.c

index 6a4c8d93c0558e3920c49106251b997bb810c830..dad5da525cb1cecce0cc57865fdcf8de265f1c29 100644 (file)
@@ -121,6 +121,12 @@ void strbuf_popchars(struct strbuf *buf, size_t n)
        buf->used -= n;
 }
 
+void strbuf_shrink_to(struct strbuf *buf, size_t sz)
+{
+       assert(buf->used >= sz);
+       buf->used = sz;
+}
+
 void strbuf_clear(struct strbuf *buf)
 {
        buf->used = 0;
index 96e6ed2401d636165a3ed71ae35752c40333b90b..02ec89556924ad44cd06837ec591e1a918f1bb65 100644 (file)
@@ -102,6 +102,11 @@ void strbuf_popchar(struct strbuf *buf);
  */
 void strbuf_popchars(struct strbuf *buf, size_t n);
 
+/*
+ * Shrink buffer to the final size @sz, which must be less or equal the current size.
+ */
+void strbuf_shrink_to(struct strbuf *buf, size_t sz);
+
 /*
  * Return number of used chars. This may different than calling strlen() in a C string
  * since '\0' is considered a valid char - this only keeps track of how many slots are
index 859f9b26a02bfdd7a67889a681c31b226666e433..e77fbdb9af2a91baa4916bd051d48bf2b167f005 100644 (file)
@@ -227,4 +227,35 @@ static int test_strbuf_used(const struct test *t)
 }
 DEFINE_TEST(test_strbuf_used, .description = "test strbuf_used");
 
+static int test_strbuf_shrink_to(const struct test *t)
+{
+       _cleanup_strbuf_ struct strbuf buf;
+
+       strbuf_init(&buf);
+       strbuf_shrink_to(&buf, 0);
+       assert_return(strbuf_used(&buf) == 0, EXIT_FAILURE);
+
+       strbuf_pushchars(&buf, TEXT);
+       strbuf_shrink_to(&buf, strlen(TEXT) - 1);
+       assert_return(strbuf_used(&buf) == strlen(TEXT) - 1, EXIT_FAILURE);
+
+       return 0;
+}
+DEFINE_TEST(test_strbuf_shrink_to, .description = "test strbuf_shrink_to");
+
+static int xfail_strbuf_shrink_to(const struct test *t)
+{
+       _cleanup_strbuf_ struct strbuf buf;
+
+       strbuf_init(&buf);
+       strbuf_pushchar(&buf, '/');
+
+       /* This should crash on assert */
+       strbuf_shrink_to(&buf, 2);
+
+       return 0;
+}
+DEFINE_TEST(xfail_strbuf_shrink_to, .description = "xfail strbuf_shrink_to",
+           .expected_fail = true);
+
 TESTSUITE_MAIN();