diff --git a/src/util-strings.c b/src/util-strings.c index 9a6a15e0..c56fc1c3 100644 --- a/src/util-strings.c +++ b/src/util-strings.c @@ -311,6 +311,27 @@ strv_find(char **strv, const char *needle, size_t *index_out) return false; } +bool +strv_find_substring(char **strv, const char *needle, size_t *index_out) +{ + if (!strv || !needle) + return false; + + size_t index = 0; + char **s = strv; + while (*s != NULL) { + if (strstr(*s, needle)) { + if (index_out) + *index_out = index; + return true; + } + s++; + index++; + } + + return false; +} + /** * Return a pointer to the basename within filename. * If the filename the empty string or a directory (i.e. the last char of diff --git a/src/util-strings.h b/src/util-strings.h index 069d554c..abe1fb69 100644 --- a/src/util-strings.h +++ b/src/util-strings.h @@ -299,6 +299,7 @@ __attribute__ ((format (printf, 2, 0))) char **strv_append_vprintf(char **strv, const char *fmt, va_list args); bool strv_find(char **strv, const char *needle, size_t *index_out); +bool strv_find_substring(char **strv, const char *needle, size_t *index_out); typedef int (*strv_foreach_callback_t)(const char *str, size_t index, void *data); int strv_for_each(const char **strv, strv_foreach_callback_t func, void *data); diff --git a/test/test-utils.c b/test/test-utils.c index 0c32ad4f..2c5e0d42 100644 --- a/test/test-utils.c +++ b/test/test-utils.c @@ -1328,6 +1328,50 @@ START_TEST(strv_find_test) } END_TEST +START_TEST(strv_find_substring_test) +{ + char *strv[] = {"a", "bc", "cccc", NULL}; + + bool rc; + size_t index; + + rc = strv_find_substring(strv, "a", &index); + litest_assert(rc); + litest_assert_int_eq(index, 0U); + + rc = strv_find_substring(strv, "b", &index); + litest_assert(rc); + litest_assert_int_eq(index, 1U); + + rc = strv_find_substring(strv, "c", &index); + litest_assert(rc); + litest_assert_int_eq(index, 1U); + + rc = strv_find_substring(strv, "a", NULL); + litest_assert(rc); + + index = 0xffff; + rc = strv_find_substring(strv, "d", &index); + litest_assert(!rc); + litest_assert_int_eq(index, 0xffffU); + + rc = strv_find_substring(strv, "d", NULL); + litest_assert(!rc); + + rc = strv_find_substring(NULL, "a", &index); + litest_assert(!rc); + litest_assert_int_eq(index, 0xffffU); + + rc = strv_find_substring(NULL, NULL, &index); + litest_assert(!rc); + litest_assert_int_eq(index, 0xffffU); + + rc = strv_find_substring(strv, NULL, &index); + litest_assert(!rc); + litest_assert_int_eq(index, 0xffffU); +} +END_TEST + START_TEST(double_array_from_string_test) { struct double_array_from_string_test { @@ -2297,6 +2341,7 @@ int main(void) ADD_TEST(strv_for_each_test); ADD_TEST(strv_append_test); ADD_TEST(strv_find_test); + ADD_TEST(strv_find_substring_test); ADD_TEST(double_array_from_string_test); ADD_TEST(strargv_test); ADD_TEST(kvsplit_double_test);