]> git.puffer.fish Git - mirror/frr.git/commitdiff
lib: add `darr_strlen_fixup()` to update len based on NUL term
authorChristian Hopps <chopps@labn.net>
Thu, 13 Mar 2025 20:32:59 +0000 (20:32 +0000)
committerChristian Hopps <chopps@labn.net>
Fri, 14 Mar 2025 08:37:46 +0000 (08:37 +0000)
Signed-off-by: Christian Hopps <chopps@labn.net>
lib/darr.h
tests/lib/test_darr.c

index 084c2a103a41eca9fe49949820b7e3a3b6336286..4638b904d18e59c32e3bd02716741e33ac104f76 100644 (file)
@@ -62,6 +62,7 @@
  *  - darr_strdup
  *  - darr_strdup_cap
  *  - darr_strlen
+ *  - darr_strlen_fixup
  *  - darr_strnul
  *  - darr_sprintf, darr_vsprintf
  */
@@ -752,6 +753,22 @@ void *__darr_resize(void *a, uint count, size_t esize, struct memtype *mt);
                __size;                                                        \
        })
 
+/**
+ * Fixup darr_len (and thus darr_strlen) for `S` based on its strlen(S)
+ * (i.e., scan for NUL byte). The dynamic array length will be set to strlen(S) + 1.
+ *
+ * Args:
+ *     S: The dynamic array with a NUL terminated string, cannot be NULL.
+ *
+ * Return:
+ *      The calculated strlen() value.
+ */
+#define darr_strlen_fixup(S)                                                                       \
+       ({                                                                                         \
+               _darr_len(S) = strlen(S) + 1;                                                      \
+               darr_strlen(S);                                                                    \
+       })
+
 /**
  * darr_vsprintf() - vsprintf into a new dynamic array.
  *
index 87f9e3e5642cdf2350ff8fa98198115ec2ef426e..be319db1c131d194b3b2b08ae50afe36217290d4 100644 (file)
@@ -48,6 +48,7 @@
  * [x] - darr_strdup
  * [x] - darr_strdup_cap
  * [x] - darr_strlen
+ * [x] - darr_strlen_fixup
  * [x] - darr_strnul
  * [ ] - darr_vsprintf
  */
@@ -406,6 +407,9 @@ static void test_string(void)
        assert(!strcmp(da1, "0123456789: DEADBEEF"));
        assert(darr_strlen(da1) == 20);
        assert(darr_cap(da1) == 128);
+
+       da1[5] = 0;
+       assert(darr_strlen_fixup(da1) == 5);
        darr_free(da1);
 
        da1 = darr_sprintf("0123456789: %08x", 0xDEADBEEF);