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.
This commit is contained in:
Barnabás Pőcze 2021-06-25 17:29:44 +02:00
parent cb6dbd165a
commit e082e64c87

View file

@ -291,6 +291,40 @@ static inline bool spa_atod(const char *str, double *val)
return true; 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)))
/** /**
* \} * \}
*/ */