From a5b4a9076bb7a063338f55edcfcff46651dbc533 Mon Sep 17 00:00:00 2001 From: Sascha Hauer Date: Fri, 30 Oct 2020 09:20:27 +0100 Subject: lib: Add match_string() Signed-off-by: Sascha Hauer --- include/linux/string.h | 2 ++ lib/string.c | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/include/linux/string.h b/include/linux/string.h index 2b699957e8..e7f471b139 100644 --- a/include/linux/string.h +++ b/include/linux/string.h @@ -135,4 +135,6 @@ static inline void *kmemdup(const void *src, size_t len, gfp_t gfp) extern int kstrtobool(const char *s, bool *res); +int match_string(const char * const *array, size_t n, const char *string); + #endif /* _LINUX_STRING_H_ */ diff --git a/lib/string.c b/lib/string.c index 003070fa53..2d0a99eab7 100644 --- a/lib/string.c +++ b/lib/string.c @@ -852,3 +852,37 @@ int strtobool(const char *str, int *val) return -EINVAL; } EXPORT_SYMBOL(strtobool); + +/** + * match_string - matches given string in an array + * @array: array of strings + * @n: number of strings in the array or -1 for NULL terminated arrays + * @string: string to match with + * + * This routine will look for a string in an array of strings up to the + * n-th element in the array or until the first NULL element. + * + * Historically the value of -1 for @n, was used to search in arrays that + * are NULL terminated. However, the function does not make a distinction + * when finishing the search: either @n elements have been compared OR + * the first NULL element was found. + * + * Return: + * index of a @string in the @array if matches, or %-EINVAL otherwise. + */ +int match_string(const char * const *array, size_t n, const char *string) +{ + int index; + const char *item; + + for (index = 0; index < n; index++) { + item = array[index]; + if (!item) + break; + if (!strcmp(item, string)) + return index; + } + + return -EINVAL; +} +EXPORT_SYMBOL(match_string); -- cgit v1.2.3