summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSascha Hauer <s.hauer@pengutronix.de>2020-10-30 09:20:27 +0100
committerSascha Hauer <s.hauer@pengutronix.de>2020-11-09 23:04:01 +0100
commita5b4a9076bb7a063338f55edcfcff46651dbc533 (patch)
treec5c4d052044fed7c0b7edc52821ddf750fc60027
parenta54dfb195a701f85a44c0a6f2c3a695a6fdf004a (diff)
downloadbarebox-a5b4a9076bb7a063338f55edcfcff46651dbc533.tar.gz
barebox-a5b4a9076bb7a063338f55edcfcff46651dbc533.tar.xz
lib: Add match_string()
Signed-off-by: Sascha Hauer <s.hauer@pengutronix.de>
-rw-r--r--include/linux/string.h2
-rw-r--r--lib/string.c34
2 files changed, 36 insertions, 0 deletions
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);