From: Sebastian Harl Date: Sat, 10 Sep 2016 23:03:00 +0000 (-0400) Subject: utils strings: Add stringv_append_if_missing(). X-Git-Url: https://git.tokkee.org/?a=commitdiff_plain;h=01cf7d5f4392df0933e56a54b1ff607d2dd2ed13;p=sysdb.git utils strings: Add stringv_append_if_missing(). --- diff --git a/src/include/utils/strings.h b/src/include/utils/strings.h index 24f7fc1..4666631 100644 --- a/src/include/utils/strings.h +++ b/src/include/utils/strings.h @@ -58,6 +58,8 @@ stringv_copy(char ***dst, size_t *dst_len, */ int stringv_append(char ***s, size_t *s_len, const char *elem); +int +stringv_append_if_missing(char ***s, size_t *s_len, const char *elem); /* * stringv_free: diff --git a/src/utils/strings.c b/src/utils/strings.c index b6a49e1..d7668f0 100644 --- a/src/utils/strings.c +++ b/src/utils/strings.c @@ -114,6 +114,21 @@ stringv_append(char ***s, size_t *s_len, const char *elem) return 0; } /* stringv_append */ +int +stringv_append_if_missing(char ***s, size_t *s_len, const char *elem) +{ + size_t i; + + if ((! s) || (! s_len)) + return -1; + + for (i = 0; i < *s_len; i++) + if (! strcmp((*s)[i], elem)) + return 0; + + return stringv_append(s, s_len, elem); +} /* stringv_append_if_missing */ + void stringv_free(char ***s, size_t *s_len) { diff --git a/t/unit/utils/strings_test.c b/t/unit/utils/strings_test.c index 326a073..3442b50 100644 --- a/t/unit/utils/strings_test.c +++ b/t/unit/utils/strings_test.c @@ -44,7 +44,7 @@ START_TEST(test_stringv) char **dst = NULL; size_t dst_len = 0; - char *src[] = { "a", "b", "c" }; + char *src[] = { "a", "b", "c", "d", "e" }; size_t src_len = SDB_STATIC_ARRAY_LEN(src); size_t i; @@ -74,12 +74,24 @@ START_TEST(test_stringv) char buf1[256], buf2[256]; size_t j; - check = stringv_append(&dst, &dst_len, src[i]); + if (i < 3) { + check = stringv_append(&dst, &dst_len, src[i]); + fail_unless(check == 0, + "stringv_append(, , '%s') = %d; expected: 0", + src[i], check); + fail_unless((dst != NULL) && (dst_len == i + 1), + "stringv_append(, , '%s') produced s=%p, len=%zu; " + "expected: s=, len=%zu", src[i], dst, dst_len, i + 1); + } + + /* A no-op for the first three iterations but then it appends the + * other elements. */ + check = stringv_append_if_missing(&dst, &dst_len, src[i]); fail_unless(check == 0, - "stringv_append(, , '%s') = %d; expected: 0", + "stringv_append_if_missing(, , '%s') = %d; expected: 0", src[i], check); fail_unless((dst != NULL) && (dst_len == i + 1), - "stringv_append(, , '%s') produced s=%p, len=%zu; " + "stringv_append_if_missing(, , '%s') produced s=%p, len=%zu; " "expected: s=, len=%zu", src[i], dst, dst_len, i + 1); for (j = 0; j <= i; j++)