From e082e64c870cd4cbf735cc847851a9e95892fbbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Barnab=C3=A1s=20P=C5=91cze?= Date: Fri, 25 Jun 2021 17:29:44 +0200 Subject: [PATCH] spa: utils: string: introduce spa_str_find() spa_str_find() may be used to check whether a string exists in an array of strings (subject to an arbitrary three-way comparator) and optinally retrieve its index. --- spa/include/spa/utils/string.h | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/spa/include/spa/utils/string.h b/spa/include/spa/utils/string.h index a41d07936..5c8a4627f 100644 --- a/spa/include/spa/utils/string.h +++ b/spa/include/spa/utils/string.h @@ -291,6 +291,40 @@ static inline bool spa_atod(const char *str, double *val) return true; } +/** + * Find \a needle in the \a haystack array of \a n strings. + * + * \param haystack an array of \a n strings + * \param n number of strings in \a haystack + * \param cmp a three-way comparator + * \param index pointer to save the index into if \a needle is found, + * may be NULL; it is not modified if \a needle is not found + * + * \return true if \a needle is found, false otherwise + * + * \since 0.3.31 + */ +static inline bool spa_find_str(const char * const haystack[], size_t n, + const char *needle, + int (*cmp)(const char *, const char *), + size_t *index) +{ + for (size_t i = 0; i < n; i++) { + if (cmp(needle, haystack[i]) != 0) + continue; + + if (index != NULL) + *index = i; + + return true; + } + + return false; +} + +#define spa_find_str_arr(haystack, needle, cmp, index) \ + (spa_find_str((haystack), SPA_N_ELEMENTS(haystack), (needle), (cmp), (index))) + /** * \} */